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

local Compat = _G.LIDCOUNCIL_Compat

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

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

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

-- JOIN acknowledgement retries are deliberately modeled independently from
-- the live timer.  The deterministic transport suite exercises these helpers
-- without opening a session, while the runtime uses the same token ownership,
-- backoff, and queue/lockdown gates below.
INTERNAL_API.LIDCOUNCIL_ResolveJoinAckRetryDelay_Impl = function(successfulAttempts, opts)
  opts = type(opts) == "table" and opts or {}
  local attempts = math.max(1, math.floor(tonumber(successfulAttempts) or 1))
  local maxAttempts = math.max(1, math.floor(tonumber(opts.maxAttempts) or 5))
  if attempts >= maxAttempts then
    return math.max(1, tonumber(opts.finalWaitSeconds) or 12)
  end
  local delays = type(opts.retryDelaysSeconds) == "table" and opts.retryDelaysSeconds or {}
  local fallbackDelay = math.max(1, tonumber(opts.fallbackDelaySeconds) or 10)
  return math.max(1, tonumber(delays[attempts]) or fallbackDelay)
end

INTERNAL_API.LIDCOUNCIL_ArmJoinAckRetryTimer_Impl = function(state, now, delaySeconds, replaceExisting)
  if type(state) ~= "table" then
    return false, 0, 0
  end
  if state.retryTimerArmed == true and replaceExisting ~= true then
    return false,
      math.max(0, tonumber(state.retryTimerToken) or 0),
      math.max(0, tonumber(state.retryTimerDueAt) or 0)
  end
  state.retryTimerToken = math.max(0, tonumber(state.retryTimerToken) or 0) + 1
  state.retryTimerArmed = true
  state.retryTimerDueAt = math.max(0, tonumber(now) or 0) + math.max(0, tonumber(delaySeconds) or 0)
  return true, state.retryTimerToken, state.retryTimerDueAt
end

INTERNAL_API.LIDCOUNCIL_ConsumeJoinAckRetryTimer_Impl = function(state, token)
  if type(state) ~= "table"
    or state.retryTimerArmed ~= true
    or math.max(0, tonumber(state.retryTimerToken) or 0) ~= math.max(0, tonumber(token) or 0)
  then
    return false
  end
  state.retryTimerArmed = false
  state.retryTimerDueAt = 0
  return true
end

INTERNAL_API.LIDCOUNCIL_InvalidateJoinAckRetryTimer_Impl = function(state)
  if type(state) ~= "table" then
    return 0
  end
  state.retryTimerToken = math.max(0, tonumber(state.retryTimerToken) or 0) + 1
  state.retryTimerArmed = false
  state.retryTimerDueAt = 0
  return state.retryTimerToken
end

INTERNAL_API.LIDCOUNCIL_UpdateJoinAckBlockedDeadline_Impl = function(state, now, blocked)
  if type(state) ~= "table" then
    return 0
  end
  local currentTime = math.max(0, tonumber(now) or 0)
  local blockedSince = math.max(0, tonumber(state.retryBlockedSince) or 0)
  if blocked == true then
    if blockedSince <= 0 then
      state.retryBlockedSince = currentTime
    end
    return 0
  end
  if blockedSince <= 0 then
    return 0
  end
  local blockedSeconds = math.max(0, currentTime - blockedSince)
  state.retryBlockedSince = 0
  state.retryBlockedSeconds = math.max(0, tonumber(state.retryBlockedSeconds) or 0) + blockedSeconds
  if math.max(0, tonumber(state.hardDeadlineAt) or 0) > 0 then
    state.hardDeadlineAt = math.max(0, tonumber(state.hardDeadlineAt) or 0) + blockedSeconds
  end
  return blockedSeconds
end

INTERNAL_API.LIDCOUNCIL_ResolvePendingJoinRetryAction_Impl = function(state, queueStatus, now, opts)
  state = type(state) == "table" and state or {}
  queueStatus = type(queueStatus) == "table" and queueStatus or {}
  opts = type(opts) == "table" and opts or {}
  local currentTime = math.max(0, tonumber(now) or 0)
  if state.confirmed == true then
    return { action = "stop", delaySeconds = 0 }
  end
  if state.state == "TIMED_OUT" then
    return { action = "late_ack_grace", delaySeconds = 0 }
  end
  local cooldownRemaining = math.max(0, tonumber(queueStatus.globalThrottleCooldownRemaining) or 0)
  if queueStatus.chatLockdownActive == true or cooldownRemaining > 0 then
    return {
      action = "wait_blocked",
      delaySeconds = math.max(
        math.max(1, tonumber(opts.blockedPollSeconds) or 1),
        cooldownRemaining
      ),
    }
  end
  local byKind = type(queueStatus.byKind) == "table" and queueStatus.byKind or {}
  if math.max(0, tonumber(byKind.JOIN) or 0) > 0 then
    return {
      action = "wait_queued",
      delaySeconds = math.max(0.25, tonumber(opts.queuePollSeconds) or 1),
    }
  end
  local hardDeadlineAt = math.max(0, tonumber(state.hardDeadlineAt) or 0)
  if hardDeadlineAt > 0 and currentTime >= hardDeadlineAt then
    return { action = "timeout", delaySeconds = 0, reason = "hard_deadline" }
  end
  local attempts = math.max(0, tonumber(state.attempts) or 0)
  local maxAttempts = math.max(1, math.floor(tonumber(opts.maxAttempts) or 5))
  if attempts >= maxAttempts then
    return { action = "timeout", delaySeconds = 0, reason = "attempts_exhausted" }
  end
  return { action = "queue_retry", delaySeconds = 0 }
end

INTERNAL_API.LIDCOUNCIL_ResolveInviteReceiptAction_Impl = function(state, queueStatus, opts)
  state = type(state) == "table" and state or {}
  queueStatus = type(queueStatus) == "table" and queueStatus or {}
  opts = type(opts) == "table" and opts or {}
  local deliveryState = string.upper(tostring(state.state or ""))
  local cooldownRemaining = math.max(0, tonumber(queueStatus.globalThrottleCooldownRemaining) or 0)
  if queueStatus.chatLockdownActive == true or cooldownRemaining > 0 then
    return {
      action = "wait_blocked",
      delaySeconds = math.max(
        math.max(0.25, tonumber(opts.blockedPollSeconds) or 1),
        cooldownRemaining
      ),
    }
  end
  local byKind = type(queueStatus.byKind) == "table" and queueStatus.byKind or {}
  if deliveryState ~= "AWAITING_RECEIPT" and math.max(0, tonumber(byKind.START) or 0) > 0 then
    return {
      action = "wait_queued",
      delaySeconds = math.max(0.25, tonumber(opts.queuePollSeconds) or 1),
    }
  end
  if deliveryState == "AWAITING_RECEIPT"
    and math.max(0, tonumber(state.attempts) or 0)
      >= math.max(1, math.floor(tonumber(opts.maxAttempts) or 2))
  then
    return { action = "timeout", delaySeconds = 0 }
  end
  return { action = "queue_retry", delaySeconds = 0 }
end

INTERNAL_API.LIDCOUNCIL_ShouldSuppressStableMemberPublication_Impl = function(
  recentSignature,
  nextSignature,
  allowIdenticalRepeat
)
  local recent = tostring(recentSignature or "")
  local incoming = tostring(nextSignature or "")
  return allowIdenticalRepeat ~= true
    and recent ~= ""
    and incoming ~= ""
    and recent == incoming
end

INTERNAL_API.LIDCOUNCIL_BuildReadinessPublicationOptions_Impl = function(opts)
  opts = type(opts) == "table" and opts or {}
  return {
    forceImmediate = true,
    suppressCheckpoint = true,
    -- An explicit operator refresh is also a delivery recovery action. The
    -- host may already have recorded the correct matrix even when a member
    -- missed that compact publication, so this one path must be resendable.
    allowIdenticalRepeat = opts.manualRefresh == true,
  }
end

INTERNAL_API.LIDCOUNCIL_AggregateHostMemberArchiveState_Impl = function(matrix)
  matrix = type(matrix) == "table" and matrix or {}
  local hasPending = false
  local hasValidating = false
  local hasStale = false
  for _, scopeName in ipairs({ "lootList", "itemHistory", "sessionHistory", "funAwards" }) do
    local state = string.upper(tostring(matrix[scopeName] or "PENDING"))
    if state == "REVIEW" then
      return "REVIEW"
    elseif state == "PENDING" then
      hasPending = true
    elseif state == "VALIDATING" then
      hasValidating = true
    elseif state == "STALE" then
      hasStale = true
    elseif state ~= "READY" then
      hasPending = true
    end
  end
  if hasPending then
    return "PENDING"
  end
  if hasValidating then
    return "VALIDATING"
  end
  if hasStale then
    return "STALE"
  end
  return "READY"
end

INTERNAL_API.LIDCOUNCIL_ResolveHostMemberP2ProofDiagnostics_Impl = function(input)
  input = type(input) == "table" and input or {}

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

  local function same(left, right)
    local resolvedLeft = string.lower(clean(left))
    local resolvedRight = string.lower(clean(right))
    return resolvedLeft ~= "" and resolvedLeft == resolvedRight
  end

  local function result(code, label, detail, state)
    return {
      code = code,
      label = label,
      detail = clean(detail),
      state = state or "PENDING",
    }
  end

  local matrixState = string.upper(clean(input.matrixState))
  local activeSessionId = clean(input.activeSessionId)
  local statusSessionId = clean(input.statusSessionId)
  local proofSessionId = clean(input.proofSessionId)
  local previousProofSessionId = clean(input.previousProofSessionId)
  local localProfileId = clean(input.localProfileId)
  local memberProfileId = clean(input.memberProfileId)
  local localSessionChecksum = clean(input.localSessionChecksum)
  local memberSessionChecksum = clean(input.memberSessionChecksum)

  if input.isHostRow == true then
    return result("HOST_REFERENCE", "Host reference row", "", "READY")
  end
  if matrixState == "READY" then
    return result("ACCEPTED", "Current-lobby proof accepted", "", "READY")
  end
  if activeSessionId == "" then
    return result("NO_ACTIVE_SESSION", "No active lobby proof context")
  end
  if statusSessionId ~= "" and not same(statusSessionId, activeSessionId) then
    return result(
      "STATUS_SESSION_MISMATCH",
      "Status belongs to a previous lobby",
      "Expected " .. activeSessionId .. "; status has " .. statusSessionId
    )
  end

  -- A member client receives the host's compact authoritative status matrix,
  -- but not the host-only immutable proof object. Explain that boundary rather
  -- than guessing that a local checksum is the proof the host evaluated.
  if input.proofInspectable ~= true then
    if matrixState == "REVIEW" then
      if localProfileId == "" then
        return result("LOCAL_PROFILE_UNKNOWN", "Local profile identity is unavailable", "", "REVIEW")
      end
      if memberProfileId == "" then
        return result("MEMBER_PROFILE_UNKNOWN", "Member profile identity is unavailable", "", "REVIEW")
      end
      if not same(localProfileId, memberProfileId) then
        return result("PROFILE_MISMATCH", "Profile identity differs", "", "REVIEW")
      end
      if localSessionChecksum == "" then
        return result("LOCAL_CHECKSUM_MISSING", "Host current-session checksum is unavailable", "", "REVIEW")
      end
      if memberSessionChecksum == "" then
        return result("MEMBER_CHECKSUM_MISSING", "Member current-session checksum is unavailable", "", "REVIEW")
      end
      if not same(localSessionChecksum, memberSessionChecksum) then
        return result("CHECKSUM_MISMATCH", "Current-session checksum differs", "", "REVIEW")
      end
    end
    return result(
      "HOST_VALIDATION_PENDING",
      "Host validation is pending",
      matrixState ~= "" and ("Host status: " .. matrixState) or "Host has not published a P2 result yet",
      matrixState == "REVIEW" and "REVIEW" or "VALIDATING"
    )
  end

  if input.proofAvailable ~= true then
    if previousProofSessionId ~= "" and not same(previousProofSessionId, activeSessionId) then
      return result(
        "PROOF_SESSION_MISMATCH",
        "Proof belongs to a previous lobby",
        "Expected " .. activeSessionId .. "; proof has " .. previousProofSessionId
      )
    end
    return result("PROOF_MISSING", "Current-lobby proof has not arrived")
  end
  if proofSessionId == "" or not same(proofSessionId, activeSessionId) then
    return result(
      "PROOF_SESSION_MISMATCH",
      proofSessionId == "" and "Proof has no lobby identity" or "Proof belongs to a previous lobby",
      proofSessionId ~= "" and ("Expected " .. activeSessionId .. "; proof has " .. proofSessionId) or ""
    )
  end
  if clean(input.expectedMemberKey) ~= "" and not same(input.expectedMemberKey, input.proofMemberKey) then
    return result("PROOF_MEMBER_MISMATCH", "Proof belongs to a different member")
  end
  if localProfileId == "" then
    return result("LOCAL_PROFILE_UNKNOWN", "Host profile identity is unavailable", "", "REVIEW")
  end
  if memberProfileId == "" then
    return result("MEMBER_PROFILE_UNKNOWN", "Member profile identity is unavailable", "", "REVIEW")
  end
  if not same(localProfileId, memberProfileId) then
    return result("PROFILE_MISMATCH", "Profile identity differs", "", "REVIEW")
  end
  if math.max(0, tonumber(input.proofLastSyncAt) or 0) <= 0 then
    return result("PROOF_INCOMPLETE", "Proof has no completed sync timestamp")
  end
  if clean(input.proofAddonVersion) == "" then
    return result("PROOF_INCOMPLETE", "Proof has no addon version", "", "REVIEW")
  end
  if localSessionChecksum == "" then
    return result("LOCAL_CHECKSUM_MISSING", "Host current-session checksum is unavailable", "", "REVIEW")
  end
  if memberSessionChecksum == "" then
    return result("MEMBER_CHECKSUM_MISSING", "Member current-session checksum is unavailable", "", "REVIEW")
  end
  if not same(localSessionChecksum, memberSessionChecksum) then
    return result("CHECKSUM_MISMATCH", "Current-session checksum differs", "", "REVIEW")
  end
  return result(
    "STATUS_PUBLICATION_PENDING",
    "Checksums match; status publication is pending",
    matrixState ~= "" and ("Host status: " .. matrixState) or ""
  )
end

INTERNAL_API.LIDCOUNCIL_SelectLatestCompletedSessionRecord_Impl = function(sessions, activeSessionId)
  local resolvedActiveSessionId = tostring(activeSessionId or "")
  local selected, selectedIndex
  local selectedEndedAt, selectedStartedAt, selectedId = -1, -1, ""
  for index, session in ipairs(type(sessions) == "table" and sessions or {}) do
    if type(session) == "table" then
      local sessionId = tostring(session.id or "")
      local status = string.upper(tostring(session.status or ""))
      local completed = status ~= "PREPARING" and status ~= "ACTIVE"
        and (tonumber(session.endedAt) ~= nil or status == "FINISHED")
      if completed and sessionId ~= "" and sessionId ~= resolvedActiveSessionId then
        local endedAt = tonumber(session.endedAt) or -1
        local startedAt = tonumber(session.startedAt) or -1
        local normalizedId = string.lower(sessionId)
        if selected == nil
          or endedAt > selectedEndedAt
          or (endedAt == selectedEndedAt and startedAt > selectedStartedAt)
          or (endedAt == selectedEndedAt and startedAt == selectedStartedAt and normalizedId > selectedId)
        then
          selected = session
          selectedIndex = index
          selectedEndedAt = endedAt
          selectedStartedAt = startedAt
          selectedId = normalizedId
        end
      end
    end
  end
  return selected, selectedIndex
end

INTERNAL_API.LIDCOUNCIL_ResolveLatestSessionHistoryCatchupAttempt_Impl = function(input)
  input = type(input) == "table" and input or {}
  local expectedChecksum = tostring(input.expectedChecksum or "")
  local memberChecksum = tostring(input.memberChecksum or "")
  if expectedChecksum == "" or memberChecksum == "" then
    return "missing_proof"
  end
  if string.lower(expectedChecksum) == string.lower(memberChecksum) then
    return "aligned"
  end
  if tostring(input.latestSessionId or "") == "" then
    return "no_completed_session"
  end
  local attempts = math.max(0, tonumber(input.attempts) or 0)
  if input.startRetry == true then
    return attempts < 2 and "queue_start_retry" or "suppress_exhausted"
  end
  return attempts == 0 and "queue_join" or "suppress_duplicate"
end

INTERNAL_API.LIDCOUNCIL_ShouldPrimeReplicaProofWork_Impl = function(becameSharedReplica, statusMatrix)
  return becameSharedReplica == true
    and not (
      type(statusMatrix) == "table"
      and statusMatrix.p1 == "READY"
      and statusMatrix.p2 == "READY"
    )
end

INTERNAL_API.LIDCOUNCIL_ShouldPublishProfileDeltaStateProof_Impl = function(domain)
  local resolvedDomain = tostring(domain or "")
  resolvedDomain = resolvedDomain:gsub("^%s+", "")
  resolvedDomain = resolvedDomain:gsub("%s+$", "")
  return string.lower(resolvedDomain) == "permissions"
end

INTERNAL_API.LIDCOUNCIL_BuildAlignedReplicaArchivePlan_Impl = function(input)
  input = type(input) == "table" and input or {}
  local function clean(value)
    local text = tostring(value or "")
    text = text:gsub("^%s+", "")
    text = text:gsub("%s+$", "")
    return text
  end
  local function appendUnique(list, lookup, value)
    local resolved = clean(value)
    local key = string.lower(resolved)
    if resolved ~= "" and not lookup[key] then
      lookup[key] = true
      list[#list + 1] = resolved
    end
  end
  local function parentDomain(subdomain)
    local resolved = string.lower(clean(subdomain))
    if resolved == "lls" or resolved == "lrsr" or resolved == "lrsv"
      or resolved:find("^llg:", 1, false) or resolved:find("^llr:", 1, false)
      or resolved:find("^lmr:", 1, false) or resolved:find("^lre:", 1, false)
      or resolved:find("^lve:", 1, false)
    then
      return "loot"
    end
    if resolved:find("^ssr:", 1, false) or resolved:find("^slb:", 1, false) then
      return "session"
    end
    return ""
  end

  local scopeInputs = type(input.scopes) == "table" and input.scopes or {}
  local localProfileId = clean(input.localProfileId)
  local memberProfileId = clean(input.memberProfileId)
  local requiredScopeLookup = {
    lootList = false,
    itemHistory = false,
    sessionHistory = false,
    funAwards = false,
  }
  local completeFamilyProof = true
  for _, scopeInput in ipairs(scopeInputs) do
    local scope = clean(type(scopeInput) == "table" and scopeInput.scope or "")
    if requiredScopeLookup[scope] ~= nil then
      requiredScopeLookup[scope] = clean(scopeInput.memberChecksum) ~= ""
    end
  end
  for _, present in pairs(requiredScopeLookup) do
    if present ~= true then
      completeFamilyProof = false
      break
    end
  end
  local canReuseExistingReplica = input.existingReplica == true
    and localProfileId ~= ""
    and memberProfileId ~= ""
    and string.lower(localProfileId) == string.lower(memberProfileId)
    and completeFamilyProof
  local plan = {
    canReuseExistingReplica = canReuseExistingReplica,
    completeFamilyProof = completeFamilyProof,
    differingScopes = {},
    preciseDomains = {},
    preciseSubdomains = {},
    broadArchiveScopes = {},
    requirePreciseProof = false,
    preciseProofReady = input.preciseProofReady == true,
    broadArchiveFallbackAllowed = not canReuseExistingReplica,
    fullSnapshotAllowed = not canReuseExistingReplica,
  }
  local differingLookup = {}
  local preciseDomainLookup = {}
  local broadScopeLookup = {}
  for _, scopeInput in ipairs(scopeInputs) do
    local scope = clean(type(scopeInput) == "table" and scopeInput.scope or "")
    if scope ~= "" and type(scopeInput) == "table" and scopeInput.needsRepair == true then
      appendUnique(plan.differingScopes, differingLookup, scope)
      if canReuseExistingReplica then
        appendUnique(
          plan.preciseDomains,
          preciseDomainLookup,
          (scope == "lootList" or scope == "funAwards") and "loot" or "session"
        )
      else
        appendUnique(plan.broadArchiveScopes, broadScopeLookup, scope)
      end
    end
  end
  plan.requirePreciseProof = canReuseExistingReplica and #plan.preciseDomains > 0

  if plan.requirePreciseProof and plan.preciseProofReady then
    local requestedDomainLookup = {}
    local preciseSubdomainLookup = {}
    for _, domain in ipairs(plan.preciseDomains) do
      requestedDomainLookup[string.lower(clean(domain))] = true
    end
    for _, subdomain in ipairs(type(input.preciseSubdomains) == "table" and input.preciseSubdomains or {}) do
      if requestedDomainLookup[parentDomain(subdomain)] then
        appendUnique(plan.preciseSubdomains, preciseSubdomainLookup, subdomain)
      end
    end
  end
  plan.awaitingPreciseProof = plan.requirePreciseProof and not plan.preciseProofReady
  return plan
end

INTERNAL_API.LIDCOUNCIL_ResolveAlignedReplicaPreciseProofAction_Impl = function(proofReady, completedAttempts, maxAttempts)
  local attempts = math.max(0, tonumber(completedAttempts) or 0)
  local limit = math.max(1, tonumber(maxAttempts) or 4)
  if proofReady == true then
    return {
      action = "apply_precise",
      attempts = attempts,
      terminal = false,
      broadArchiveFallbackAllowed = false,
      fullSnapshotAllowed = false,
    }
  end
  attempts = attempts + 1
  return {
    action = attempts < limit and "retry_precise_proof" or "fail_closed",
    attempts = attempts,
    terminal = attempts >= limit,
    broadArchiveFallbackAllowed = false,
    fullSnapshotAllowed = false,
  }
end

INTERNAL_API.LIDCOUNCIL_ResolveJoinManifestProofPoll_Impl = function(input)
  input = type(input) == "table" and input or {}
  local attempts = math.max(0, tonumber(input.completedAttempts) or 0)
  if input.proofReady == true then
    return INTERNAL_API.LIDCOUNCIL_ResolveAlignedReplicaPreciseProofAction_Impl(
      true,
      attempts,
      input.maxAttempts
    )
  end

  local requestState = string.lower(tostring(input.requestState or ""))
  requestState = requestState:gsub("^%s+", "")
  requestState = requestState:gsub("%s+$", "")
  if requestState == "waiting" then
    return {
      action = "wait_for_precise_proof",
      attempts = attempts,
      terminal = false,
      broadArchiveFallbackAllowed = false,
      fullSnapshotAllowed = false,
    }
  end

  return INTERNAL_API.LIDCOUNCIL_ResolveAlignedReplicaPreciseProofAction_Impl(
    false,
    attempts,
    input.maxAttempts
  )
end

INTERNAL_API.LIDCOUNCIL_BuildJoinManifestProofIdentity_Impl = function(input)
  input = type(input) == "table" and input or {}

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

  local function pack(value, lower)
    local text = clean(value)
    if lower then
      text = string.lower(text)
    end
    return tostring(#text) .. ":" .. text
  end

  local function scopeSignature(values)
    local ordered = {}
    local included = {}
    for _, value in ipairs(type(values) == "table" and values or {}) do
      local resolved = string.lower(clean(value))
      if resolved ~= "" and not included[resolved] then
        included[resolved] = true
        ordered[#ordered + 1] = resolved
      end
    end
    table.sort(ordered)
    return table.concat(ordered, "\30")
  end

  local sessionId = clean(input.sessionId)
  local memberKey = clean(input.memberKey)
  local profileRevision = clean(input.profileRevision)
  local domainSignature = scopeSignature(input.domains)
  local subdomainSignature = scopeSignature(input.subdomains)
  if sessionId == "" or memberKey == "" or profileRevision == ""
    or (domainSignature == "" and subdomainSignature == "")
  then
    return ""
  end

  return table.concat({
    pack(sessionId, true),
    pack(memberKey, true),
    pack(profileRevision, false),
    pack(domainSignature, false),
    pack(subdomainSignature, false),
  }, "|")
end

INTERNAL_API.LIDCOUNCIL_ResolveJoinManifestProofRequest_Impl = function(input)
  input = type(input) == "table" and input or {}
  local identity = tostring(input.proofIdentity or "")
  local pendingState = type(input.pendingState) == "table" and input.pendingState or nil
  local terminalState = type(input.terminalState) == "table" and input.terminalState or nil
  local pendingIdentity = tostring(type(pendingState) == "table" and pendingState.proofIdentity or "")
  local pendingToken = tostring(type(pendingState) == "table" and pendingState.token or "")
  local terminalIdentity = tostring(type(terminalState) == "table" and terminalState.proofIdentity or "")

  if identity == "" then
    return {
      action = "invalid",
      token = "",
      terminal = false,
    }
  end
  if input.manualRearm == true then
    return {
      action = "start_new",
      token = "",
      terminal = false,
      manualRearm = true,
    }
  end
  if pendingIdentity == identity and pendingToken ~= "" then
    return {
      action = "reuse_pending",
      token = pendingToken,
      terminal = false,
    }
  end
  if terminalIdentity == identity then
    return {
      action = "suppress_terminal",
      token = "",
      terminal = true,
    }
  end
  return {
    action = "start_new",
    token = "",
    terminal = false,
  }
end

INTERNAL_API.LIDCOUNCIL_IsJoinManifestPreciseProofReady_Impl = function(candidate, pendingToken, requiredDomains)
  if type(candidate) ~= "table"
    or candidate.preciseDetailLoaded ~= true
    or candidate.preciseResponseComplete ~= true
  then
    return false
  end

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

  local expectedToken = clean(pendingToken)
  if expectedToken == "" or clean(candidate.preciseRequestToken) ~= expectedToken then
    return false
  end

  local comparedDomains = {}
  for _, domain in ipairs(type(candidate.preciseScopeDomains) == "table" and candidate.preciseScopeDomains or {}) do
    local resolvedDomain = string.lower(clean(domain))
    if resolvedDomain ~= "" then
      comparedDomains[resolvedDomain] = true
    end
  end
  local requiredCount = 0
  for _, domain in ipairs(type(requiredDomains) == "table" and requiredDomains or {}) do
    local resolvedDomain = string.lower(clean(domain))
    if resolvedDomain ~= "" then
      requiredCount = requiredCount + 1
      if not comparedDomains[resolvedDomain] then
        return false
      end
    end
  end
  return requiredCount > 0
end

INTERNAL_API.LIDCOUNCIL_ResolveJoinManifestValidationState_Impl = function(pendingState, context)
  pendingState = type(pendingState) == "table" and pendingState or nil
  context = type(context) == "table" and context or {}
  if type(pendingState) ~= "table"
    or pendingState.kind ~= "join_manifest"
    or pendingState.requirePreciseProof ~= true
  then
    return nil
  end

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

  local function same(left, right)
    local resolvedLeft = string.lower(clean(left))
    local resolvedRight = string.lower(clean(right))
    return resolvedLeft ~= "" and resolvedLeft == resolvedRight
  end

  if clean(pendingState.token) == ""
    or not same(pendingState.sessionId, context.sessionId)
    or not same(pendingState.profileName, context.profileName)
    or not same(pendingState.memberKey, context.memberKey)
  then
    return nil
  end

  local expectedProfileId = clean(context.profileId)
  if expectedProfileId ~= "" and not same(pendingState.profileId, expectedProfileId) then
    return nil
  end
  local expectedMemberProfileId = clean(context.memberProfileId)
  local pendingMemberProfileId = clean(pendingState.memberProfileId)
  if expectedMemberProfileId ~= ""
    and pendingMemberProfileId ~= ""
    and not same(pendingMemberProfileId, expectedMemberProfileId)
  then
    return nil
  end

  local domains = {}
  local seenDomains = {}
  local pendingProofDomains = type(pendingState.proofDomains) == "table"
    and pendingState.proofDomains
    or pendingState.domains
  for _, domain in ipairs(type(pendingProofDomains) == "table" and pendingProofDomains or {}) do
    local resolvedDomain = string.lower(clean(domain))
    if resolvedDomain ~= "" and not seenDomains[resolvedDomain] then
      seenDomains[resolvedDomain] = true
      domains[#domains + 1] = resolvedDomain
    end
  end
  if #domains == 0 then
    return nil
  end

  return {
    state = "VALIDATING",
    token = clean(pendingState.token),
    domains = domains,
    attempts = math.max(0, tonumber(pendingState.preciseProofAttempts) or 0),
    maxAttempts = math.max(1, tonumber(pendingState.maxPreciseProofAttempts) or 4),
  }
end

INTERNAL_API.LIDCOUNCIL_ApplyJoinManifestValidationToStatusMatrix_Impl = function(matrix, validationState)
  if type(matrix) ~= "table"
    or type(validationState) ~= "table"
    or validationState.state ~= "VALIDATING"
  then
    return matrix
  end

  local validatingScopes = {}
  for _, domain in ipairs(type(validationState.domains) == "table" and validationState.domains or {}) do
    local resolvedDomain = string.lower(tostring(domain or ""))
    if resolvedDomain == "loot" then
      validatingScopes.lootList = true
      validatingScopes.funAwards = true
    elseif resolvedDomain == "session" then
      validatingScopes.itemHistory = true
      validatingScopes.sessionHistory = true
    end
  end
  for scopeName in pairs(validatingScopes) do
    if string.upper(tostring(matrix[scopeName] or "")) == "PENDING" then
      matrix[scopeName] = "VALIDATING"
    end
  end

  matrix.p3 = INTERNAL_API.LIDCOUNCIL_AggregateHostMemberArchiveState_Impl(matrix)
  return matrix
end

INTERNAL_API.LIDCOUNCIL_ResolveSessionFinalizationReceiptAction_Impl = function(missingCount, attempts, maxAttempts)
  if math.max(0, tonumber(missingCount) or 0) == 0 then
    return "complete"
  end
  if math.max(1, tonumber(attempts) or 1) < math.max(1, tonumber(maxAttempts) or 3) then
    return "retry"
  end
  return "defer_p3"
end

INTERNAL_API.LIDCOUNCIL_ResolveJoinedSessionRollOptions_Impl = function(
  localProfileOptions,
  inviteOptions,
  sharedProfileReady,
  normalizeOptions
)
  local source = nil
  local sourceKind = "pending_profile"
  if sharedProfileReady == true and type(localProfileOptions) == "table" and #localProfileOptions > 0 then
    source = localProfileOptions
    sourceKind = "local_profile"
  elseif type(inviteOptions) == "table" and #inviteOptions > 0 then
    source = inviteOptions
    sourceKind = "invite"
  end
  if type(source) ~= "table" then
    return {}, sourceKind
  end
  if type(normalizeOptions) == "function" then
    return normalizeOptions(source), sourceKind
  end
  local copy = {}
  for index, option in ipairs(source) do
    copy[index] = option
  end
  return copy, sourceKind
end

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

  local Print = deps.Print
  local TrimText = deps.TrimText
  local NormalizeCharacterKey = deps.NormalizeCharacterKey
  local FirstNonEmptyText = deps.FirstNonEmptyText
  local GetCharacterKey = deps.GetCharacterKey
  local GetActiveLootSession = deps.GetActiveLootSession
  local JoinLootSession = deps.JoinLootSession
  local UpsertLootSessionMember = deps.UpsertLootSessionMember
  local FinishLootSession = deps.FinishLootSession
  local SetLocalAutoPassEnabled = deps.SetLocalAutoPassEnabled
  local GetLootProfileRevisionSummary = deps.GetLootProfileRevisionSummary
  local IsCurrentGroupCharacter = deps.IsCurrentGroupCharacter
  local IsClaimedActorSenderMatch = deps.IsClaimedActorSenderMatch
  local IsJoinedSessionCharacter = deps.IsJoinedSessionCharacter
  local DoesActiveSessionMatch = deps.DoesActiveSessionMatch
  local SendComm = deps.SendComm
  local ResolveJoinedSessionRollOptions = INTERNAL_API.LIDCOUNCIL_ResolveJoinedSessionRollOptions_Impl
  local RecordProfileSyncDecision = deps.RecordProfileSyncDecision
  local PrepareProfileSnapshotTransfer = deps.PrepareProfileSnapshotTransfer
  local BuildPreparedProfileRepairTransfers = deps.BuildPreparedProfileRepairTransfers
  local profileSyncMetaOps = {
    getSubchecksumManifest = deps.GetLootProfileSubchecksumManifest,
    getSubdomainKeysForDomain = deps.GetLootProfileSubdomainKeysForDomain,
    getSubdomainParentDomain = deps.GetLootProfileSubdomainParentDomain,
    calculateStableChecksum = deps.CalculateStableChecksum,
    sendPatchManifest = deps.SendProfileSubdomainPatchManifest,
    sendSubchecksumRequests = deps.SendProfileSubchecksumRequests,
    getMemberSubchecksumFreshness = deps.GetMemberSubchecksumFreshness,
    sendLocalProfileStateToHost = deps.SendLocalProfileStateToHost,
    scheduleDelayedLocalProfileStateSend = deps.ScheduleDelayedLocalProfileStateSend,
    getActiveSyncCandidates = deps.GetActiveProfileSyncCandidates,
    delaySnapshotBatchForJoins = deps.DelayProfileSnapshotBatchForJoins,
    parsePayload = deps.ParsePayload,
    recordRepairHistory = deps.RecordRepairHistory,
    validateCommPayload = deps.ValidateCommPayload,
    recordOutboundPayloadReject = deps.RecordOutboundPayloadReject,
    markArchiveTransferState = deps.MarkArchiveTransferState,
    canRetryArchiveTransfer = deps.CanRetryArchiveTransfer,
    reconcileMemberArchiveTransactions = deps.ReconcileMemberArchiveTransactions,
  }
  profileSyncMetaOps.recentAutomaticHostRepairRequestStates = {}
  profileSyncMetaOps.normalizeSenderKey = type(deps.NormalizeSenderKey) == "function"
    and deps.NormalizeSenderKey
    or NormalizeCharacterKey
  -- The invite tracker is defined before the factory's normal runtime-clock helper.
  profileSyncMetaOps.getInviteDeliveryTime = function()
    if type(GetTime) == "function" then
      return math.max(0, tonumber(GetTime()) or 0)
    end
    return math.max(0, tonumber(time and time() or 0) or 0)
  end
  local COMM_PROTOCOL_VERSION = math.max(1, tonumber(deps.COMM_PROTOCOL_VERSION) or 1)
  local sessionRuntime = {
    pendingInvites = {},
    pendingJoinRequests = {},
    acceptedJoinFollowupQueue = {},
    acceptedJoinFollowupByKey = {},
    acceptedJoinFollowupTimerToken = 0,
    acceptedJoinFollowupTimerArmed = false,
    acceptedJoinFollowupNotBeforeAt = 0,
    acceptedJoinBurstMembers = {},
    acceptedJoinBurstSessionId = "",
    acceptedJoinBurstProfileName = "",
    acceptedJoinBurstNeedsCommit = false,
    acceptedJoinBurstStats = {
      acceptedTotal = 0,
      coalescedTotal = 0,
      processedTotal = 0,
      failedTotal = 0,
      commitTotal = 0,
      committedMemberTotal = 0,
      uiRefreshRequestedTotal = 0,
      lastQueuedAt = 0,
      lastProcessedAt = 0,
      lastDurationMs = 0,
      maxDurationMs = 0,
    },
    inviteReceipts = {},
    pendingInviteDeliveries = {},
    inviteDeliveryTimerToken = 0,
    pendingSessionFinalizations = {},
    recentSessionFinalizationReceipts = {},
    sessionFinalizationSequence = 0,
    appliedProfileDeltaIds = {},
    profileDeltaLastSequence = {},
    pendingProfileDeltaAcks = {},
    profileDeltaAckSupersededTotal = 0,
    recentProfileDeltaRecoveryRequests = {},
    recentProfileDeltaRecoverySources = {},
    pendingProfileCheckpointSyncs = {},
    pendingProfileCheckpointTimers = {},
    profileCheckpointTimerToken = 0,
    pendingJoinManifestRepairTimers = {
      joinManifest = {},
      patchStateRetry = {},
    },
    joinManifestProofTombstones = {},
    pendingMissingMemberHistoryTimers = {},
    latestSessionHistoryCatchups = {},
    lastProfileCheckpointSyncAt = {},
    recentAutoSubcheckRequestTimes = {},
    recentMemberPrecisePrewarmRequests = {},
    pendingAutoDetailedComparisonTimers = {},
    pendingPostBootstrapRevalidationTimers = {},
    pendingAckTimeoutRevalidations = {},
    ackTimeoutRevalidationStats = {
      sessionId = "",
      suppressedDomainTotal = 0,
      coalescedRecoveryCallbackTotal = 0,
      sharedRecoveryBatchTotal = 0,
      sharedRecoveryTransferTotal = 0,
      lastSuppressedDomainCount = 0,
      lastSharedRecoveryTransferCount = 0,
    },
    pendingSessionMemberBroadcasts = {},
    pendingDeferredMemberSnapshotsBySession = {},
    hostMemberSyncStatusByMember = setmetatable({}, { __mode = "k" }),
    hostMemberSyncStatusSessionByMember = setmetatable({}, { __mode = "k" }),
    hostMemberSyncStatusGenerationByMember = setmetatable({}, { __mode = "k" }),
    hostMemberSyncStatusByKey = {},
    hostMemberSyncStatusGenerationByKey = {},
    hostMemberSyncStatusSessionId = "",
    hostMemberReadinessProofByMember = setmetatable({}, { __mode = "k" }),
    hostMemberReadinessProofSessionByMember = setmetatable({}, { __mode = "k" }),
    hostMemberReadinessProofByKey = {},
    hostMemberReadinessProofGenerationByKey = {},
    readinessTransitionLog = {},
    recentMemberSnapshotWhispers = {},
    recentStatePacketSends = {},
    pendingProfileStateParts = {},
    recentDuplicateJoinRecoveryResends = {},
    recentMissingMemberBootstrapRequests = {},
    recentMemberRepairRequestStates = {},
    recentSessionMemberCheckpointStates = {},
    recentProfileCheckpointRequestStates = {},
    recentRuntimeStateEmissionStates = {},
    lastRuntimeTrackingPruneAt = 0,
    lastReadinessRefreshSessionId = "",
    lastReadinessRefreshAt = 0,
  }
  local sessionConfig = {
    profileDeltaAckTimeoutSeconds = 4,
    profileDeltaMaxRetries = 2,
    profileCheckpointSyncDelaySeconds = 2,
    profileCheckpointSyncMinIntervalSeconds = 3,
    profileSyncAutoSubcheckDedupeSeconds = 6,
    readinessRefreshCooldownSeconds = 5,
    profileSyncJoinManifestRepairDelaySeconds = 1.0,
    profileSyncJoinManifestProofPollSeconds = 2.0,
    -- Let member snapshots and the P1/P2 bootstrap settle before queuing P3 history.
    profileSyncMissingMemberHistoryDelaySeconds = 6,
    -- A full raid can exhaust the host's initial addon-message allowance before
    -- every JACK leaves its queue.  Retry only after a successfully sent JOIN,
    -- with one serialized timer and enough room for 20-30 simultaneous joins.
    joinAckRetryDelaysSeconds = { 8, 12, 18, 25 },
    joinAckFinalWaitSeconds = 12,
    joinAckFallbackDelaySeconds = 10,
    joinAckHardTimeoutSeconds = 90,
    joinAckLateGraceSeconds = 60,
    joinAckQueuePollSeconds = 1,
    joinAckBlockedPollSeconds = 1,
    joinAckMaxAttempts = 5,
    -- Accept a raid-wide JOIN wave immediately, but let the roster settle before
    -- profile revision, comparison, snapshot, and editor work begins.
    acceptedJoinBurstQuietSeconds = 0.75,
    acceptedJoinFollowupStepSeconds = 0.08,
    acceptedJoinUiRefreshDelaySeconds = 0.75,
    acceptedJoinFollowupSlowMilliseconds = 20,
    prepareJoinGraceSeconds = 10,
    inviteJoinGraceSeconds = 10,
    joinQuietGraceSeconds = 5,
    memberBroadcastCoalesceDelaySeconds = 0.05,
    memberSnapshotWhisperDedupeSeconds = 1.0,
    statePacketSendDedupeSeconds = 1.0,
    duplicateJoinRecoveryResendDedupeSeconds = 1.0,
    missingMemberBootstrapDedupeSeconds = 1.5,
    runtimeTrackingPruneIntervalSeconds = 30,
    memberSnapshotWhisperRetentionSeconds = 20,
    statePacketSendRetentionSeconds = 20,
    profileStatePartRetentionSeconds = 20,
    maxPendingProfileStateAssemblies = 40,
    maxProfileStateParts = 16,
    maxProfileStateAssemblyBytes = 4096,
    maxProfileStatePartTokenBytes = 64,
    duplicateJoinRecoveryResendRetentionSeconds = 20,
    missingMemberBootstrapRetentionSeconds = 30,
    runtimeStateEmissionRetentionSeconds = 20,
    memberRepairRequestRetentionSeconds = 4,
    autoSubcheckRequestRetentionSeconds = 120,
    memberPrecisePrewarmDedupeSeconds = 1.5,
    memberPrecisePrewarmRetentionSeconds = 30,
    memberBackgroundSyncBurstDelaySeconds = 0.35,
    memberBackgroundSyncBurstStaggerSeconds = 0.25,
    memberBackgroundSyncBurstMaxStaggerSeconds = 5.0,
    autoDetailedComparisonTimerRetentionSeconds = 60,
    ackTimeoutRevalidationDelaySeconds = 1.5,
    ackTimeoutRevalidationRetentionSeconds = 8,
    profileDeltaSeenRetentionSeconds = 1800,
    profileDeltaSequenceRetentionSeconds = 1800,
    profileDeltaRecoveryRequestDedupeSeconds = 3,
    profileDeltaRecoveryRequestRetentionSeconds = 30,
    profileDeltaRecoverySourceRetentionSeconds = 30,
    -- Deltas are sent directly and cannot be split generically.  Route unusually
    -- large host deltas through the existing chunked repair flow before they reach
    -- the hard addon-message transport limit.
    profileDeltaPayloadTargetBytes = 220,
    maxRecentProfileDeltaRecoverySources = 64,
    pendingProfileDeltaAckRetentionSeconds = 30,
    pendingProfileCheckpointRetentionSeconds = 30,
    recentSessionMemberCheckpointRetentionSeconds = 45,
    recentProfileCheckpointRequestRetentionSeconds = 45,
    lastProfileCheckpointSyncRetentionSeconds = 300,
    automaticHostRepairRequestRetentionSeconds = 45,
    pendingJoinManifestRepairRetentionSeconds = 30,
    pendingPatchStateRetryRetentionSeconds = 30,
    pendingInviteRetentionSeconds = 300,
    inviteReceiptRetentionSeconds = 300,
    inviteReceiptTimeoutSeconds = 8,
    inviteReceiptQueuePollSeconds = 1,
    inviteReceiptBlockedPollSeconds = 1,
    inviteReceiptMaxAttempts = 2,
    inviteDeliveryRetentionSeconds = 300,
    sessionFinalizationAckTimeoutSeconds = 4,
    sessionFinalizationMaxAttempts = 3,
    sessionFinalizationRetentionSeconds = 300,
    sessionFinalizationReceiptRetentionSeconds = 300,
    pendingJoinRequestRetentionSeconds = 180,
    pendingSessionMemberBroadcastRetentionSeconds = 5,
    pendingMissingMemberHistoryTimerRetentionSeconds = 45,
    -- A full raid can take several minutes to finish its serialized bootstrap.
    -- These entries contain only member keys and are cleared as soon as the
    -- target becomes ready, so retain them long enough for a throttled raid join.
    pendingDeferredMemberSnapshotRetentionSeconds = 1800,
    profileBootstrapDomains = { "settings", "permissions" },
  }
  local AreCharacterKeysSame
  local FindSessionMember
  local CloneCheckpointSubdomainList
  local MergeDecisionTextLists
  local BuildRepairScopeEscalationKindsSuffix
  local GetActiveSyncCandidateContext
  local BuildActiveSyncCandidateSnapshot
  local QueueTargetedDeltaRecoveryForMember
  local NormalizeSenderKey
  local BuildSessionVisibleMemberStateSignature
  local BuildTargetMemberSnapshotWhisperStateKey
  local BuildLocalRepairRevisionSignature
  local QueueProfileSnapshotForMember
  local QueuePreparedRepairTransfersForMember
  local QueueLiveFirstRepairTransfersForMember
  local SendJoinRequest
  local optionalApiOps = {
    resolve = type(deps.ResolveOptionalApiFunction) == "function" and deps.ResolveOptionalApiFunction or nil,
    cache = {},
    failureSignatures = {},
  }
  local sessionUiOps = {}
  local sessionLifecycleOps = {
    syncEvents = {
      deferred_join_repair_sent = {
        runtimeStateKey = "host_snapshot_sent",
        runtimeStateLevel = "success",
      },
      deferred_join_repair_waiting = {
        runtimeStateKey = "host_snapshot_sent",
        runtimeStateLevel = "info",
      },
      deferred_join_repair_aligned = {
        runtimeStateKey = "host_snapshot_sent",
        runtimeStateLevel = "success",
      },
      deferred_join_repair_failed = {
        runtimeStateKey = "host_snapshot_sent",
        runtimeStateLevel = "warn",
      },
      host_join_repair_sent = {
        runtimeStateKey = "host_snapshot_sent",
        runtimeStateLevel = "success",
      },
      host_join_repair_pending = {
        runtimeStateKey = "host_snapshot_sent",
        runtimeStateLevel = "info",
      },
      host_join_repair_aligned = {
        runtimeStateKey = "host_snapshot_sent",
        runtimeStateLevel = "success",
      },
      host_join_repair_scopes_only = {
        runtimeStateKey = "host_snapshot_sent",
        runtimeStateLevel = "info",
      },
      host_join_repair_failed = {
        runtimeStateKey = "host_snapshot_sent",
        runtimeStateLevel = "warn",
      },
      missing_member_copy_bootstrap = {
        runtimeStateKey = "missing_member_copy",
        runtimeStateLevel = "success",
      },
      missing_member_copy_bootstrap_failed = {
        runtimeStateKey = "missing_member_copy",
        runtimeStateLevel = "warn",
      },
      remote_join_diverged = {
        runtimeStateKey = "diverged_remote_member",
        runtimeStateLevel = "warn",
      },
      remote_join_member_newer = {
        runtimeStateKey = "member_newer",
        runtimeStateLevel = "warn",
      },
    },
    transitionEvents = {
      prepared = {
        runtimeStateKey = "session_prepared",
        runtimeStateLevel = "info",
        runtimeStateMessage = "Preparation lobby is open. Joined member profile revisions can be compared before the session is started.",
      },
      host_started = {
        runtimeStateKey = "session_started",
        runtimeStateLevel = "success",
        runtimeStateMessage = "Session started. The host profile is authoritative for this active session. No extra full profile push was queued automatically.",
      },
      remote_started = {
        runtimeStateKey = "session_started",
        runtimeStateLevel = "success",
        runtimeStateMessage = "Session started. The host profile is authoritative for this active session.",
      },
    },
    memberEvents = {
      join_confirmed_ready = {},
      join_confirmed_bootstrap_pending = {},
      member_removed = {
        runtimeStateKey = "member_removed",
        runtimeStateLevel = "info",
      },
      remote_member_left = {
        runtimeStateKey = "member_left",
        runtimeStateLevel = "info",
      },
    },
    endEvents = {
      member_left = {
        runtimeStateKey = "session_left",
        runtimeStateLevel = "info",
        runtimeStateMessage = "You left the active loot session. The host session continues for the remaining joined members.",
      },
      host_stopped = {
        runtimeStateKey = "session_stopped",
        runtimeStateLevel = "info",
        runtimeStateMessage = "Shared profile sync is idle because the active session ended.",
      },
      left_group = {
        runtimeStateKey = "left_group",
        runtimeStateLevel = "info",
        runtimeStateMessage = "Local loot session ended because you left the host group.",
      },
      remote_stopped = {
        runtimeStateKey = "session_stopped",
        runtimeStateLevel = "info",
        runtimeStateMessage = "Shared profile sync is idle because the active session ended.",
      },
    },
  }

  local function GetCommProtocolMarker()
    if type(deps.BuildCommProtocolMarker) == "function" then
      return deps.BuildCommProtocolMarker(COMM_PROTOCOL_VERSION)
    end
    return "P" .. tostring(COMM_PROTOCOL_VERSION)
  end

  function optionalApiOps.get(apiName)
    local resolvedApiName = TrimText(apiName)
    if resolvedApiName == "" or type(optionalApiOps.resolve) ~= "function" then
      return nil
    end
    local cached = optionalApiOps.cache[resolvedApiName]
    if cached ~= nil then
      return cached ~= false and cached or nil
    end
    local ok, resolved = pcall(optionalApiOps.resolve, resolvedApiName)
    if not ok then
      optionalApiOps.warnFailure("ResolveOptionalApiFunction(" .. resolvedApiName .. ")", resolved, "resolve")
      optionalApiOps.cache[resolvedApiName] = false
      return nil
    end
    resolved = type(resolved) == "function" and resolved or false
    optionalApiOps.cache[resolvedApiName] = resolved
    return resolved ~= false and resolved or nil
  end

  function optionalApiOps.warnFailure(apiName, errorText, context)
    local resolvedApiName = TrimText(apiName)
    local resolvedErrorText = TrimText(errorText)
    local resolvedContext = TrimText(context)
    if resolvedApiName == "" or resolvedErrorText == "" then
      return
    end
    local failureSignature = string.lower(resolvedApiName) .. "\31" .. string.lower(resolvedContext) .. "\31" .. resolvedErrorText
    if optionalApiOps.failureSignatures[failureSignature] == true then
      return
    end
    optionalApiOps.failureSignatures[failureSignature] = true
    local contextSuffix = resolvedContext ~= "" and " during " .. resolvedContext or ""
    Print("Optional LidCouncil session helper " .. resolvedApiName .. " failed" .. contextSuffix .. ": " .. resolvedErrorText)
  end

  function optionalApiOps.invoke(apiName, ...)
    local resolvedApiName = TrimText(apiName)
    local optionalFn = optionalApiOps.get(resolvedApiName)
    if type(optionalFn) ~= "function" then
      return nil, "unavailable"
    end
    local ok, result1, result2, result3, result4, result5 = pcall(optionalFn, ...)
    if not ok then
      optionalApiOps.warnFailure(resolvedApiName, result1, "invoke")
      return nil, "failed", result1
    end
    return true, result1, result2, result3, result4, result5
  end

  function sessionUiOps.buildRefreshOpts(opts)
    if type(opts) ~= "table" then
      return {
        defer = true,
        delaySeconds = sessionConfig.memberBroadcastCoalesceDelaySeconds,
      }
    end
    local refreshOpts = {}
    for key, value in pairs(opts) do
      refreshOpts[key] = value
    end
    if refreshOpts.defer == nil then
      refreshOpts.defer = true
    end
    if refreshOpts.forceImmediate ~= true and refreshOpts.delaySeconds == nil then
      refreshOpts.delaySeconds = sessionConfig.memberBroadcastCoalesceDelaySeconds
    end
    return refreshOpts
  end

  function sessionUiOps.refreshCurrentAndSyncSections(currentSectionChanged, opts)
    return INTERNAL_API.LIDCOUNCIL_RefreshEditorForCurrentAndSyncSections(
      currentSectionChanged == true,
      sessionUiOps.buildRefreshOpts(opts)
    )
  end

  function sessionUiOps.refreshLootListAfterRosterChange()
    -- Keep the Loot List live when it is visible, without forcing an expensive
    -- rebuild of that hidden page for every roster broadcast.
    return INTERNAL_API.LIDCOUNCIL_RequestSessionEditorRefresh({
      defer = false,
      delaySeconds = 0,
      refreshPages = {
        Backgrounds = true,
      },
    })
  end

  function sessionUiOps.refreshCurrentSyncAndLootListAfterRosterChange(opts)
    local refreshed = sessionUiOps.refreshCurrentAndSyncSections(true, opts)
    sessionUiOps.refreshLootListAfterRosterChange()
    return refreshed
  end

  function sessionUiOps.queueAcceptedJoinBurstRefresh()
    local stats = type(sessionRuntime.acceptedJoinBurstStats) == "table"
      and sessionRuntime.acceptedJoinBurstStats
      or {}
    sessionRuntime.acceptedJoinBurstStats = stats
    stats.uiRefreshRequestedTotal = math.max(0, tonumber(stats.uiRefreshRequestedTotal) or 0) + 1
    local delaySeconds = sessionConfig.acceptedJoinUiRefreshDelaySeconds
    local refreshed = sessionUiOps.refreshCurrentAndSyncSections(true, {
      defer = true,
      delaySeconds = delaySeconds,
    })
    INTERNAL_API.LIDCOUNCIL_RequestSessionEditorRefresh({
      defer = true,
      delaySeconds = delaySeconds,
      refreshPages = {
        Backgrounds = true,
      },
    })
    return refreshed
  end

  function sessionUiOps.refreshSyncManagementSection(opts)
    return INTERNAL_API.LIDCOUNCIL_RefreshEditorForSyncManagementSection(sessionUiOps.buildRefreshOpts(opts))
  end

  function sessionUiOps.refreshPanelsAndLiveBoard(opts)
    return INTERNAL_API.LIDCOUNCIL_RefreshEditorForPanelsAndLiveBoard(sessionUiOps.buildRefreshOpts(opts))
  end

  function sessionUiOps.refreshCurrentAndAutoPassSections(opts)
    return INTERNAL_API.LIDCOUNCIL_RefreshEditorForCurrentAndAutoPassSections(sessionUiOps.buildRefreshOpts(opts))
  end

  function sessionUiOps.refreshCurrentSection(opts)
    return INTERNAL_API.LIDCOUNCIL_RefreshEditorForCurrentSection(sessionUiOps.buildRefreshOpts(opts))
  end

  function sessionUiOps.refreshAutoPassSection(opts)
    return INTERNAL_API.LIDCOUNCIL_RefreshEditorForAutoPassSection(sessionUiOps.buildRefreshOpts(opts))
  end

  function sessionUiOps.refreshRepairOutcomeIfTouched(repairOutcomeTouched, currentSectionChanged, opts)
    if repairOutcomeTouched ~= true then
      return false
    end
    return sessionUiOps.refreshCurrentAndSyncSections(currentSectionChanged == true, opts) == true
  end

  function sessionUiOps.mergeRepairOutcomeRefreshState(repairRefreshState, touched, currentSectionChanged)
    repairRefreshState = type(repairRefreshState) == "table" and repairRefreshState or {}
    if touched == true then
      repairRefreshState.touched = true
      if currentSectionChanged == true then
        repairRefreshState.currentSectionChanged = true
      end
    end
    return repairRefreshState
  end

  function sessionUiOps.mergeRepairOutcomePersistResult(repairRefreshState, persistResult)
    return sessionUiOps.mergeRepairOutcomeRefreshState(
      repairRefreshState,
      type(persistResult) == "table" and persistResult.stamped == true,
      type(persistResult) == "table" and persistResult.currentSectionChanged == true
    )
  end

  function sessionUiOps.applyRepairOutcomeRefreshState(repairRefreshState, opts)
    repairRefreshState = type(repairRefreshState) == "table" and repairRefreshState or {}
    opts = type(opts) == "table" and opts or {}
    local repairOutcomeRefreshed = sessionUiOps.refreshRepairOutcomeIfTouched(
      repairRefreshState.touched == true,
      repairRefreshState.currentSectionChanged == true,
      opts
    ) == true

    local fallbackCurrentSectionChanged = false
    if repairOutcomeRefreshed ~= true and type(opts.previousHostCurrentSectionProbe) == "table" then
      fallbackCurrentSectionChanged = INTERNAL_API.LIDCOUNCIL_GetHostCurrentSectionChangeFromProbe(
        opts.activeSession,
        opts.profileName,
        opts.previousHostCurrentSectionProbe,
        {
          hostCurrentSessionDisplayBaseContext = opts.hostCurrentSessionDisplayBaseContext,
          syncCandidateSnapshot = opts.syncCandidateSnapshot,
          candidateEntries = opts.candidateEntries,
          candidateSyncStateByMemberKey = opts.candidateSyncStateByMemberKey,
        }
      ) == true
      if fallbackCurrentSectionChanged == true then
        local fallbackScope = string.upper(TrimText(opts.fallbackScope))
        if fallbackScope == "CURRENT_AND_SYNC" then
          sessionUiOps.refreshCurrentAndSyncSections(true, opts)
        elseif fallbackScope == "CURRENT" then
          sessionUiOps.refreshCurrentSection(opts)
        elseif fallbackScope == "SYNCMGMT" then
          sessionUiOps.refreshSyncManagementSection(opts)
        end
      end
    end

    return {
      repairOutcomeRefreshed = repairOutcomeRefreshed,
      fallbackCurrentSectionChanged = fallbackCurrentSectionChanged,
      currentSectionChanged = repairRefreshState.currentSectionChanged == true or fallbackCurrentSectionChanged,
      refreshed = repairOutcomeRefreshed == true or fallbackCurrentSectionChanged,
    }
  end

  function sessionLifecycleOps.createRepairMetricsState()
    return {
      memberSentCount = 0,
      targetedCount = 0,
      preciseCount = 0,
      rowPatchTransferCount = 0,
      patchTransferCount = 0,
      patchScopeCount = 0,
      snapshotTransferCount = 0,
      fullFallbackCount = 0,
      scopeEscalationCount = 0,
      scopeEscalationKinds = {},
      skippedAlignedCount = 0,
      skippedMemberNewerCount = 0,
      suppressedRepeatCount = 0,
      deferredPatchStateCount = 0,
      queueMergeCount = 0,
      queueExactDuplicateCount = 0,
    }
  end

  function sessionLifecycleOps.accumulateOutboundQueueMetrics(repairMetricsState, queueDetail)
    repairMetricsState = type(repairMetricsState) == "table" and repairMetricsState or sessionLifecycleOps.createRepairMetricsState()
    queueDetail = type(queueDetail) == "table" and queueDetail or {}

    repairMetricsState.queueMergeCount = repairMetricsState.queueMergeCount
      + math.max(0, tonumber(queueDetail.queueMergeCount) or tonumber(queueDetail.mergedCount) or 0)
    repairMetricsState.queueExactDuplicateCount = repairMetricsState.queueExactDuplicateCount
      + math.max(
        0,
        tonumber(queueDetail.queueExactDuplicateCount) or tonumber(queueDetail.exactDuplicateCount) or 0
      )
    return repairMetricsState
  end

  function sessionLifecycleOps.accumulateQueuedRepairMetrics(repairMetricsState, queuedTransfers, repairDetail, opts)
    repairMetricsState = type(repairMetricsState) == "table" and repairMetricsState or sessionLifecycleOps.createRepairMetricsState()
    repairDetail = type(repairDetail) == "table" and repairDetail or {}
    opts = type(opts) == "table" and opts or {}

    local resolvedQueuedTransfers = math.max(0, tonumber(queuedTransfers) or 0)
    local resolvedMemberCount = math.max(0, tonumber(opts.memberCount) or 1)
    if resolvedQueuedTransfers > 0 then
      repairMetricsState.memberSentCount = repairMetricsState.memberSentCount + resolvedMemberCount
      if repairDetail.scopeEscalated == true and repairDetail.fullSnapshotFallback ~= true then
        repairMetricsState.scopeEscalationCount = repairMetricsState.scopeEscalationCount + resolvedMemberCount
        repairMetricsState.scopeEscalationKinds = MergeDecisionTextLists(
          repairMetricsState.scopeEscalationKinds,
          repairDetail.scopeEscalationKinds
        )
      end
      local treatedAsFullFallback = opts.forceFullSnapshot == true
        or repairDetail.forceFullSnapshot == true
        or repairDetail.fullSnapshotFallback == true
        or TrimText(repairDetail.repairMode) == "full"
      if treatedAsFullFallback then
        repairMetricsState.fullFallbackCount = repairMetricsState.fullFallbackCount + resolvedMemberCount
      else
        repairMetricsState.targetedCount = repairMetricsState.targetedCount + resolvedMemberCount
        local countedAsPrecise = opts.precise == true or TrimText(repairDetail.repairMode) == "precise"
        if countedAsPrecise then
          repairMetricsState.preciseCount = repairMetricsState.preciseCount + resolvedMemberCount
        end
        repairMetricsState.patchTransferCount = repairMetricsState.patchTransferCount
          + math.max(0, tonumber(repairDetail.patchTransfers) or 0)
        repairMetricsState.patchScopeCount = repairMetricsState.patchScopeCount
          + math.max(0, tonumber(repairDetail.patchSubdomains) or 0)
      end
      repairMetricsState.snapshotTransferCount = repairMetricsState.snapshotTransferCount
        + math.max(0, tonumber(repairDetail.snapshotTransfers) or 0)
      sessionLifecycleOps.accumulateOutboundQueueMetrics(repairMetricsState, repairDetail)
    end
    if repairDetail.deferredPatchState == true then
      repairMetricsState.deferredPatchStateCount = repairMetricsState.deferredPatchStateCount + 1
    end
    return repairMetricsState
  end

  function sessionLifecycleOps.accumulateQueuedRowPatchMetrics(repairMetricsState, queuedTransfers, rowPatchSubdomains, opts)
    repairMetricsState = type(repairMetricsState) == "table" and repairMetricsState or sessionLifecycleOps.createRepairMetricsState()
    opts = type(opts) == "table" and opts or {}

    local resolvedQueuedTransfers = math.max(0, tonumber(queuedTransfers) or 0)
    local resolvedMemberCount = math.max(0, tonumber(opts.memberCount) or resolvedQueuedTransfers or 0)
    if resolvedQueuedTransfers <= 0 or resolvedMemberCount <= 0 then
      return repairMetricsState
    end

    repairMetricsState.memberSentCount = repairMetricsState.memberSentCount + resolvedMemberCount
    repairMetricsState.targetedCount = repairMetricsState.targetedCount + resolvedMemberCount
    if #CloneCheckpointSubdomainList(rowPatchSubdomains) > 0 then
      repairMetricsState.preciseCount = repairMetricsState.preciseCount + resolvedMemberCount
    end
    repairMetricsState.rowPatchTransferCount = repairMetricsState.rowPatchTransferCount + resolvedQueuedTransfers
    sessionLifecycleOps.accumulateOutboundQueueMetrics(repairMetricsState, opts)
    return repairMetricsState
  end

  function sessionLifecycleOps.accumulateSkippedRepairMetrics(repairMetricsState, repairDetail, opts)
    repairMetricsState = type(repairMetricsState) == "table" and repairMetricsState or sessionLifecycleOps.createRepairMetricsState()
    repairDetail = type(repairDetail) == "table" and repairDetail or {}
    opts = type(opts) == "table" and opts or {}

    if repairDetail.deferredPatchState == true and opts.includeDeferred ~= false then
      repairMetricsState.deferredPatchStateCount = repairMetricsState.deferredPatchStateCount + 1
      return repairMetricsState
    end
    if repairDetail.skippedMemberNewer == true then
      repairMetricsState.skippedMemberNewerCount = repairMetricsState.skippedMemberNewerCount + 1
      return repairMetricsState
    end
    if repairDetail.suppressedUnchanged == true and opts.includeSuppressed == true then
      repairMetricsState.suppressedRepeatCount = repairMetricsState.suppressedRepeatCount + 1
      return repairMetricsState
    end
    if repairDetail.skippedAligned == true or repairDetail.skippedNoOp == true then
      repairMetricsState.skippedAlignedCount = repairMetricsState.skippedAlignedCount + 1
    end
    return repairMetricsState
  end

  function optionalApiOps.cancelQueuedProfileSyncForSession(sessionId)
    local invoked, result = optionalApiOps.invoke("LIDCOUNCIL_CancelQueuedProfileSyncForSession", sessionId)
    if invoked == true then
      return result
    end
    return nil
  end

  function optionalApiOps.cancelProfileSnapshotBatchForSession(sessionId)
    local invoked, result = optionalApiOps.invoke("LIDCOUNCIL_CancelProfileSnapshotBatchForSession", sessionId)
    if invoked == true then
      return result
    end
    return nil
  end

  function optionalApiOps.beginProfileSnapshotDiagnosticsForSession(sessionId, startedAt)
    local invoked, result = optionalApiOps.invoke("LIDCOUNCIL_BeginProfileSnapshotDiagnosticsForSession", sessionId, startedAt)
    if invoked == true then
      return result
    end
    return nil
  end

  function optionalApiOps.clearLiveLootRuntime()
    local invoked, result = optionalApiOps.invoke("LIDCOUNCIL_ClearLiveLootRuntime")
    if invoked == true then
      return result
    end
    return nil
  end

  function optionalApiOps.getSessionCommQueueStatus()
    local invoked, result = optionalApiOps.invoke("LIDCOUNCIL_GetSessionCommQueueStatus")
    if invoked == true then
      return result
    end
    return nil
  end

  function optionalApiOps.cancelSessionSyncArtifacts(sessionId)
    local resolvedSessionId = TrimText(sessionId)
    if resolvedSessionId == "" then
      return false
    end
    optionalApiOps.cancelQueuedProfileSyncForSession(resolvedSessionId)
    optionalApiOps.cancelProfileSnapshotBatchForSession(resolvedSessionId)
    return true
  end

  function sessionLifecycleOps.buildEndFinalizeOpts(eventKey, opts)
    opts = type(opts) == "table" and opts or {}
    local event = sessionLifecycleOps.endEvents[TrimText(eventKey)]
    if type(event) ~= "table" then
      return {
        sender = opts.sender,
        activeSession = opts.activeSession,
        refreshEditor = opts.refreshEditor,
      }
    end
    return {
      runtimeStateKey = event.runtimeStateKey,
      runtimeStateLevel = event.runtimeStateLevel,
      runtimeStateMessage = event.runtimeStateMessage,
      sender = opts.sender,
      activeSession = opts.activeSession,
      refreshEditor = opts.refreshEditor,
    }
  end

  function sessionLifecycleOps.buildTransitionRuntimeOpts(eventKey, opts)
    opts = type(opts) == "table" and opts or {}
    local event = sessionLifecycleOps.transitionEvents[TrimText(eventKey)]
    if type(event) ~= "table" then
      return {
        sender = opts.sender,
        refreshEditor = opts.refreshEditor,
      }
    end
    return {
      runtimeStateKey = event.runtimeStateKey,
      runtimeStateLevel = event.runtimeStateLevel,
      runtimeStateMessage = event.runtimeStateMessage,
      sender = opts.sender,
      refreshEditor = opts.refreshEditor,
    }
  end

  function sessionLifecycleOps.buildTransitionNoticeText(eventKey, opts)
    opts = type(opts) == "table" and opts or {}
    local resolvedProfileName = tostring(opts.profileName or "Unknown")
    local resolvedEventKey = TrimText(eventKey)
    if resolvedEventKey == "prepared" then
      if opts.hasDistribution == true then
        return "Prepared loot session \"" .. resolvedProfileName .. "\"."
      end
      return "Prepared local loot session \"" .. resolvedProfileName .. "\". No raid or party channel is available yet."
    end
    if resolvedEventKey == "host_started" then
      return "Started loot session \"" .. resolvedProfileName .. "\". The host profile is now authoritative."
    end
    if resolvedEventKey == "remote_started" then
      return "Loot session \"" .. resolvedProfileName .. "\" was started by " .. tostring(opts.host or "Unknown") .. "."
    end
    return ""
  end

  function sessionLifecycleOps.buildMemberRuntimeOpts(eventKey, opts)
    opts = type(opts) == "table" and opts or {}
    local resolvedEventKey = TrimText(eventKey)
    local event = sessionLifecycleOps.memberEvents[resolvedEventKey]
    local resolvedMemberKey = tostring(opts.memberKey or "Unknown")
    if type(event) ~= "table" then
      return {
        sender = opts.sender,
        refreshEditor = opts.refreshEditor,
      }
    end
    local runtimeStateMessage = ""
    if resolvedEventKey == "member_removed" then
      runtimeStateMessage = resolvedMemberKey .. " was removed from the joined member list."
    elseif resolvedEventKey == "remote_member_left" then
      runtimeStateMessage = resolvedMemberKey .. " left the active loot session early."
    end
    return {
      runtimeStateKey = event.runtimeStateKey,
      runtimeStateLevel = event.runtimeStateLevel,
      runtimeStateMessage = runtimeStateMessage,
      sender = opts.sender,
      refreshEditor = opts.refreshEditor,
    }
  end

  function sessionLifecycleOps.buildMemberNoticeText(eventKey, opts)
    opts = type(opts) == "table" and opts or {}
    local resolvedProfileName = tostring(opts.profileName or "Unknown")
    local resolvedMemberKey = tostring(opts.memberKey or "Unknown")
    local resolvedEventKey = TrimText(eventKey)
    if resolvedEventKey == "join_confirmed_bootstrap_pending" then
      return "Host confirmed your join for \"" .. resolvedProfileName
        .. "\". Waiting for the host bootstrap copy before LidCouncil roll choices become available."
        .. " Remaining shared history can keep syncing in the background."
    end
    if resolvedEventKey == "join_confirmed_ready" then
      return "Host confirmed your join for \"" .. resolvedProfileName .. "\"."
    end
    if resolvedEventKey == "member_removed" then
      return "Removed " .. resolvedMemberKey .. " from the joined member list."
    end
    if resolvedEventKey == "remote_member_left" then
      return resolvedMemberKey .. " left loot session \"" .. resolvedProfileName .. "\"."
    end
    if resolvedEventKey == "local_autopass_session" then
      return "Local Auto Pass " .. (opts.enabled and "enabled" or "disabled") .. " for session \"" .. resolvedProfileName .. "\"."
    end
    if resolvedEventKey == "local_autopass_global" then
      return "Local Auto Pass " .. (opts.enabled and "enabled" or "disabled") .. "."
    end
    if resolvedEventKey == "member_autopass_changed" then
      return resolvedMemberKey .. " set local Auto Pass " .. (opts.enabled and "|cff4adf6bON|r" or "|cffff5a5aOFF|r") .. "."
    end
    if resolvedEventKey == "member_declined" then
      return resolvedMemberKey .. " declined the loot session \"" .. resolvedProfileName .. "\"."
    end
    return ""
  end

  function sessionLifecycleOps.buildFlowNoticeText(eventKey, opts)
    opts = type(opts) == "table" and opts or {}
    local resolvedProfileName = tostring(opts.profileName or "Unknown")
    local resolvedHost = tostring(opts.host or "Unknown")
    local resolvedSessionName = tostring(opts.profileName or "Unknown")
    local resolvedEventKey = TrimText(eventKey)
    if resolvedEventKey == "invite_ignored_existing_session" then
      return "Ignored session invite from " .. resolvedHost .. " because a different LidCouncil session is already open."
    end
    if resolvedEventKey == "invite_incompatible_build" then
      return "Could not join \"" .. resolvedProfileName .. "\" because the session host is using an incompatible LidCouncil build. Update both clients to the same build and try again."
    end
    if resolvedEventKey == "join_request_sent" then
      return "Join request sent for \"" .. resolvedProfileName .. "\". Waiting for host confirmation before creating the local session."
    end
    if resolvedEventKey == "join_request_retried" then
      return "Still waiting for host confirmation for \"" .. resolvedProfileName .. "\". Retried join request "
        .. tostring(opts.attempts or 0) .. "/" .. tostring(opts.maxAttempts or 0) .. "."
    end
    if resolvedEventKey == "join_request_failed" then
      return "Could not send join request to the session host: " .. tostring(opts.error or "JOIN send failed.")
    end
    if resolvedEventKey == "join_request_timeout" then
      return "The session host did not confirm your join request for \"" .. resolvedProfileName .. "\". Ask the host to send the invite again."
    end
    if resolvedEventKey == "invite_no_channel" then
      return "No raid or party channel is available yet."
    end
    if resolvedEventKey == "invite_no_new_targets" then
      return "No new raid members were found for this active session."
    end
    if resolvedEventKey == "invite_sent_count" then
      return "Queued session invite for " .. tostring(opts.sentCount or 0) .. " late joiner" .. ((opts.sentCount or 0) == 1 and "" or "s") .. ". Waiting for recipient receipt."
    end
    if resolvedEventKey == "invite_sent_none" then
      return "No session invites could be sent."
    end
    if resolvedEventKey == "invite_broadcast_queued" then
      return "Queued session announcement for " .. tostring(opts.targetCount or 0) .. " group member"
        .. ((opts.targetCount or 0) == 1 and "" or "s") .. ". Waiting for recipient receipts."
    end
    if resolvedEventKey == "invite_received" then
      if TrimText(opts.reason) == "popup_shown" then
        return tostring(opts.memberKey or "A member") .. " received the session invite and the confirmation popup is open."
      end
      return tostring(opts.memberKey or "A member") .. " received the session invite."
    end
    if resolvedEventKey == "invite_rejected" then
      return tostring(opts.memberKey or "A member") .. " could not display the session invite: " .. tostring(opts.reason or "unknown reason") .. "."
    end
    if resolvedEventKey == "invite_receipt_retry" then
      return "No receipt from " .. tostring(opts.memberKey or "a member") .. " yet. Retrying the session invite once."
    end
    if resolvedEventKey == "invite_receipt_timeout" then
      return "No receipt from " .. tostring(opts.memberKey or "a member")
        .. " after " .. tostring(opts.attempts or 0) .. " invite attempts. They may not have LidCouncil active, or their client did not receive the addon message."
    end
    if resolvedEventKey == "invite_retry_send_failed" then
      return "Could not queue the retry invite for " .. tostring(opts.memberKey or "a member")
        .. ": " .. tostring(opts.error or "unknown send error") .. "."
    end
    if resolvedEventKey == "invite_rejected_identity" then
      return "Ignored a session invite because the claimed host identity did not match the sender."
    end
    if resolvedEventKey == "invite_rejected_group" then
      return "Ignored a session invite because the host is not in your current group."
    end
    if resolvedEventKey == "invite_rejected_payload" then
      return "Ignored an invalid session invite from " .. resolvedHost .. ": " .. tostring(opts.reason or "invalid payload") .. "."
    end
    if resolvedEventKey == "start_missing_prepared" then
      return "Prepare a loot session before starting it."
    end
    if resolvedEventKey == "start_only_host" then
      return "Only the preparation host can start this session."
    end
    if resolvedEventKey == "start_already_active" then
      return "Loot session \"" .. resolvedSessionName .. "\" is already active."
    end
    if resolvedEventKey == "start_not_prepared" then
      return "Only a prepared loot session can be started."
    end
    if resolvedEventKey == "start_warning_fallback" then
      return tostring(opts.warningText or "")
        .. " Use Start Session again after more members are roll-ready, or force start only if you accept that some players may still miss the roll popup."
    end
    if resolvedEventKey == "start_prepared_failed" then
      return tostring(opts.error or "Could not start the prepared loot session.")
    end
    if resolvedEventKey == "start_incoming_failed" then
      return tostring(opts.error or "Could not start the incoming prepared loot session.")
    end
    if resolvedEventKey == "join_confirm_incompatible_build" then
      return "Ignored join confirmation for \"" .. resolvedProfileName .. "\" because the host is using an incompatible LidCouncil build."
    end
    if resolvedEventKey == "join_confirm_failed" then
      return tostring(opts.error or "Could not join the confirmed incoming loot session.")
    end
    if resolvedEventKey == "role_update_no_session" then
      return "No matching active session."
    end
    if resolvedEventKey == "role_update_member_key_required" then
      return "Character-Realm is required."
    end
    if resolvedEventKey == "role_update_member_not_found" then
      return "Session member not found."
    end
    return ""
  end

  function sessionLifecycleOps.scheduleInviteReceiptCheck(sessionId, memberKey, timerToken, delaySeconds)
    if type(Compat) ~= "table" or type(Compat.After) ~= "function" then
      return false, "timer_unavailable"
    end
    return Compat.After(math.max(0.05, tonumber(delaySeconds) or sessionConfig.inviteReceiptTimeoutSeconds), function()
      sessionLifecycleOps.handleInviteReceiptTimeout(sessionId, memberKey, timerToken)
    end)
  end

  function sessionLifecycleOps.armInviteDeliveryCheck(delivery, sessionId, memberKey, delaySeconds)
    if type(delivery) ~= "table" then
      return false, "missing_invite_delivery"
    end
    sessionRuntime.inviteDeliveryTimerToken =
      math.max(0, tonumber(sessionRuntime.inviteDeliveryTimerToken) or 0) + 1
    delivery.timerToken = sessionRuntime.inviteDeliveryTimerToken
    local scheduled, scheduleReason = sessionLifecycleOps.scheduleInviteReceiptCheck(
      sessionId,
      memberKey,
      delivery.timerToken,
      delaySeconds
    )
    if scheduled ~= true then
      delivery.state = "TIMER_UNAVAILABLE"
      delivery.error = TrimText(scheduleReason)
      delivery.updatedAt = profileSyncMetaOps.getInviteDeliveryTime()
      return false, delivery.error
    end
    return true
  end

  function sessionLifecycleOps.queueInviteStart(activeSession, memberKey)
    local targetKey = NormalizeCharacterKey(memberKey)
    if type(activeSession) ~= "table" or targetKey == "" then
      return false, "missing_invite_delivery_identity"
    end
    return SendComm(
      "START",
      "WHISPER",
      targetKey,
      activeSession.id,
      activeSession.profileName,
      TrimText(select(1, deps.GetLootProfileId(activeSession.profileName)) or ""),
      activeSession.host,
      activeSession.startedAt,
      deps.GetLootProfileMaster(activeSession.profileName),
      GetCommProtocolMarker(),
      activeSession.status or "PREPARING"
    )
  end

  function sessionLifecycleOps.beginInviteDelivery(activeSession, memberKey, queued, sendError)
    local sessionId = TrimText(type(activeSession) == "table" and activeSession.id or "")
    local profileName = TrimText(type(activeSession) == "table" and activeSession.profileName or "")
    local targetKey = NormalizeCharacterKey(memberKey)
    if sessionId == "" or profileName == "" or targetKey == "" then
      return false, "missing_invite_delivery_identity"
    end

    sessionRuntime.pendingInviteDeliveries[sessionId] = sessionRuntime.pendingInviteDeliveries[sessionId] or {}
    local delivery = {
      memberKey = targetKey,
      profileName = profileName,
      host = NormalizeCharacterKey(activeSession.host),
      attempts = 0,
      queueAttempts = queued == true and 1 or 0,
      state = queued == true and "QUEUED" or "SEND_FAILED",
      queuedAt = profileSyncMetaOps.getInviteDeliveryTime(),
      updatedAt = profileSyncMetaOps.getInviteDeliveryTime(),
      error = TrimText(sendError),
      timerToken = 0,
    }
    sessionRuntime.pendingInviteDeliveries[sessionId][targetKey] = delivery
    if queued ~= true then
      sessionUiOps.refreshSyncManagementSection({ defer = true })
      return false, delivery.error ~= "" and delivery.error or "invite_not_queued"
    end

    local scheduled, scheduleReason = sessionLifecycleOps.armInviteDeliveryCheck(
      delivery,
      sessionId,
      targetKey,
      sessionConfig.inviteReceiptQueuePollSeconds
    )
    if scheduled ~= true then
      sessionUiOps.refreshSyncManagementSection({ defer = true })
      return false, scheduleReason
    end
    sessionUiOps.refreshSyncManagementSection({ defer = true })
    return true
  end

  function sessionLifecycleOps.resolveInviteDelivery(sessionId, memberKey, receiptState, reason)
    local resolvedSessionId = TrimText(sessionId)
    local targetKey = NormalizeCharacterKey(memberKey)
    local deliveryStates = type(sessionRuntime.pendingInviteDeliveries[resolvedSessionId]) == "table"
      and sessionRuntime.pendingInviteDeliveries[resolvedSessionId]
      or nil
    local delivery = type(deliveryStates) == "table" and deliveryStates[targetKey] or nil
    if type(delivery) ~= "table" and type(deliveryStates) == "table" then
      -- CHAT_MSG_ADDON may supply an equivalent character key with different realm formatting.
      for storedMemberKey, candidate in pairs(deliveryStates) do
        if type(candidate) == "table" and AreCharacterKeysSame(storedMemberKey, targetKey) then
          delivery = candidate
          break
        end
      end
    end
    if type(delivery) ~= "table" then
      return false
    end
    delivery.state = string.upper(TrimText(receiptState)) == "RECEIVED" and "CONFIRMED" or "REJECTED"
    delivery.receiptState = string.upper(TrimText(receiptState))
    delivery.reason = TrimText(reason)
    delivery.updatedAt = profileSyncMetaOps.getInviteDeliveryTime()
    sessionRuntime.inviteDeliveryTimerToken =
      math.max(0, tonumber(sessionRuntime.inviteDeliveryTimerToken) or 0) + 1
    delivery.timerToken = sessionRuntime.inviteDeliveryTimerToken
    sessionUiOps.refreshSyncManagementSection({ defer = true })
    return true
  end

  function sessionLifecycleOps.handleOutboundStartSent(metadata, sentAt)
    metadata = type(metadata) == "table" and metadata or {}
    local sessionId = TrimText(metadata.sessionId)
    local targetKey = NormalizeCharacterKey(FirstNonEmptyText(metadata.memberKey, metadata.target))
    local deliveryStates = type(sessionRuntime.pendingInviteDeliveries[sessionId]) == "table"
      and sessionRuntime.pendingInviteDeliveries[sessionId]
      or nil
    if sessionId == "" or type(deliveryStates) ~= "table" then
      return false, "missing_invite_delivery"
    end

    local marked = 0
    local function MarkDeliverySent(storedMemberKey, delivery)
      if type(delivery) ~= "table" then
        return
      end
      local state = string.upper(TrimText(delivery.state))
      if state == "CONFIRMED" or state == "REJECTED" or state == "TIMED_OUT" or state == "CANCELLED" then
        return
      end
      delivery.attempts = math.max(0, tonumber(delivery.attempts) or 0) + 1
      delivery.state = "AWAITING_RECEIPT"
      delivery.lastSentAt = math.max(0, tonumber(sentAt) or profileSyncMetaOps.getInviteDeliveryTime())
      delivery.updatedAt = profileSyncMetaOps.getInviteDeliveryTime()
      delivery.error = ""
      sessionLifecycleOps.armInviteDeliveryCheck(
        delivery,
        sessionId,
        NormalizeCharacterKey(storedMemberKey),
        sessionConfig.inviteReceiptTimeoutSeconds
      )
      marked = marked + 1
    end

    if targetKey ~= "" then
      local delivery = deliveryStates[targetKey]
      local storedKey = targetKey
      if type(delivery) ~= "table" then
        for candidateKey, candidate in pairs(deliveryStates) do
          if AreCharacterKeysSame(candidateKey, targetKey) then
            delivery = candidate
            storedKey = candidateKey
            break
          end
        end
      end
      MarkDeliverySent(storedKey, delivery)
    else
      -- A raid/party START is one successful send covering every delivery
      -- record created for that announcement.
      for storedKey, delivery in pairs(deliveryStates) do
        if string.upper(TrimText(type(delivery) == "table" and delivery.state or "")) == "QUEUED" then
          MarkDeliverySent(storedKey, delivery)
        end
      end
    end
    if marked > 0 then
      sessionUiOps.refreshSyncManagementSection({ defer = true })
      return true, marked
    end
    return false, "no_matching_invite_delivery"
  end
  INTERNAL_API.LIDCOUNCIL_HandleOutboundStartSent_Impl = sessionLifecycleOps.handleOutboundStartSent

  function sessionLifecycleOps.handleInviteReceiptTimeout(sessionId, memberKey, timerToken)
    local resolvedSessionId = TrimText(sessionId)
    local targetKey = NormalizeCharacterKey(memberKey)
    local delivery = type(sessionRuntime.pendingInviteDeliveries[resolvedSessionId]) == "table"
      and sessionRuntime.pendingInviteDeliveries[resolvedSessionId][targetKey]
      or nil
    if type(delivery) ~= "table" or tonumber(delivery.timerToken) ~= tonumber(timerToken) then
      return false, "stale_invite_delivery_timer"
    end
    local deliveryState = string.upper(TrimText(delivery.state))
    if deliveryState ~= "AWAITING_RECEIPT" and deliveryState ~= "QUEUED" and deliveryState ~= "RETRYING" then
      return false, "invite_delivery_already_resolved"
    end

    local activeSession, activeProfileName = GetActiveLootSession()
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if type(activeSession) ~= "table"
      or not DoesActiveSessionMatch(activeSession, activeProfileName, resolvedSessionId, delivery.profileName)
      or not AreCharacterKeysSame(activeSession.host, selfKey)
      or not IsCurrentGroupCharacter(targetKey)
    then
      delivery.state = "CANCELLED"
      delivery.updatedAt = profileSyncMetaOps.getInviteDeliveryTime()
      sessionUiOps.refreshSyncManagementSection({ defer = true })
      return false, "invite_delivery_no_longer_applicable"
    end

    local queueStatus = sessionLifecycleOps.getJoinOutboundQueueStatus()
    local receiptDecision = INTERNAL_API.LIDCOUNCIL_ResolveInviteReceiptAction_Impl(
      delivery,
      queueStatus,
      {
        maxAttempts = sessionConfig.inviteReceiptMaxAttempts,
        queuePollSeconds = sessionConfig.inviteReceiptQueuePollSeconds,
        blockedPollSeconds = sessionConfig.inviteReceiptBlockedPollSeconds,
      }
    )
    if receiptDecision.action == "wait_blocked" or receiptDecision.action == "wait_queued" then
      delivery.updatedAt = profileSyncMetaOps.getInviteDeliveryTime()
      local scheduled, scheduleReason = sessionLifecycleOps.armInviteDeliveryCheck(
        delivery,
        resolvedSessionId,
        targetKey,
        receiptDecision.delaySeconds
      )
      sessionUiOps.refreshSyncManagementSection({ defer = true })
      return scheduled, scheduled and (receiptDecision.action == "wait_blocked"
        and "invite_delivery_transport_blocked" or "invite_delivery_still_queued") or scheduleReason
    end

    if receiptDecision.action == "timeout" then
      delivery.state = "TIMED_OUT"
      delivery.updatedAt = profileSyncMetaOps.getInviteDeliveryTime()
      Print(sessionLifecycleOps.buildFlowNoticeText("invite_receipt_timeout", {
        memberKey = targetKey,
        attempts = delivery.attempts,
      }))
      sessionUiOps.refreshSyncManagementSection({ defer = true })
      return false, "invite_receipt_timeout"
    end

    delivery.state = "RETRYING"
    delivery.updatedAt = profileSyncMetaOps.getInviteDeliveryTime()
    if deliveryState == "AWAITING_RECEIPT" then
      Print(sessionLifecycleOps.buildFlowNoticeText("invite_receipt_retry", {
        memberKey = targetKey,
      }))
    end
    local queued, sendError = sessionLifecycleOps.queueInviteStart(activeSession, targetKey)
    if queued ~= true then
      delivery.state = "SEND_FAILED"
      delivery.error = TrimText(sendError)
      delivery.updatedAt = profileSyncMetaOps.getInviteDeliveryTime()
      Print(sessionLifecycleOps.buildFlowNoticeText("invite_retry_send_failed", {
        memberKey = targetKey,
        error = delivery.error,
      }))
      sessionUiOps.refreshSyncManagementSection({ defer = true })
      return false, delivery.error
    end

    delivery.queueAttempts = math.max(0, tonumber(delivery.queueAttempts) or 0) + 1
    delivery.state = "QUEUED"
    delivery.updatedAt = profileSyncMetaOps.getInviteDeliveryTime()
    local scheduled, scheduleReason = sessionLifecycleOps.armInviteDeliveryCheck(
      delivery,
      resolvedSessionId,
      targetKey,
      sessionConfig.inviteReceiptQueuePollSeconds
    )
    if scheduled ~= true then
      sessionUiOps.refreshSyncManagementSection({ defer = true })
      return false, scheduleReason
    end
    sessionUiOps.refreshSyncManagementSection({ defer = true })
    return true
  end

  function sessionLifecycleOps.getInviteDeliveryStatus()
    local activeSession, activeProfileName = GetActiveLootSession()
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    local sessionId = TrimText(type(activeSession) == "table" and activeSession.id or "")
    local deliveryStates = type(sessionRuntime.pendingInviteDeliveries[sessionId]) == "table"
      and sessionRuntime.pendingInviteDeliveries[sessionId]
      or {}
    local status = {
      sessionId = sessionId,
      isHost = type(activeSession) == "table" and AreCharacterKeysSame(activeSession.host, selfKey) or false,
      total = 0,
      confirmed = 0,
      pending = 0,
      retrying = 0,
      rejected = 0,
      timedOut = 0,
      sendFailed = 0,
      cancelled = 0,
      entries = {},
    }
    if not status.isHost or sessionId == "" or not DoesActiveSessionMatch(activeSession, activeProfileName, sessionId, type(activeSession) == "table" and activeSession.profileName or "") then
      return status
    end
    for memberKey, delivery in pairs(deliveryStates) do
      if type(delivery) == "table" then
        local state = string.upper(TrimText(delivery.state))
        status.total = status.total + 1
        if state == "CONFIRMED" then
          status.confirmed = status.confirmed + 1
        elseif state == "RETRYING" then
          status.retrying = status.retrying + 1
        elseif state == "REJECTED" then
          status.rejected = status.rejected + 1
        elseif state == "TIMED_OUT" then
          status.timedOut = status.timedOut + 1
        elseif state == "SEND_FAILED" or state == "TIMER_UNAVAILABLE" then
          status.sendFailed = status.sendFailed + 1
        elseif state == "CANCELLED" then
          status.cancelled = status.cancelled + 1
        else
          status.pending = status.pending + 1
        end
        status.entries[#status.entries + 1] = {
          memberKey = NormalizeCharacterKey(memberKey),
          state = state,
          attempts = math.max(0, tonumber(delivery.attempts) or 0),
          queueAttempts = math.max(0, tonumber(delivery.queueAttempts) or 0),
          reason = FirstNonEmptyText(delivery.reason, delivery.error),
        }
      end
    end
    table.sort(status.entries, function(left, right)
      return string.lower(TrimText(left.memberKey)) < string.lower(TrimText(right.memberKey))
    end)
    return status
  end

  function sessionLifecycleOps.buildSyncNoticeText(eventKey, opts)
    opts = type(opts) == "table" and opts or {}
    local resolvedEventKey = TrimText(eventKey)
    local resolvedProfileName = tostring(opts.profileName or "Unknown")
    local resolvedMemberKey = tostring(opts.memberKey or "Unknown")
    local resolvedSender = tostring(opts.sender or "Unknown")
    local resentMemberRowCount = math.max(0, tonumber(opts.resentMemberRowCount) or 0)
    if resolvedEventKey == "join_ignored_session_mismatch" then
      return "Ignored JOIN from " .. resolvedMemberKey .. ": session mismatch."
    end
    if resolvedEventKey == "join_ignored_sender_mismatch" then
      return "Ignored JOIN from " .. resolvedSender .. ": sender does not match claimed member " .. resolvedMemberKey .. "."
    end
    if resolvedEventKey == "join_ignored_not_in_group" then
      return "Ignored JOIN from " .. resolvedMemberKey .. ": character is not in the current group."
    end
    if resolvedEventKey == "join_incompatible_build_active_session" then
      return resolvedMemberKey .. " could not join \"" .. resolvedProfileName .. "\" because their LidCouncil build is incompatible with the active session. Update both clients to the same build and try again."
    end
    if resolvedEventKey == "duplicate_join_recovered_queued" then
      local repairSummary = "queued the remaining shared profile repair."
      if opts.queuedFullFallback == true then
        repairSummary = "queued a full shared profile fallback."
      elseif opts.scopeEscalated == true then
        repairSummary = "queued a widened shared profile repair"
          .. BuildRepairScopeEscalationKindsSuffix(opts.scopeEscalationKinds)
          .. "."
      end
      return "Recovered duplicate JOIN from " .. resolvedMemberKey
        .. ": resent " .. tostring(resentMemberRowCount) .. " relevant member row(s) and "
        .. repairSummary
    end
    if resolvedEventKey == "duplicate_join_recovered_deferred" then
      return "Recovered duplicate JOIN from " .. resolvedMemberKey
        .. ": resent " .. tostring(resentMemberRowCount) .. " relevant member row(s) and deferred the remaining shared profile repair while patch manifests load."
    end
    if resolvedEventKey == "duplicate_join_recovered_noop" then
      return "Recovered duplicate JOIN from " .. resolvedMemberKey
        .. ": resent " .. tostring(resentMemberRowCount) .. " relevant member row(s) and no additional shared profile repair was needed."
    end
    if resolvedEventKey == "duplicate_join_recovered_failed" then
      return "Recovered duplicate JOIN from " .. resolvedMemberKey
        .. ": resent " .. tostring(resentMemberRowCount) .. " relevant member row(s), but the recovery repair could not be queued."
        .. (opts.error and (" " .. tostring(opts.error)) or "")
    end
    if resolvedEventKey == "remote_join_diverged" then
      return "Divergent shared profile data detected for \"" .. resolvedProfileName .. "\" from " .. resolvedMemberKey
        .. ". Remote newer: " .. tostring(opts.remoteDomainsText or "")
        .. ". Local newer: " .. tostring(opts.localDomainsText or "")
        .. ". Automatic sync was skipped."
    end
    if resolvedEventKey == "remote_join_member_newer" then
      return "Newer shared profile data was found from " .. resolvedMemberKey
        .. " for \"" .. resolvedProfileName .. "\" (" .. tostring(opts.role or "RAIDER") .. "). Newer domains: "
        .. tostring(opts.remoteDomainsText or "")
        .. ". Your current host copy was kept for now."
    end
    if resolvedEventKey == "deferred_join_repair_aligned" then
      return "Skipped the deferred shared profile repair for " .. resolvedMemberKey
        .. " because the finer repair scope was already aligned."
    end
    if resolvedEventKey == "deferred_join_repair_sent" then
      return "Queued the deferred shared profile repair for " .. resolvedMemberKey
        .. " after loading finer repair scopes."
    end
    if resolvedEventKey == "deferred_join_repair_waiting" then
      return "Deferred shared profile repair for " .. resolvedMemberKey
        .. " is waiting for patch manifests after loading finer repair scopes."
    end
    if resolvedEventKey == "deferred_join_repair_failed" then
      return "Deferred shared profile repair for " .. resolvedMemberKey
        .. " could not be queued after loading finer repair scopes."
        .. (opts.error and (" " .. tostring(opts.error)) or "")
    end
    if resolvedEventKey == "host_join_repair_pending" then
      return "Queued the first host repair for " .. resolvedMemberKey
        .. " and requested finer loot scopes before sending the remaining loot repair."
    end
    if resolvedEventKey == "host_join_repair_scopes_only" then
      return "Requested detailed loot scopes from " .. resolvedMemberKey
        .. " before sending the remaining host loot repair."
    end
    if resolvedEventKey == "host_join_repair_aligned" then
      return "Skipped the host shared profile repair for " .. resolvedMemberKey
        .. " because their remaining join repair scope was already aligned."
    end
    if resolvedEventKey == "host_join_repair_sent" then
      return "Queued the host shared profile repair for " .. resolvedMemberKey
        .. " because their copy was older in: " .. tostring(opts.localDomainsText or "") .. "."
    end
    if resolvedEventKey == "host_join_repair_failed" then
      return "Host shared profile repair for " .. resolvedMemberKey .. " could not be queued."
        .. (opts.error and (" " .. tostring(opts.error)) or "")
    end
    if resolvedEventKey == "bootstrap_queued_with_followup" then
      return "Queued the initial shared-profile bootstrap for " .. resolvedMemberKey
        .. " so roll choices can unlock sooner. Current session state, loot starter rows, and remaining loot history continue syncing in stages."
    end
    if resolvedEventKey == "bootstrap_queued_without_followup" then
      return "Queued the initial shared-profile bootstrap for " .. resolvedMemberKey
        .. ". Roll choices can unlock sooner once that bootstrap arrives."
    end
    if resolvedEventKey == "bootstrap_followup_queue_failed" then
      return "Background current-session / loot follow-up for " .. resolvedMemberKey .. " could not be queued: " .. tostring(opts.error or "")
    end
    if resolvedEventKey == "missing_member_copy_bootstrap_failed" then
      return "Initial shared-profile bootstrap for " .. resolvedMemberKey .. " could not be queued."
        .. (opts.error and (" " .. tostring(opts.error)) or "")
    end
    return ""
  end

  function sessionLifecycleOps.buildSyncRuntimeOpts(eventKey, opts)
    opts = type(opts) == "table" and opts or {}
    local resolvedEventKey = TrimText(eventKey)
    local event = sessionLifecycleOps.syncEvents[resolvedEventKey]
    local resolvedMemberKey = tostring(opts.memberKey or "Unknown")
    if type(event) ~= "table" then
      return {
        sender = opts.sender,
        refreshEditor = opts.refreshEditor,
      }
    end
    local runtimeStateMessage = ""
    if resolvedEventKey == "deferred_join_repair_sent" then
      runtimeStateMessage = resolvedMemberKey .. " joined with older shared data. Deferred finer repair sent."
    elseif resolvedEventKey == "deferred_join_repair_waiting" then
      runtimeStateMessage = resolvedMemberKey .. " joined with older shared data. Deferred finer repair is waiting for patch manifests."
    elseif resolvedEventKey == "deferred_join_repair_aligned" then
      runtimeStateMessage = resolvedMemberKey .. " join repair scope was already aligned after loading finer repair scopes."
    elseif resolvedEventKey == "deferred_join_repair_failed" then
      runtimeStateMessage = resolvedMemberKey .. " joined with older shared data, but the deferred finer repair could not be queued."
    elseif resolvedEventKey == "host_join_repair_sent" then
      runtimeStateMessage = resolvedMemberKey .. " joined with an older shared copy. Host repair sent."
    elseif resolvedEventKey == "host_join_repair_pending" then
      runtimeStateMessage = resolvedMemberKey .. " joined with an older shared copy. Initial host repair sent; finer loot repair is still pending."
    elseif resolvedEventKey == "host_join_repair_aligned" then
      runtimeStateMessage = resolvedMemberKey .. " joined with an older shared copy, but the remaining repair scope was already aligned."
    elseif resolvedEventKey == "host_join_repair_scopes_only" then
      runtimeStateMessage = resolvedMemberKey .. " joined with an older shared copy. Requested finer loot scopes before sending the remaining loot repair."
    elseif resolvedEventKey == "host_join_repair_failed" then
      runtimeStateMessage = resolvedMemberKey .. " joined with an older shared copy, but the host repair could not be queued."
    elseif resolvedEventKey == "missing_member_copy_bootstrap" then
      runtimeStateMessage = resolvedMemberKey .. " joined without a local shared copy. Sent the smaller roll-ready bootstrap and loot starter copy first."
    elseif resolvedEventKey == "missing_member_copy_bootstrap_failed" then
      runtimeStateMessage = resolvedMemberKey .. " joined without a local shared copy, but the initial bootstrap could not be queued."
    elseif resolvedEventKey == "remote_join_diverged" then
      runtimeStateMessage = resolvedMemberKey .. " joined with diverged shared profile data."
    elseif resolvedEventKey == "remote_join_member_newer" then
      runtimeStateMessage = resolvedMemberKey .. " joined with newer shared profile data."
    end
    return {
      runtimeStateKey = event.runtimeStateKey,
      runtimeStateLevel = event.runtimeStateLevel,
      runtimeStateMessage = runtimeStateMessage,
      sender = opts.sender,
      refreshEditor = opts.refreshEditor,
    }
  end

  function sessionLifecycleOps.buildInvitePopupText(opts)
    opts = type(opts) == "table" and opts or {}
    local resolvedHost = tostring(opts.host or "Unknown")
    local resolvedProfileName = tostring(opts.profileName or "Unknown")
    local inviteStatus = string.upper(TrimText(opts.status))
    local actionText = inviteStatus == "ACTIVE" and "started an active Loot Session" or "prepared a new Loot Session"
    local questionText = inviteStatus == "ACTIVE" and "Do you want to join the active session?" or "Do you want to join the preparation lobby?"
    return string.format(
      "%s %s with the profile \"%s\".\n\nBy joining, your local Auto Pass starts as ON by default. You can change that later in Session -> Auto Pass Setting.\n\n%s",
      resolvedHost,
      actionText,
      resolvedProfileName,
      questionText
    )
  end

  function sessionLifecycleOps.buildEndNoticeText(eventKey, opts)
    opts = type(opts) == "table" and opts or {}
    local resolvedProfileName = tostring(opts.profileName or "Unknown")
    local resolvedEventKey = TrimText(eventKey)
    if resolvedEventKey == "member_left" then
      if opts.notifiedHost == false then
        return "You left loot session \"" .. resolvedProfileName
          .. "\". The host could not be notified: " .. tostring(opts.notifyError or "leave message failed.")
      end
      return "You left loot session \"" .. resolvedProfileName .. "\"."
    end
    if resolvedEventKey == "host_stopped" then
      return "Stopped loot session \"" .. resolvedProfileName .. "\"."
    end
    if resolvedEventKey == "left_group" then
      return "Left the group. Local loot session \"" .. resolvedProfileName .. "\" was ended."
    end
    if resolvedEventKey == "remote_stopped" then
      return "Loot session \"" .. resolvedProfileName .. "\" ended by " .. tostring(opts.endedBy or "Unknown") .. "."
    end
    return ""
  end

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

  local function PruneAgedSessionRuntimeTracking(now)
    local currentTime = math.max(0, tonumber(now) or 0)
    if currentTime <= 0 then
      currentTime = GetProfileCheckpointSyncTime()
    end
    local lastPrunedAt = math.max(0, tonumber(sessionRuntime.lastRuntimeTrackingPruneAt) or 0)
    if lastPrunedAt > 0 and (currentTime - lastPrunedAt) < sessionConfig.runtimeTrackingPruneIntervalSeconds then
      return false
    end
    sessionRuntime.lastRuntimeTrackingPruneAt = currentTime

    local activeSessionForBroadcastDedupe = GetActiveLootSession()
    local activeBroadcastPrefix = type(activeSessionForBroadcastDedupe) == "table"
      and (string.lower(TrimText(activeSessionForBroadcastDedupe.id)) .. "|broadcast|")
      or ""
    for whisperKey, whisperState in pairs(sessionRuntime.recentMemberSnapshotWhispers) do
      local sentAt = math.max(0, tonumber(type(whisperState) == "table" and whisperState.sentAt or 0) or 0)
      local retainedActiveBroadcast = activeBroadcastPrefix ~= ""
        and type(whisperKey) == "string"
        and string.sub(whisperKey, 1, #activeBroadcastPrefix) == activeBroadcastPrefix
      if not retainedActiveBroadcast
        and (sentAt <= 0 or (currentTime - sentAt) >= sessionConfig.memberSnapshotWhisperRetentionSeconds)
      then
        sessionRuntime.recentMemberSnapshotWhispers[whisperKey] = nil
      end
    end
    for stateKey, stateInfo in pairs(sessionRuntime.recentStatePacketSends) do
      local sentAt = math.max(0, tonumber(type(stateInfo) == "table" and stateInfo.sentAt or 0) or 0)
      if sentAt <= 0 or (currentTime - sentAt) >= sessionConfig.statePacketSendRetentionSeconds then
        sessionRuntime.recentStatePacketSends[stateKey] = nil
      end
    end
    for stateKey, stateInfo in pairs(sessionRuntime.pendingProfileStateParts) do
      local updatedAt = math.max(0, tonumber(type(stateInfo) == "table" and stateInfo.updatedAt or 0) or 0)
      if updatedAt <= 0 or (currentTime - updatedAt) >= sessionConfig.profileStatePartRetentionSeconds then
        sessionRuntime.pendingProfileStateParts[stateKey] = nil
      end
    end
    for resendKey, resendState in pairs(sessionRuntime.recentDuplicateJoinRecoveryResends) do
      local sentAt = math.max(0, tonumber(type(resendState) == "table" and resendState.sentAt or 0) or 0)
      if sentAt <= 0 or (currentTime - sentAt) >= sessionConfig.duplicateJoinRecoveryResendRetentionSeconds then
        sessionRuntime.recentDuplicateJoinRecoveryResends[resendKey] = nil
      end
    end
    for bootstrapKey, bootstrapState in pairs(sessionRuntime.recentMissingMemberBootstrapRequests) do
      local queuedAt = math.max(0, tonumber(type(bootstrapState) == "table" and bootstrapState.queuedAt or 0) or 0)
      if queuedAt <= 0 or (currentTime - queuedAt) >= sessionConfig.missingMemberBootstrapRetentionSeconds then
        sessionRuntime.recentMissingMemberBootstrapRequests[bootstrapKey] = nil
      end
    end
    for requestKey, requestState in pairs(sessionRuntime.recentMemberRepairRequestStates) do
      local updatedAt = math.max(0, tonumber(type(requestState) == "table" and (requestState.updatedAt or requestState.queuedAt) or 0) or 0)
      if updatedAt <= 0 or (currentTime - updatedAt) >= sessionConfig.memberRepairRequestRetentionSeconds then
        sessionRuntime.recentMemberRepairRequestStates[requestKey] = nil
      end
    end
    for requestStamp, requestedAt in pairs(sessionRuntime.recentAutoSubcheckRequestTimes) do
      local resolvedRequestedAt = math.max(0, tonumber(requestedAt) or 0)
      if resolvedRequestedAt <= 0 or (currentTime - resolvedRequestedAt) >= sessionConfig.autoSubcheckRequestRetentionSeconds then
        sessionRuntime.recentAutoSubcheckRequestTimes[requestStamp] = nil
      end
    end
    for requestKey, requestState in pairs(sessionRuntime.recentMemberPrecisePrewarmRequests) do
      local requestedAt = math.max(0, tonumber(type(requestState) == "table" and (requestState.requestedAt or requestState.updatedAt) or 0) or 0)
      if requestedAt <= 0 or (currentTime - requestedAt) >= sessionConfig.memberPrecisePrewarmRetentionSeconds then
        sessionRuntime.recentMemberPrecisePrewarmRequests[requestKey] = nil
      end
    end
    for pendingKey, pendingState in pairs(sessionRuntime.pendingAutoDetailedComparisonTimers) do
      local queuedAt = math.max(0, tonumber(type(pendingState) == "table" and (pendingState.updatedAt or pendingState.queuedAt) or 0) or 0)
      if queuedAt <= 0 or (currentTime - queuedAt) >= sessionConfig.autoDetailedComparisonTimerRetentionSeconds then
        sessionRuntime.pendingAutoDetailedComparisonTimers[pendingKey] = nil
      end
    end
    for pendingKey, pendingState in pairs(sessionRuntime.pendingPostBootstrapRevalidationTimers) do
      local queuedAt = math.max(0, tonumber(type(pendingState) == "table" and (pendingState.updatedAt or pendingState.queuedAt) or 0) or 0)
      if queuedAt <= 0 or (currentTime - queuedAt) >= sessionConfig.autoDetailedComparisonTimerRetentionSeconds then
        sessionRuntime.pendingPostBootstrapRevalidationTimers[pendingKey] = nil
      end
    end
    for pendingKey, pendingState in pairs(sessionRuntime.pendingAckTimeoutRevalidations) do
      local requestedAt = math.max(0, tonumber(type(pendingState) == "table" and (pendingState.updatedAt or pendingState.requestedAt) or 0) or 0)
      if requestedAt <= 0 or (currentTime - requestedAt) >= sessionConfig.ackTimeoutRevalidationRetentionSeconds then
        sessionRuntime.pendingAckTimeoutRevalidations[pendingKey] = nil
      end
    end
    for broadcastKey, pendingState in pairs(sessionRuntime.pendingSessionMemberBroadcasts) do
      local updatedAt = math.max(0, tonumber(type(pendingState) == "table" and (pendingState.updatedAt or pendingState.queuedAt) or 0) or 0)
      if updatedAt <= 0 or (currentTime - updatedAt) >= sessionConfig.pendingSessionMemberBroadcastRetentionSeconds then
        sessionRuntime.pendingSessionMemberBroadcasts[broadcastKey] = nil
      end
    end
    for inviteSessionId, inviteState in pairs(sessionRuntime.pendingInvites) do
      local receivedAt = math.max(0, tonumber(type(inviteState) == "table" and inviteState.receivedAt or 0) or 0)
      if receivedAt <= 0 or (currentTime - receivedAt) >= sessionConfig.pendingInviteRetentionSeconds then
        sessionRuntime.pendingInvites[inviteSessionId] = nil
      end
    end
    for inviteSessionId, receiptStates in pairs(sessionRuntime.inviteReceipts) do
      local hasRecentReceipt = false
      if type(receiptStates) == "table" then
        for memberKey, receiptState in pairs(receiptStates) do
          local receivedAt = math.max(0, tonumber(type(receiptState) == "table" and receiptState.receivedAt or 0) or 0)
          if receivedAt <= 0 or (currentTime - receivedAt) >= sessionConfig.inviteReceiptRetentionSeconds then
            receiptStates[memberKey] = nil
          else
            hasRecentReceipt = true
          end
        end
      end
      if not hasRecentReceipt then
        sessionRuntime.inviteReceipts[inviteSessionId] = nil
      end
    end
    for inviteSessionId, deliveryStates in pairs(sessionRuntime.pendingInviteDeliveries) do
      local hasRecentDelivery = false
      if type(deliveryStates) == "table" then
        for memberKey, deliveryState in pairs(deliveryStates) do
          local updatedAt = math.max(0, tonumber(type(deliveryState) == "table"
            and (deliveryState.updatedAt or deliveryState.queuedAt) or 0) or 0)
          if updatedAt <= 0 or (currentTime - updatedAt) >= sessionConfig.inviteDeliveryRetentionSeconds then
            deliveryStates[memberKey] = nil
          else
            hasRecentDelivery = true
          end
        end
      end
      if not hasRecentDelivery then
        sessionRuntime.pendingInviteDeliveries[inviteSessionId] = nil
      end
    end
    for token, finalizationState in pairs(sessionRuntime.pendingSessionFinalizations) do
      local updatedAt = math.max(0, tonumber(type(finalizationState) == "table"
        and (finalizationState.updatedAt or finalizationState.queuedAt) or 0) or 0)
      if updatedAt <= 0 or (currentTime - updatedAt) >= sessionConfig.sessionFinalizationRetentionSeconds then
        sessionRuntime.pendingSessionFinalizations[token] = nil
      end
    end
    for token, receiptState in pairs(sessionRuntime.recentSessionFinalizationReceipts) do
      local receivedAt = math.max(0, tonumber(type(receiptState) == "table"
        and (receiptState.receivedAt or receiptState.updatedAt) or 0) or 0)
      if receivedAt <= 0 or (currentTime - receivedAt) >= sessionConfig.sessionFinalizationReceiptRetentionSeconds then
        sessionRuntime.recentSessionFinalizationReceipts[token] = nil
      end
    end
    for sessionId, requestState in pairs(sessionRuntime.pendingJoinRequests) do
      local updatedAt = math.max(0, tonumber(type(requestState) == "table" and (requestState.updatedAt or requestState.queuedAt or requestState.joinedAt) or 0) or 0)
      local lateAckUntil = math.max(0, tonumber(type(requestState) == "table" and requestState.acceptLateAckUntil or 0) or 0)
      local lateAckGraceExpired = type(requestState) == "table"
        and requestState.state == "TIMED_OUT"
        and lateAckUntil > 0
        and currentTime >= lateAckUntil
      if lateAckGraceExpired
        or updatedAt <= 0
        or (currentTime - updatedAt) >= sessionConfig.pendingJoinRequestRetentionSeconds
      then
        sessionRuntime.pendingJoinRequests[sessionId] = nil
        sessionRuntime.pendingInvites[sessionId] = nil
      end
    end
    for pendingKey, pendingState in pairs(sessionRuntime.pendingJoinManifestRepairTimers.joinManifest) do
      local updatedAt = math.max(0, tonumber(type(pendingState) == "table" and (pendingState.updatedAt or pendingState.queuedAt) or 0) or 0)
      if updatedAt <= 0 or (currentTime - updatedAt) >= sessionConfig.pendingJoinManifestRepairRetentionSeconds then
        if type(pendingState) == "table"
          and pendingState.requirePreciseProof == true
          and type(profileSyncMetaOps.markJoinManifestProofTerminal) == "function"
        then
          profileSyncMetaOps.markJoinManifestProofTerminal(
            pendingState,
            "precise_archive_proof_pending_state_expired"
          )
        end
        sessionRuntime.pendingJoinManifestRepairTimers.joinManifest[pendingKey] = nil
      end
    end
    for pendingKey, pendingState in pairs(sessionRuntime.pendingJoinManifestRepairTimers.patchStateRetry) do
      local updatedAt = math.max(0, tonumber(type(pendingState) == "table" and (pendingState.updatedAt or pendingState.queuedAt) or 0) or 0)
      if updatedAt <= 0 or (currentTime - updatedAt) >= sessionConfig.pendingPatchStateRetryRetentionSeconds then
        sessionRuntime.pendingJoinManifestRepairTimers.patchStateRetry[pendingKey] = nil
      end
    end
    for timerKey, timerState in pairs(sessionRuntime.pendingMissingMemberHistoryTimers) do
      local updatedAt = math.max(0, tonumber(type(timerState) == "table" and (timerState.updatedAt or timerState.queuedAt) or 0) or 0)
      if updatedAt <= 0 or (currentTime - updatedAt) >= sessionConfig.pendingMissingMemberHistoryTimerRetentionSeconds then
        sessionRuntime.pendingMissingMemberHistoryTimers[timerKey] = nil
      end
    end
    for pendingKey, pendingState in pairs(sessionRuntime.pendingProfileCheckpointSyncs) do
      local updatedAt = math.max(0, tonumber(type(pendingState) == "table" and (pendingState.updatedAt or pendingState.queuedAt) or 0) or 0)
      if updatedAt <= 0 or (currentTime - updatedAt) >= sessionConfig.pendingProfileCheckpointRetentionSeconds then
        sessionRuntime.pendingProfileCheckpointSyncs[pendingKey] = nil
        sessionRuntime.pendingProfileCheckpointTimers[pendingKey] = nil
      end
    end
    for timerKey, timerState in pairs(sessionRuntime.pendingProfileCheckpointTimers) do
      local queuedAt = math.max(0, tonumber(type(timerState) == "table" and timerState.queuedAt or 0) or 0)
      if queuedAt <= 0 or (currentTime - queuedAt) >= sessionConfig.pendingProfileCheckpointRetentionSeconds then
        sessionRuntime.pendingProfileCheckpointTimers[timerKey] = nil
      end
    end
    for checkpointKey, lastSentAt in pairs(sessionRuntime.lastProfileCheckpointSyncAt) do
      local resolvedLastSentAt = math.max(0, tonumber(lastSentAt) or 0)
      if resolvedLastSentAt <= 0 or (currentTime - resolvedLastSentAt) >= sessionConfig.lastProfileCheckpointSyncRetentionSeconds then
        sessionRuntime.lastProfileCheckpointSyncAt[checkpointKey] = nil
      end
    end
    for checkpointKey, checkpointState in pairs(sessionRuntime.recentSessionMemberCheckpointStates) do
      local queuedAt = math.max(0, tonumber(type(checkpointState) == "table" and checkpointState.queuedAt or 0) or 0)
      if queuedAt <= 0 or (currentTime - queuedAt) >= sessionConfig.recentSessionMemberCheckpointRetentionSeconds then
        sessionRuntime.recentSessionMemberCheckpointStates[checkpointKey] = nil
      end
    end
    for requestKey, requestState in pairs(sessionRuntime.recentProfileCheckpointRequestStates) do
      local sentAt = math.max(0, tonumber(type(requestState) == "table" and requestState.sentAt or 0) or 0)
      if sentAt <= 0 or (currentTime - sentAt) >= sessionConfig.recentProfileCheckpointRequestRetentionSeconds then
        sessionRuntime.recentProfileCheckpointRequestStates[requestKey] = nil
      end
    end
    for emissionKey, emissionState in pairs(sessionRuntime.recentRuntimeStateEmissionStates) do
      local updatedAt = math.max(0, tonumber(type(emissionState) == "table" and (emissionState.updatedAt or emissionState.emittedAt) or 0) or 0)
      if updatedAt <= 0 or (currentTime - updatedAt) >= sessionConfig.runtimeStateEmissionRetentionSeconds then
        sessionRuntime.recentRuntimeStateEmissionStates[emissionKey] = nil
      end
    end
    if type(profileSyncMetaOps.recentAutomaticHostRepairRequestStates) == "table" then
      for requestKey, requestState in pairs(profileSyncMetaOps.recentAutomaticHostRepairRequestStates) do
        local queuedAt = math.max(0, tonumber(type(requestState) == "table" and requestState.queuedAt or 0) or 0)
        if queuedAt <= 0 or (currentTime - queuedAt) >= sessionConfig.automaticHostRepairRequestRetentionSeconds then
          profileSyncMetaOps.recentAutomaticHostRepairRequestStates[requestKey] = nil
        end
      end
    end
    for changeId, pendingAck in pairs(sessionRuntime.pendingProfileDeltaAcks) do
      local updatedAt = math.max(0, tonumber(type(pendingAck) == "table" and (pendingAck.updatedAt or pendingAck.queuedAt) or 0) or 0)
      if (updatedAt <= 0 or (currentTime - updatedAt) >= sessionConfig.pendingProfileDeltaAckRetentionSeconds)
        and not next(type(pendingAck) == "table" and type(pendingAck.queued) == "table" and pendingAck.queued or {})
      then
        sessionRuntime.pendingProfileDeltaAcks[changeId] = nil
      end
    end
    for changeId, seenState in pairs(sessionRuntime.appliedProfileDeltaIds) do
      local seenAt = math.max(0, tonumber(type(seenState) == "table" and seenState.seenAt or 0) or 0)
      if seenAt <= 0 or (currentTime - seenAt) >= sessionConfig.profileDeltaSeenRetentionSeconds then
        sessionRuntime.appliedProfileDeltaIds[changeId] = nil
      end
    end
    for runtimeKey, sequenceState in pairs(sessionRuntime.profileDeltaLastSequence) do
      local updatedAt = math.max(0, tonumber(type(sequenceState) == "table" and sequenceState.updatedAt or 0) or 0)
      if updatedAt <= 0 or (currentTime - updatedAt) >= sessionConfig.profileDeltaSequenceRetentionSeconds then
        sessionRuntime.profileDeltaLastSequence[runtimeKey] = nil
      end
    end
    for requestKey, requestState in pairs(sessionRuntime.recentProfileDeltaRecoveryRequests) do
      local requestedAt = math.max(0, tonumber(type(requestState) == "table" and requestState.requestedAt or 0) or 0)
      if requestedAt <= 0 or (currentTime - requestedAt) >= sessionConfig.profileDeltaRecoveryRequestRetentionSeconds then
        sessionRuntime.recentProfileDeltaRecoveryRequests[requestKey] = nil
      end
    end
    for sourceKey, sourceState in pairs(sessionRuntime.recentProfileDeltaRecoverySources) do
      local rememberedAt = math.max(0, tonumber(type(sourceState) == "table" and sourceState.rememberedAt or 0) or 0)
      if rememberedAt <= 0 or (currentTime - rememberedAt) >= sessionConfig.profileDeltaRecoverySourceRetentionSeconds then
        sessionRuntime.recentProfileDeltaRecoverySources[sourceKey] = nil
      end
    end
    return true
  end

  local function GetInviteProtocolVersion(fieldValue)
    if type(deps.ParseCommProtocolMarker) == "function" then
      return deps.ParseCommProtocolMarker(fieldValue)
    end
    return nil
  end

  function profileSyncMetaOps.hasRequiredInboundFields(fields, lastIndex)
    if type(fields) ~= "table" then
      return false
    end
    for index = 2, math.max(2, tonumber(lastIndex) or 0) do
      if fields[index] == nil then
        return false
      end
    end
    return true
  end

  function profileSyncMetaOps.parseInboundNumberField(fields, index, opts)
    opts = type(opts) == "table" and opts or {}
    if type(fields) ~= "table" then
      return nil, false
    end
    local rawValue = fields[index]
    if rawValue == nil then
      return opts.emptyValue, opts.allowMissing == true
    end
    local valueText = TrimText(rawValue)
    if valueText == "" then
      if opts.allowEmpty == true then
        return opts.emptyValue, true
      end
      return nil, false
    end
    local value = tonumber(valueText)
    if value == nil then
      return nil, false
    end
    if opts.floorZero ~= false then
      value = math.max(0, value)
    end
    return value, true
  end

  function profileSyncMetaOps.parseInboundProtocolVersionField(fields, index, opts)
    opts = type(opts) == "table" and opts or {}
    if type(fields) ~= "table" then
      return opts.emptyValue, opts.allowMissing == true
    end
    local rawValue = fields[index]
    if rawValue == nil then
      return opts.emptyValue, opts.allowMissing == true
    end
    local valueText = TrimText(rawValue)
    if valueText == "" then
      if opts.allowEmpty == true then
        return opts.emptyValue, true
      end
      return opts.emptyValue, opts.allowMissing == true
    end
    local parsed = GetInviteProtocolVersion(valueText)
    if tonumber(parsed) == nil then
      return nil, false
    end
    return math.max(0, tonumber(parsed) or 0), true
  end

  function profileSyncMetaOps.recordInboundPayloadReject(opcode, sender, fields, reason)
    if type(RecordProfileSyncDecision) ~= "function" then
      return
    end
    local rejectionAction, rejectionCategory = "rejected_malformed_payload", "malformed"
    if type(INTERNAL_API.LIDCOUNCIL_GetInboundRejectDecisionAction_Impl) == "function" then
      rejectionAction, rejectionCategory = INTERNAL_API.LIDCOUNCIL_GetInboundRejectDecisionAction_Impl(reason)
    end
    RecordProfileSyncDecision("incoming_payload", {
      action = rejectionAction,
      rejectionCategory = rejectionCategory,
      opcode = TrimText(opcode),
      sender = NormalizeCharacterKey(sender),
      sessionId = type(fields) == "table" and TrimText(fields[2]) or "",
      profileName = type(fields) == "table" and TrimText(fields[3]) or "",
      reason = TrimText(reason),
      fieldCount = type(fields) == "table" and math.max(0, #fields) or 0,
    })
  end

  function profileSyncMetaOps.parseInboundMemberPayload(fields)
    if not profileSyncMetaOps.hasRequiredInboundFields(fields, 30) then
      return nil, "truncated_member_payload"
    end
    local sessionId = TrimText(fields[2])
    local profileName = TrimText(fields[3])
    local memberKey = NormalizeCharacterKey(fields[4])
    if sessionId == "" or profileName == "" or memberKey == "" then
      return nil, "missing_member_identity"
    end
    local status = string.upper(TrimText(fields[5]))
    if status == "" then
      status = "JOINED"
    end
    if status ~= "JOINED" and status ~= "LEFT" and status ~= "REMOVED" then
      return nil, "invalid_member_status"
    end
    local joinedAt, joinedAtValid = profileSyncMetaOps.parseInboundNumberField(fields, 6)
    if not joinedAtValid then
      return nil, "invalid_member_joined_at"
    end
    local settingsRevision, settingsRevisionValid = profileSyncMetaOps.parseInboundNumberField(fields, 17)
    if not settingsRevisionValid then
      return nil, "invalid_member_settings_revision"
    end
    local permissionsRevision, permissionsRevisionValid = profileSyncMetaOps.parseInboundNumberField(fields, 18)
    if not permissionsRevisionValid then
      return nil, "invalid_member_permissions_revision"
    end
    local operationalRevision, operationalRevisionValid = profileSyncMetaOps.parseInboundNumberField(fields, 19)
    if not operationalRevisionValid then
      return nil, "invalid_member_operational_revision"
    end
    local profileUpdatedAt, profileUpdatedAtValid = profileSyncMetaOps.parseInboundNumberField(fields, 20)
    if not profileUpdatedAtValid then
      return nil, "invalid_member_profile_updated_at"
    end
    local leftAt, leftAtValid = profileSyncMetaOps.parseInboundNumberField(fields, 24, {
      allowEmpty = true,
      emptyValue = nil,
    })
    if not leftAtValid then
      return nil, "invalid_member_left_at"
    end
    local lootRevision, lootRevisionValid = profileSyncMetaOps.parseInboundNumberField(fields, 25)
    if not lootRevisionValid then
      return nil, "invalid_member_loot_revision"
    end
    local sessionRevision, sessionRevisionValid = profileSyncMetaOps.parseInboundNumberField(fields, 26)
    if not sessionRevisionValid then
      return nil, "invalid_member_session_revision"
    end
    local operationalChecksum = TrimText(fields[23])
    local lootChecksum = TrimText(fields[27])
    if lootChecksum == "" then
      lootChecksum = operationalChecksum
    end
    local sessionChecksum = TrimText(fields[28])
    if sessionChecksum == "" then
      sessionChecksum = operationalChecksum
    end
    local lastSyncAt = nil
    if TrimText(fields[31]) ~= "" then
      local parsedLastSyncAt, parsedLastSyncAtValid = profileSyncMetaOps.parseInboundNumberField(fields, 31)
      if not parsedLastSyncAtValid then
        return nil, "invalid_member_last_sync_at"
      end
      lastSyncAt = parsedLastSyncAt
    end
    local lastDeltaRecoveryAt = nil
    if TrimText(fields[38]) ~= "" then
      local parsedLastDeltaRecoveryAt, parsedLastDeltaRecoveryAtValid = profileSyncMetaOps.parseInboundNumberField(fields, 38)
      if not parsedLastDeltaRecoveryAtValid then
        return nil, "invalid_member_last_delta_recovery_at"
      end
      lastDeltaRecoveryAt = parsedLastDeltaRecoveryAt
    end
    local lastDeltaRecoveryScopeEscalated = nil
    if TrimText(fields[35]) ~= "" then
      lastDeltaRecoveryScopeEscalated = deps.NormalizeEnabledFlag(fields[35], false) and true or false
    end
    local lastDeltaRecoveryFullSnapshotFallback = nil
    if TrimText(fields[36]) ~= "" then
      lastDeltaRecoveryFullSnapshotFallback = deps.NormalizeEnabledFlag(fields[36], false) and true or false
    end
    return {
      sessionId = sessionId,
      profileName = profileName,
      memberKey = memberKey,
      status = status,
      joinedAt = joinedAt,
      addonVersion = TrimText(fields[7]),
      clientVersion = TrimText(fields[8]),
      className = TrimText(fields[9]),
      classFile = TrimText(fields[10]),
      specName = TrimText(fields[11]),
      specIcon = TrimText(fields[12]),
      localAutoPassEnabled = deps.NormalizeEnabledFlag(fields[13], true),
      profileMaster = TrimText(fields[14]),
      role = TrimText(fields[15]),
      sharedProfileId = TrimText(fields[16]),
      settingsRevision = settingsRevision,
      permissionsRevision = permissionsRevision,
      operationalRevision = operationalRevision,
      lootRevision = lootRevision,
      sessionRevision = sessionRevision,
      profileUpdatedAt = profileUpdatedAt,
      settingsChecksum = TrimText(fields[21]),
      permissionsChecksum = TrimText(fields[22]),
      operationalChecksum = operationalChecksum,
      lootChecksum = lootChecksum,
      sessionChecksum = sessionChecksum,
      liveLootChecksum = TrimText(fields[29]),
      archiveLootChecksum = TrimText(fields[30]),
      leftAt = leftAt,
      lastSyncAt = lastSyncAt,
      lastDeltaRecoveryState = TrimText(fields[32]),
      lastDeltaRecoveryKind = TrimText(fields[33]),
      lastDeltaRecoveryRequestedScope = TrimText(fields[34]),
      lastDeltaRecoveryScopeEscalated = lastDeltaRecoveryScopeEscalated,
      lastDeltaRecoveryFullSnapshotFallback = lastDeltaRecoveryFullSnapshotFallback,
      lastDeltaRecoveryScopeEscalationKinds = TrimText(fields[37]),
      lastDeltaRecoveryAt = lastDeltaRecoveryAt,
      lastDeltaRecoverySummary = TrimText(fields[39]),
      lootListArchiveChecksum = TrimText(fields[40]),
      itemHistoryArchiveChecksum = TrimText(fields[41]),
      sessionHistoryArchiveChecksum = TrimText(fields[42]),
      funAwardsArchiveChecksum = TrimText(fields[43]),
      hostSyncStatusMatrix = type(profileSyncMetaOps.decodeHostMemberStatusMatrix(fields[44])) == "table"
        and TrimText(fields[44])
        or "",
      hostSyncStatusGeneration = tonumber(fields[45]) or 0,
    }, nil
  end

  function profileSyncMetaOps.parseInboundProfileStatePayload(fields, sender)
    if not profileSyncMetaOps.hasRequiredInboundFields(fields, 19) then
      return nil, "truncated_profile_state_payload"
    end
    local sessionId = TrimText(fields[2])
    local profileName = TrimText(fields[3])
    local memberKey = NormalizeCharacterKey(TrimText(fields[4]) ~= "" and fields[4] or sender)
    if sessionId == "" or profileName == "" or memberKey == "" then
      return nil, "missing_profile_state_identity"
    end
    local settingsRevision, settingsRevisionValid = profileSyncMetaOps.parseInboundNumberField(fields, 6)
    if not settingsRevisionValid then
      return nil, "invalid_profile_state_settings_revision"
    end
    local permissionsRevision, permissionsRevisionValid = profileSyncMetaOps.parseInboundNumberField(fields, 7)
    if not permissionsRevisionValid then
      return nil, "invalid_profile_state_permissions_revision"
    end
    local operationalRevision, operationalRevisionValid = profileSyncMetaOps.parseInboundNumberField(fields, 8)
    if not operationalRevisionValid then
      return nil, "invalid_profile_state_operational_revision"
    end
    local profileUpdatedAt, profileUpdatedAtValid = profileSyncMetaOps.parseInboundNumberField(fields, 9)
    if not profileUpdatedAtValid then
      return nil, "invalid_profile_state_profile_updated_at"
    end
    local lootRevision, lootRevisionValid = profileSyncMetaOps.parseInboundNumberField(fields, 13)
    if not lootRevisionValid then
      return nil, "invalid_profile_state_loot_revision"
    end
    local sessionRevision, sessionRevisionValid = profileSyncMetaOps.parseInboundNumberField(fields, 14)
    if not sessionRevisionValid then
      return nil, "invalid_profile_state_session_revision"
    end
    local protocolVersion = GetInviteProtocolVersion(fields[19])
    if tonumber(protocolVersion) == nil then
      return nil, "invalid_profile_state_protocol"
    end
    local operationalChecksum = TrimText(fields[12])
    local lootChecksum = TrimText(fields[15])
    if lootChecksum == "" then
      lootChecksum = operationalChecksum
    end
    local sessionChecksum = TrimText(fields[16])
    if sessionChecksum == "" then
      sessionChecksum = operationalChecksum
    end
    local lootListArchiveChecksum = TrimText(fields[20])
    local itemHistoryArchiveChecksum = TrimText(fields[21])
    local sessionHistoryArchiveChecksum = TrimText(fields[22])
    local funAwardsArchiveChecksum = TrimText(fields[23])
    return {
      sessionId = sessionId,
      profileName = profileName,
      memberKey = memberKey,
      sharedProfileId = TrimText(fields[5]),
      settingsRevision = settingsRevision,
      permissionsRevision = permissionsRevision,
      operationalRevision = operationalRevision,
      lootRevision = lootRevision,
      sessionRevision = sessionRevision,
      profileUpdatedAt = profileUpdatedAt,
      settingsChecksum = TrimText(fields[10]),
      permissionsChecksum = TrimText(fields[11]),
      operationalChecksum = operationalChecksum,
      lootChecksum = lootChecksum,
      sessionChecksum = sessionChecksum,
      liveLootChecksum = TrimText(fields[17]),
      archiveLootChecksum = TrimText(fields[18]),
      lootListArchiveChecksum = lootListArchiveChecksum,
      itemHistoryArchiveChecksum = itemHistoryArchiveChecksum,
      sessionHistoryArchiveChecksum = sessionHistoryArchiveChecksum,
      funAwardsArchiveChecksum = funAwardsArchiveChecksum,
      archiveProofAvailable = lootListArchiveChecksum ~= ""
        or itemHistoryArchiveChecksum ~= ""
        or sessionHistoryArchiveChecksum ~= ""
        or funAwardsArchiveChecksum ~= "",
      archiveProofComplete = lootListArchiveChecksum ~= ""
        and itemHistoryArchiveChecksum ~= ""
        and sessionHistoryArchiveChecksum ~= ""
        and funAwardsArchiveChecksum ~= "",
      protocolVersion = math.max(0, tonumber(protocolVersion) or 0),
    }, nil
  end

  function profileSyncMetaOps.parseInboundProfileStatePartPayload(fields, sender)
    if not profileSyncMetaOps.hasRequiredInboundFields(fields, 9) then
      return nil, "truncated_profile_state_part_payload"
    end
    local sessionId = TrimText(fields[2])
    local profileName = TrimText(fields[3])
    local memberKey = NormalizeCharacterKey(fields[4])
    local partToken = TrimText(fields[6])
    if sessionId == "" or profileName == "" or memberKey == "" or partToken == "" then
      return nil, "missing_profile_state_part_identity"
    end
    if #partToken > sessionConfig.maxProfileStatePartTokenBytes then
      return nil, "profile_state_part_token_exceeds_limit"
    end
    local partIndex, partIndexValid = profileSyncMetaOps.parseInboundNumberField(fields, 7)
    local partTotal, partTotalValid = profileSyncMetaOps.parseInboundNumberField(fields, 8)
    partIndex = math.max(0, tonumber(partIndex) or 0)
    partTotal = math.max(0, tonumber(partTotal) or 0)
    if not partIndexValid or not partTotalValid or partIndex <= 0 or partIndex > partTotal then
      return nil, "invalid_profile_state_part_range"
    end
    if partTotal > sessionConfig.maxProfileStateParts then
      return nil, "profile_state_part_total_exceeds_limit"
    end
    local chunkPayload = tostring(fields[9] or "")
    if #chunkPayload > sessionConfig.maxProfileStateAssemblyBytes then
      return nil, "profile_state_part_bytes_exceed_limit"
    end
    return {
      sessionId = sessionId,
      profileName = profileName,
      memberKey = memberKey,
      profileId = TrimText(fields[5]),
      partToken = partToken,
      partIndex = partIndex,
      partTotal = partTotal,
      chunkPayload = chunkPayload,
      senderKey = profileSyncMetaOps.normalizeSenderKey(sender),
    }, nil
  end

  profileSyncMetaOps.rememberPendingProfileStatePart = function(payload)
    payload = type(payload) == "table" and payload or {}
    PruneAgedSessionRuntimeTracking(GetProfileCheckpointSyncTime())
    local assemblyKey = string.lower(table.concat({
      TrimText(payload.sessionId),
      TrimText(payload.profileName),
      NormalizeCharacterKey(payload.memberKey),
      NormalizeCharacterKey(payload.senderKey),
      TrimText(payload.partToken),
    }, "\31"))
    if assemblyKey == "" then
      return nil, "missing_profile_state_part_assembly_key"
    end
    local assembly = sessionRuntime.pendingProfileStateParts[assemblyKey]
    if type(assembly) ~= "table" then
      local pendingCount = 0
      for _ in pairs(sessionRuntime.pendingProfileStateParts) do
        pendingCount = pendingCount + 1
      end
      if pendingCount >= sessionConfig.maxPendingProfileStateAssemblies then
        return nil, "profile_state_part_assembly_limit_reached"
      end
      assembly = {
        total = payload.partTotal,
        parts = {},
        receivedBytes = 0,
        updatedAt = GetProfileCheckpointSyncTime(),
      }
      sessionRuntime.pendingProfileStateParts[assemblyKey] = assembly
    elseif tonumber(assembly.total) ~= tonumber(payload.partTotal) then
      sessionRuntime.pendingProfileStateParts[assemblyKey] = nil
      return nil, "profile_state_part_total_changed"
    end

    local previousPart = assembly.parts[payload.partIndex]
    if previousPart ~= nil and previousPart ~= payload.chunkPayload then
      sessionRuntime.pendingProfileStateParts[assemblyKey] = nil
      return nil, "profile_state_part_payload_changed"
    end
    if previousPart == nil then
      assembly.parts[payload.partIndex] = payload.chunkPayload
      assembly.receivedBytes = math.max(0, tonumber(assembly.receivedBytes) or 0) + #payload.chunkPayload
    end
    assembly.updatedAt = GetProfileCheckpointSyncTime()
    if assembly.receivedBytes > sessionConfig.maxProfileStateAssemblyBytes then
      sessionRuntime.pendingProfileStateParts[assemblyKey] = nil
      return nil, "profile_state_assembly_bytes_exceed_limit"
    end
    for index = 1, payload.partTotal do
      if assembly.parts[index] == nil then
        return nil, "waiting_for_profile_state_parts"
      end
    end
    local orderedParts = {}
    for index = 1, payload.partTotal do
      orderedParts[index] = assembly.parts[index]
    end
    sessionRuntime.pendingProfileStateParts[assemblyKey] = nil
    return table.concat(orderedParts), "complete"
  end

  function profileSyncMetaOps.parseInboundProfileDeltaAckPayload(fields, sender)
    if not profileSyncMetaOps.hasRequiredInboundFields(fields, 17) then
      return nil, "truncated_profile_delta_ack_payload"
    end
    local sessionId = TrimText(fields[2])
    local profileName = TrimText(fields[3])
    local changeId = TrimText(fields[4])
    local memberKey = NormalizeCharacterKey(TrimText(fields[5]) ~= "" and fields[5] or sender)
    if sessionId == "" or profileName == "" or changeId == "" or memberKey == "" then
      return nil, "missing_profile_delta_ack_identity"
    end
    local sequence, sequenceValid = profileSyncMetaOps.parseInboundNumberField(fields, 6)
    if not sequenceValid then
      return nil, "invalid_profile_delta_ack_sequence"
    end
    local settingsRevision, settingsRevisionValid = profileSyncMetaOps.parseInboundNumberField(fields, 7)
    if not settingsRevisionValid then
      return nil, "invalid_profile_delta_ack_settings_revision"
    end
    local permissionsRevision, permissionsRevisionValid = profileSyncMetaOps.parseInboundNumberField(fields, 8)
    if not permissionsRevisionValid then
      return nil, "invalid_profile_delta_ack_permissions_revision"
    end
    local operationalRevision, operationalRevisionValid = profileSyncMetaOps.parseInboundNumberField(fields, 9)
    if not operationalRevisionValid then
      return nil, "invalid_profile_delta_ack_operational_revision"
    end
    local profileUpdatedAt, profileUpdatedAtValid = profileSyncMetaOps.parseInboundNumberField(fields, 10)
    if not profileUpdatedAtValid then
      return nil, "invalid_profile_delta_ack_profile_updated_at"
    end
    local lootRevision, lootRevisionValid = profileSyncMetaOps.parseInboundNumberField(fields, 14)
    if not lootRevisionValid then
      return nil, "invalid_profile_delta_ack_loot_revision"
    end
    local sessionRevision, sessionRevisionValid = profileSyncMetaOps.parseInboundNumberField(fields, 15)
    if not sessionRevisionValid then
      return nil, "invalid_profile_delta_ack_session_revision"
    end
    local operationalChecksum = TrimText(fields[13])
    local lootChecksum = TrimText(fields[16])
    if lootChecksum == "" then
      lootChecksum = operationalChecksum
    end
    local sessionChecksum = TrimText(fields[17])
    if sessionChecksum == "" then
      sessionChecksum = operationalChecksum
    end
    local ackPhase = type(INTERNAL_API.LIDCOUNCIL_NormalizeCombatSyncAckPhase_Impl) == "function"
      and INTERNAL_API.LIDCOUNCIL_NormalizeCombatSyncAckPhase_Impl(fields[18])
      or (TrimText(fields[18]) == "" and "APPLIED" or string.upper(TrimText(fields[18])))
    if ackPhase == "" then
      return nil, "invalid_profile_delta_ack_phase"
    end
    return {
      sessionId = sessionId,
      profileName = profileName,
      changeId = changeId,
      memberKey = memberKey,
      sequence = sequence,
      settingsRevision = settingsRevision,
      permissionsRevision = permissionsRevision,
      operationalRevision = operationalRevision,
      lootRevision = lootRevision,
      sessionRevision = sessionRevision,
      profileUpdatedAt = profileUpdatedAt,
      settingsChecksum = TrimText(fields[11]),
      permissionsChecksum = TrimText(fields[12]),
      operationalChecksum = operationalChecksum,
      lootChecksum = lootChecksum,
      sessionChecksum = sessionChecksum,
      ackPhase = ackPhase,
    }, nil
  end

  function profileSyncMetaOps.parseInboundProfileDeltaNackPayload(fields, sender)
    if not profileSyncMetaOps.hasRequiredInboundFields(fields, 7) then
      return nil, "truncated_profile_delta_nack_payload"
    end
    local sessionId = TrimText(fields[2])
    local profileName = TrimText(fields[3])
    local changeId = TrimText(fields[4])
    local memberKey = NormalizeCharacterKey(TrimText(fields[5]) ~= "" and fields[5] or sender)
    if sessionId == "" or profileName == "" or changeId == "" or memberKey == "" then
      return nil, "missing_profile_delta_nack_identity"
    end
    local sequence, sequenceValid = profileSyncMetaOps.parseInboundNumberField(fields, 6)
    if not sequenceValid then
      return nil, "invalid_profile_delta_nack_sequence"
    end
    return {
      sessionId = sessionId,
      profileName = profileName,
      changeId = changeId,
      memberKey = memberKey,
      sequence = sequence,
      reason = TrimText(fields[7]),
    }, nil
  end

  function profileSyncMetaOps.parseInboundProfileDeltaPayload(fields)
    if not profileSyncMetaOps.hasRequiredInboundFields(fields, 16) then
      return nil, "truncated_profile_delta_payload"
    end
    local sessionId = TrimText(fields[2])
    local profileName = TrimText(fields[3])
    local changeId = TrimText(fields[5])
    local actor = NormalizeCharacterKey(fields[6])
    local action = TrimText(fields[8])
    if sessionId == "" or profileName == "" or changeId == "" or actor == "" or action == "" then
      return nil, "missing_profile_delta_identity"
    end
    local settingsRevision, settingsRevisionValid = profileSyncMetaOps.parseInboundNumberField(fields, 9)
    if not settingsRevisionValid then
      return nil, "invalid_profile_delta_settings_revision"
    end
    local permissionsRevision, permissionsRevisionValid = profileSyncMetaOps.parseInboundNumberField(fields, 10)
    if not permissionsRevisionValid then
      return nil, "invalid_profile_delta_permissions_revision"
    end
    local operationalRevision, operationalRevisionValid = profileSyncMetaOps.parseInboundNumberField(fields, 11)
    if not operationalRevisionValid then
      return nil, "invalid_profile_delta_operational_revision"
    end
    local profileUpdatedAt, profileUpdatedAtValid = profileSyncMetaOps.parseInboundNumberField(fields, 12)
    if not profileUpdatedAtValid then
      return nil, "invalid_profile_delta_profile_updated_at"
    end
    local sequence, sequenceValid = profileSyncMetaOps.parseInboundNumberField(fields, 13)
    if not sequenceValid then
      return nil, "invalid_profile_delta_sequence"
    end
    local args = {}
    for index = 17, #fields do
      args[#args + 1] = fields[index]
    end
    return {
      sessionId = sessionId,
      profileName = profileName,
      profileId = TrimText(fields[4]),
      changeId = changeId,
      actor = actor,
      domain = TrimText(fields[7]),
      action = action,
      settingsRevision = settingsRevision,
      permissionsRevision = permissionsRevision,
      operationalRevision = operationalRevision,
      profileUpdatedAt = profileUpdatedAt,
      sequence = sequence,
      settingsChecksum = TrimText(fields[14]),
      permissionsChecksum = TrimText(fields[15]),
      operationalChecksum = TrimText(fields[16]),
      args = args,
    }, nil
  end

  function profileSyncMetaOps.parseInboundJoinAckPayload(fields, sender)
    if not profileSyncMetaOps.hasRequiredInboundFields(fields, 9) then
      return nil, "truncated_join_ack_payload"
    end
    local sessionId = TrimText(fields[2])
    local profileName = TrimText(fields[3])
    local host = profileSyncMetaOps.normalizeSenderKey(sender)
    if sessionId == "" or profileName == "" or host == "" then
      return nil, "missing_join_ack_identity"
    end
    local startedAt, startedAtValid = profileSyncMetaOps.parseInboundNumberField(fields, 7, {
      allowMissing = true,
      emptyValue = time and time() or 0,
    })
    if not startedAtValid then
      return nil, "invalid_join_ack_started_at"
    end
    local activatedAt, activatedAtValid = profileSyncMetaOps.parseInboundNumberField(fields, 9, {
      allowMissing = true,
      allowEmpty = true,
      emptyValue = nil,
    })
    if not activatedAtValid then
      return nil, "invalid_join_ack_activated_at"
    end
    local protocolVersion, protocolVersionValid = profileSyncMetaOps.parseInboundProtocolVersionField(fields, 10, {
      allowMissing = true,
      allowEmpty = true,
      emptyValue = 1,
    })
    if not protocolVersionValid then
      return nil, "invalid_join_ack_protocol"
    end
    local hostAutoPassEnabled = nil
    if fields[12] ~= nil and TrimText(fields[12]) ~= "" then
      hostAutoPassEnabled = deps.NormalizeEnabledFlag(fields[12], false) and true or false
    end
    return {
      sessionId = sessionId,
      profileName = profileName,
      profileId = TrimText(fields[4]),
      claimedHost = NormalizeCharacterKey(fields[5]),
      host = host,
      profileMaster = TrimText(fields[6]),
      startedAt = startedAt,
      ackStatus = string.upper(TrimText(fields[8])),
      activatedAt = activatedAt,
      protocolVersion = protocolVersion,
      ackMemberKey = NormalizeCharacterKey(fields[11]),
      hostAutoPassEnabled = hostAutoPassEnabled,
    }, nil
  end
  INTERNAL_API.LIDCOUNCIL_ParseInboundJoinAckPayload_Impl = profileSyncMetaOps.parseInboundJoinAckPayload

  function profileSyncMetaOps.parseInboundBeginPayload(fields, sender)
    if not profileSyncMetaOps.hasRequiredInboundFields(fields, 7) then
      return nil, "truncated_begin_payload"
    end
    local sessionId = TrimText(fields[2])
    local profileName = TrimText(fields[3])
    local host = profileSyncMetaOps.normalizeSenderKey(sender)
    if sessionId == "" or profileName == "" or host == "" then
      return nil, "missing_begin_identity"
    end
    local activatedAt, activatedAtValid = profileSyncMetaOps.parseInboundNumberField(fields, 6, {
      allowMissing = true,
      emptyValue = time and time() or 0,
    })
    if not activatedAtValid then
      return nil, "invalid_begin_activated_at"
    end
    local protocolVersion, protocolVersionValid = profileSyncMetaOps.parseInboundProtocolVersionField(fields, 8, {
      allowMissing = true,
      allowEmpty = true,
      emptyValue = 1,
    })
    if not protocolVersionValid then
      return nil, "invalid_begin_protocol"
    end
    return {
      sessionId = sessionId,
      profileName = profileName,
      profileId = TrimText(fields[4]),
      claimedHost = NormalizeCharacterKey(fields[5]),
      host = host,
      activatedAt = activatedAt,
      profileMaster = TrimText(fields[7]),
      protocolVersion = protocolVersion,
    }, nil
  end

  function profileSyncMetaOps.parseInboundJoinPayload(fields, sender)
    if not profileSyncMetaOps.hasRequiredInboundFields(fields, 18) then
      return nil, "truncated_join_payload"
    end
    local sessionId = TrimText(fields[2])
    local profileName = TrimText(fields[3])
    local memberKey = NormalizeCharacterKey(TrimText(fields[4]) ~= "" and fields[4] or sender)
    if sessionId == "" or profileName == "" or memberKey == "" then
      return nil, "missing_join_identity"
    end
    local joinedAt, joinedAtValid = profileSyncMetaOps.parseInboundNumberField(fields, 5, {
      allowMissing = true,
      emptyValue = time and time() or 0,
    })
    if not joinedAtValid then
      return nil, "invalid_join_joined_at"
    end
    local remoteSettingsRevision, remoteSettingsRevisionValid = profileSyncMetaOps.parseInboundNumberField(fields, 14)
    if not remoteSettingsRevisionValid then
      return nil, "invalid_join_settings_revision"
    end
    local remotePermissionsRevision, remotePermissionsRevisionValid = profileSyncMetaOps.parseInboundNumberField(fields, 15)
    if not remotePermissionsRevisionValid then
      return nil, "invalid_join_permissions_revision"
    end
    local remoteOperationalRevision, remoteOperationalRevisionValid = profileSyncMetaOps.parseInboundNumberField(fields, 16)
    if not remoteOperationalRevisionValid then
      return nil, "invalid_join_operational_revision"
    end
    local memberProtocolVersion = GetInviteProtocolVersion(fields[19])
    local remoteProfileUpdatedAt
    local remoteProfileUpdatedAtValid = true
    local hadLocalSharedProfile = false
    if tonumber(memberProtocolVersion) ~= nil then
      remoteProfileUpdatedAt, remoteProfileUpdatedAtValid = profileSyncMetaOps.parseInboundNumberField(fields, 17, {
        allowMissing = true,
        emptyValue = 0,
      })
      if not remoteProfileUpdatedAtValid then
        return nil, "invalid_join_profile_updated_at"
      end
      hadLocalSharedProfile = deps.NormalizeEnabledFlag(fields[18], false) and true or false
      memberProtocolVersion = math.max(0, tonumber(memberProtocolVersion) or 0)
    else
      memberProtocolVersion, remoteProfileUpdatedAtValid = profileSyncMetaOps.parseInboundProtocolVersionField(fields, 18, {
        allowMissing = true,
        allowEmpty = true,
        emptyValue = 1,
      })
      if not remoteProfileUpdatedAtValid then
        return nil, "invalid_join_protocol"
      end
      remoteProfileUpdatedAt = 0
      hadLocalSharedProfile = deps.NormalizeEnabledFlag(fields[17], false) and true or false
    end
    local remoteLootRevision = memberProtocolVersion >= 2 and math.max(0, tonumber(fields[23]) or remoteOperationalRevision) or remoteOperationalRevision
    local remoteSessionRevision = memberProtocolVersion >= 2 and math.max(0, tonumber(fields[24]) or remoteOperationalRevision) or remoteOperationalRevision
    local remoteOperationalChecksum = memberProtocolVersion >= 2 and TrimText(fields[22]) or ""
    local remoteLootChecksum = memberProtocolVersion >= 2 and TrimText(fields[25]) or ""
    if remoteLootChecksum == "" then
      remoteLootChecksum = remoteOperationalChecksum
    end
    local remoteSessionChecksum = memberProtocolVersion >= 2 and TrimText(fields[26]) or ""
    if remoteSessionChecksum == "" then
      remoteSessionChecksum = remoteOperationalChecksum
    end
    return {
      sessionId = sessionId,
      profileName = profileName,
      memberKey = memberKey,
      joinedAt = joinedAt,
      addonVersion = TrimText(fields[6]),
      clientVersion = TrimText(fields[7]),
      className = TrimText(fields[8]),
      classFile = TrimText(fields[9]),
      specName = TrimText(fields[10]),
      specIcon = TrimText(fields[11]),
      localAutoPassEnabled = deps.NormalizeEnabledFlag(fields[12], true),
      claimedProfileId = TrimText(fields[13]),
      remoteSettingsRevision = remoteSettingsRevision,
      remotePermissionsRevision = remotePermissionsRevision,
      remoteOperationalRevision = remoteOperationalRevision,
      remoteProfileUpdatedAt = remoteProfileUpdatedAt,
      hadLocalSharedProfile = hadLocalSharedProfile,
      memberProtocolVersion = memberProtocolVersion,
      remoteSettingsChecksum = memberProtocolVersion >= 2 and TrimText(fields[20]) or "",
      remotePermissionsChecksum = memberProtocolVersion >= 2 and TrimText(fields[21]) or "",
      remoteOperationalChecksum = remoteOperationalChecksum,
      remoteLootRevision = remoteLootRevision,
      remoteSessionRevision = remoteSessionRevision,
      remoteLootChecksum = remoteLootChecksum,
      remoteSessionChecksum = remoteSessionChecksum,
      remoteLiveLootChecksum = memberProtocolVersion >= 6 and TrimText(fields[27]) or "",
    }, nil
  end

  function profileSyncMetaOps.parseInboundAutoPassPayload(fields, sender, opts)
    opts = type(opts) == "table" and opts or {}
    if not profileSyncMetaOps.hasRequiredInboundFields(fields, 5) then
      return nil, "truncated_autopass_payload"
    end
    local sessionId = TrimText(fields[2])
    local profileName = TrimText(fields[3])
    local memberKey = NormalizeCharacterKey(opts.allowSenderFallback == true and (TrimText(fields[4]) ~= "" and fields[4] or sender) or fields[4])
    if sessionId == "" or profileName == "" or memberKey == "" then
      return nil, "missing_autopass_identity"
    end
    return {
      sessionId = sessionId,
      profileName = profileName,
      memberKey = memberKey,
      enabled = deps.NormalizeEnabledFlag(fields[5], true),
    }, nil
  end

  function profileSyncMetaOps.parseInboundLeavePayload(fields, sender)
    if not profileSyncMetaOps.hasRequiredInboundFields(fields, 5) then
      return nil, "truncated_leave_payload"
    end
    local sessionId = TrimText(fields[2])
    local profileName = TrimText(fields[3])
    local memberKey = NormalizeCharacterKey(TrimText(fields[4]) ~= "" and fields[4] or sender)
    if sessionId == "" or profileName == "" or memberKey == "" then
      return nil, "missing_leave_identity"
    end
    local leftAt, leftAtValid = profileSyncMetaOps.parseInboundNumberField(fields, 5, {
      allowMissing = true,
      emptyValue = time and time() or 0,
    })
    if not leftAtValid then
      return nil, "invalid_leave_timestamp"
    end
    return {
      sessionId = sessionId,
      profileName = profileName,
      memberKey = memberKey,
      leftAt = leftAt,
    }, nil
  end

  function profileSyncMetaOps.parseInboundStartInvitePayload(fields, sender)
    if not profileSyncMetaOps.hasRequiredInboundFields(fields, 7) then
      return nil, "truncated_start_payload"
    end
    local sessionId = TrimText(fields[2])
    local profileName = TrimText(fields[3])
    local host = profileSyncMetaOps.normalizeSenderKey(sender)
    if sessionId == "" or profileName == "" or host == "" then
      return nil, "missing_start_identity"
    end
    local startedAt, startedAtValid = profileSyncMetaOps.parseInboundNumberField(fields, 6, {
      allowMissing = true,
      emptyValue = time and time() or 0,
    })
    if not startedAtValid then
      return nil, "invalid_start_started_at"
    end
    local parsedProtocolVersion = GetInviteProtocolVersion(fields[8])
    local protocolVersion = parsedProtocolVersion or 1
    local rollFieldsStartIndex = parsedProtocolVersion and 9 or 8
    local inviteStatus = string.upper(TrimText(fields[rollFieldsStartIndex]))
    if inviteStatus == "ACTIVE" or inviteStatus == "PREPARING" then
      rollFieldsStartIndex = rollFieldsStartIndex + 1
    else
      inviteStatus = "PREPARING"
    end
    return {
      sessionId = sessionId,
      profileName = profileName,
      profileId = TrimText(fields[4]),
      claimedHost = NormalizeCharacterKey(fields[5]),
      host = host,
      startedAt = startedAt,
      profileMaster = TrimText(fields[7]),
      protocolVersion = math.max(0, tonumber(protocolVersion) or 1),
      inviteStatus = inviteStatus,
      rollFieldsStartIndex = rollFieldsStartIndex,
    }, nil
  end

  function profileSyncMetaOps.parseInboundInviteAckPayload(fields, sender)
    if not profileSyncMetaOps.hasRequiredInboundFields(fields, 5) then
      return nil, "truncated_invite_ack_payload"
    end
    local sessionId = TrimText(fields[2])
    local profileName = TrimText(fields[3])
    local memberKey = NormalizeCharacterKey(fields[4])
    local receiptState = string.upper(TrimText(fields[5]))
    if sessionId == "" or profileName == "" or memberKey == "" or receiptState == "" then
      return nil, "missing_invite_ack_identity"
    end
    return {
      sessionId = sessionId,
      profileName = profileName,
      memberKey = memberKey,
      receiptState = receiptState,
      reason = TrimText(fields[6]),
      sender = profileSyncMetaOps.normalizeSenderKey(sender),
    }, nil
  end

  function profileSyncMetaOps.parseInboundDeclinePayload(fields, sender)
    if not profileSyncMetaOps.hasRequiredInboundFields(fields, 4) then
      return nil, "truncated_decline_payload"
    end
    local sessionId = TrimText(fields[2])
    local profileName = TrimText(fields[3])
    local memberKey = NormalizeCharacterKey(TrimText(fields[4]) ~= "" and fields[4] or sender)
    if sessionId == "" or profileName == "" or memberKey == "" then
      return nil, "missing_decline_identity"
    end
    return {
      sessionId = sessionId,
      profileName = profileName,
      memberKey = memberKey,
    }, nil
  end

  function profileSyncMetaOps.parseInboundStopPayload(fields)
    if not profileSyncMetaOps.hasRequiredInboundFields(fields, 5) then
      return nil, "truncated_stop_payload"
    end
    local sessionId = TrimText(fields[2])
    local profileName = TrimText(fields[3])
    local host = NormalizeCharacterKey(fields[4])
    if sessionId == "" or profileName == "" or host == "" then
      return nil, "missing_stop_identity"
    end
    local endedAt, endedAtValid = profileSyncMetaOps.parseInboundNumberField(fields, 5, {
      allowMissing = true,
      emptyValue = time and time() or 0,
    })
    if not endedAtValid then
      return nil, "invalid_stop_timestamp"
    end
    return {
      sessionId = sessionId,
      profileName = profileName,
      host = host,
      endedAt = endedAt,
      token = TrimText(fields[6]),
    }, nil
  end

  function profileSyncMetaOps.parseInboundStopAckPayload(fields, sender)
    if not profileSyncMetaOps.hasRequiredInboundFields(fields, 6) then
      return nil, "truncated_stop_ack_payload"
    end
    local sessionId = TrimText(fields[2])
    local profileName = TrimText(fields[3])
    local memberKey = NormalizeCharacterKey(fields[4])
    local token = TrimText(fields[5])
    local receiptState = string.upper(TrimText(fields[6]))
    local senderKey = profileSyncMetaOps.normalizeSenderKey(sender)
    if sessionId == "" or profileName == "" or memberKey == "" or token == "" or senderKey == "" then
      return nil, "missing_stop_ack_identity"
    end
    if receiptState ~= "APPLIED" and receiptState ~= "ALREADY_APPLIED" then
      return nil, "invalid_stop_ack_state"
    end
    if not AreCharacterKeysSame(memberKey, senderKey) then
      return nil, "stop_ack_sender_mismatch"
    end
    return {
      sessionId = sessionId,
      profileName = profileName,
      memberKey = memberKey,
      token = token,
      receiptState = receiptState,
      sender = senderKey,
    }, nil
  end

  local function CloneComparedDomains(domains)
    local cloned = {}
    for _, domain in ipairs(type(domains) == "table" and domains or {}) do
      local value = string.lower(TrimText(domain))
      if value ~= "" then
        cloned[#cloned + 1] = value
      end
    end
    return cloned
  end

  local function MergeComparedDomains(...)
    local merged = {}
    local seen = {}
    for index = 1, select("#", ...) do
      for _, domain in ipairs(type(select(index, ...)) == "table" and select(index, ...) or {}) do
        local value = string.lower(TrimText(domain))
        if value ~= "" and not seen[value] then
          seen[value] = true
          merged[#merged + 1] = value
        end
      end
    end
    return merged
  end

  local function EncodeCheckpointSubdomainToken(value)
    local text = TrimText(value)
    if text == "" then
      return ""
    end
    return (text:gsub("([^%w%-%_])", function(character)
      return string.format("%%%02x", string.byte(character))
    end))
  end

  local function BuildDynamicCheckpointSubdomainKey(prefix, identity)
    local resolvedPrefix = string.lower(TrimText(prefix))
    local token = EncodeCheckpointSubdomainToken(identity)
    if resolvedPrefix == "" or token == "" then
      return ""
    end
    return resolvedPrefix .. ":" .. token
  end

  local function BuildSessionRecordCheckpointSubdomain(sessionId)
    local resolvedSessionId = TrimText(sessionId)
    if resolvedSessionId == "" then
      return ""
    end
    return BuildDynamicCheckpointSubdomainKey("ssr", "id:" .. resolvedSessionId)
  end

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

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

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

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

  BuildRepairScopeEscalationKindsSuffix = function(kinds)
    local resolvedKinds = CloneDecisionTextList(kinds)
    if #resolvedKinds == 0 then
      return ""
    end
    return " (" .. table.concat(resolvedKinds, ", ") .. ")"
  end

  local function BuildRepairScopeEscalationSummary(count, kinds)
    local resolvedCount = math.max(0, tonumber(count) or 0)
    if resolvedCount == 0 then
      return ""
    end
    return " | Scope widened: " .. tostring(resolvedCount)
      .. BuildRepairScopeEscalationKindsSuffix(kinds)
  end

  function sessionLifecycleOps.buildCountLabelText(count, singularLabel)
    local resolvedCount = math.max(0, tonumber(count) or 0)
    local resolvedLabel = TrimText(singularLabel)
    if resolvedLabel == "" then
      resolvedLabel = "item"
    end
    return tostring(resolvedCount) .. " " .. resolvedLabel .. (resolvedCount == 1 and "" or "s")
  end

  function sessionLifecycleOps.buildJoinedMemberCountLabel(count)
    return sessionLifecycleOps.buildCountLabelText(count, "joined member")
  end

  function sessionLifecycleOps.buildAggregateRepairMetricsSummary(repairMetricsState, opts)
    repairMetricsState = type(repairMetricsState) == "table" and repairMetricsState or sessionLifecycleOps.createRepairMetricsState()
    opts = type(opts) == "table" and opts or {}

    local summary = opts.includeTransfers == false
      and ""
      or (" Transfers: " .. tostring(math.max(0, tonumber(opts.transferCount) or 0)))
    summary = summary
      .. " | Targeted: " .. tostring(repairMetricsState.targetedCount)
      .. " | Precise: " .. tostring(repairMetricsState.preciseCount)
    if opts.includeRowPatchTransfers == true then
      summary = summary .. " | Row patch transfers: " .. tostring(repairMetricsState.rowPatchTransferCount)
    end
    summary = summary
      .. " | Patch transfers: " .. tostring(repairMetricsState.patchTransferCount)
      .. " | Patch scopes: " .. tostring(repairMetricsState.patchScopeCount)
    if opts.includeSnapshotTransfers == true then
      summary = summary .. " | Snapshot transfers: " .. tostring(repairMetricsState.snapshotTransferCount)
    end
    summary = summary
      .. BuildRepairScopeEscalationSummary(repairMetricsState.scopeEscalationCount, repairMetricsState.scopeEscalationKinds)
      .. " | Full fallback: " .. tostring(repairMetricsState.fullFallbackCount)
    if repairMetricsState.queueMergeCount > 0 then
      summary = summary .. " | Queue merges: " .. tostring(repairMetricsState.queueMergeCount)
    end
    if repairMetricsState.queueExactDuplicateCount > 0 then
      summary = summary .. " | Duplicate collapses: " .. tostring(repairMetricsState.queueExactDuplicateCount)
    end
    if opts.includeDeferred ~= false and repairMetricsState.deferredPatchStateCount > 0 then
      summary = summary .. " | Deferred manifest retries: " .. tostring(repairMetricsState.deferredPatchStateCount)
    end
    if opts.includeSuppressed == true and repairMetricsState.suppressedRepeatCount > 0 then
      summary = summary .. " | Already queued unchanged: " .. tostring(repairMetricsState.suppressedRepeatCount)
    end
    if opts.includeSkippedAligned == true and repairMetricsState.skippedAlignedCount > 0 then
      summary = summary .. " | Already aligned: " .. tostring(repairMetricsState.skippedAlignedCount)
    end
    if opts.includeSkippedMemberNewer == true and repairMetricsState.skippedMemberNewerCount > 0 then
      summary = summary .. " | Member newer/conflict skipped: " .. tostring(repairMetricsState.skippedMemberNewerCount)
    end
    return summary
  end

  function sessionLifecycleOps.buildCheckpointRepairDispatchMessage(sentCount, repairMetricsState, opts)
    repairMetricsState = type(repairMetricsState) == "table" and repairMetricsState or sessionLifecycleOps.createRepairMetricsState()
    opts = type(opts) == "table" and opts or {}

    local resolvedSentCount = math.max(0, tonumber(sentCount) or 0)
    local resolvedScopeCount = math.max(0, tonumber(opts.scopeCount) or 0)
    local resolvedScopeLabel = TrimText(opts.scopeLabel)
    if resolvedScopeLabel == "" then
      resolvedScopeLabel = "scope"
    end

    local message
    if resolvedSentCount > 0 then
      message = "Queued a live " .. resolvedScopeLabel .. " checkpoint for "
        .. sessionLifecycleOps.buildJoinedMemberCountLabel(repairMetricsState.memberSentCount)
        .. " across " .. sessionLifecycleOps.buildCountLabelText(resolvedScopeCount, resolvedScopeLabel) .. "."
    else
      message = "Deferred a live " .. resolvedScopeLabel .. " checkpoint retry for "
        .. sessionLifecycleOps.buildJoinedMemberCountLabel(repairMetricsState.deferredPatchStateCount)
        .. " across " .. sessionLifecycleOps.buildCountLabelText(resolvedScopeCount, resolvedScopeLabel)
        .. " while patch manifests load."
    end
    return message .. sessionLifecycleOps.buildAggregateRepairMetricsSummary(repairMetricsState, {
      transferCount = resolvedSentCount,
      includeRowPatchTransfers = opts.includeRowPatchTransfers == true,
      includeSnapshotTransfers = opts.includeSnapshotTransfers == true,
      includeSkippedAligned = opts.includeSkippedAligned == true,
      includeDeferred = opts.includeDeferred ~= false,
    })
  end

  function sessionLifecycleOps.buildHostPushRepairDispatchMessage(sentCount, repairMetricsState, opts)
    repairMetricsState = type(repairMetricsState) == "table" and repairMetricsState or sessionLifecycleOps.createRepairMetricsState()
    opts = type(opts) == "table" and opts or {}

    local resolvedSentCount = math.max(0, tonumber(sentCount) or 0)
    local message
    if resolvedSentCount > 0 then
      message = "Queued shared-profile repairs for " .. sessionLifecycleOps.buildJoinedMemberCountLabel(repairMetricsState.memberSentCount) .. "."
    else
      message = "Deferred manifest-assisted shared-profile retries for "
        .. sessionLifecycleOps.buildJoinedMemberCountLabel(repairMetricsState.deferredPatchStateCount) .. "."
    end
    return message .. sessionLifecycleOps.buildAggregateRepairMetricsSummary(repairMetricsState, {
      transferCount = resolvedSentCount,
      includeSnapshotTransfers = opts.includeSnapshotTransfers == true,
      includeSuppressed = opts.includeSuppressed == true,
      includeSkippedAligned = opts.includeSkippedAligned == true,
      includeSkippedMemberNewer = opts.includeSkippedMemberNewer == true,
      includeDeferred = opts.includeDeferred ~= false,
    })
  end

  function sessionLifecycleOps.buildLiveBroadcastRepairDispatchMessage(sentCount, repairMetricsState, opts)
    repairMetricsState = type(repairMetricsState) == "table" and repairMetricsState or sessionLifecycleOps.createRepairMetricsState()
    opts = type(opts) == "table" and opts or {}

    local resolvedSentCount = math.max(0, tonumber(sentCount) or 0)
    local message
    if resolvedSentCount > 0 then
      message = "Queued a live shared profile update for "
        .. sessionLifecycleOps.buildJoinedMemberCountLabel(repairMetricsState.memberSentCount)
        .. ". Transfers: " .. tostring(resolvedSentCount)
    else
      message = "Deferred live shared profile repair retries for "
        .. sessionLifecycleOps.buildJoinedMemberCountLabel(repairMetricsState.deferredPatchStateCount)
        .. " while patch manifests load. Transfers: 0"
    end
    return message .. sessionLifecycleOps.buildAggregateRepairMetricsSummary(repairMetricsState, {
      includeTransfers = false,
      includeSnapshotTransfers = opts.includeSnapshotTransfers == true,
      includeSuppressed = opts.includeSuppressed == true,
      includeSkippedAligned = opts.includeSkippedAligned == true,
      includeSkippedMemberNewer = opts.includeSkippedMemberNewer == true,
      includeDeferred = opts.includeDeferred ~= false,
    })
  end

  function sessionLifecycleOps.buildRepairIdleStatusMessage(baseMessage, repairMetricsState, opts)
    repairMetricsState = type(repairMetricsState) == "table" and repairMetricsState or sessionLifecycleOps.createRepairMetricsState()
    opts = type(opts) == "table" and opts or {}

    local message = TrimText(baseMessage)
    if message == "" then
      message = "No repair was queued."
    end
    if opts.includeSuppressed == true and repairMetricsState.suppressedRepeatCount > 0 then
      message = message .. " Already queued unchanged: " .. tostring(repairMetricsState.suppressedRepeatCount) .. "."
    end
    if opts.includeSkippedAligned == true and repairMetricsState.skippedAlignedCount > 0 then
      message = message .. " Already aligned: " .. tostring(repairMetricsState.skippedAlignedCount) .. "."
    end
    if opts.includeSkippedMemberNewer == true and repairMetricsState.skippedMemberNewerCount > 0 then
      message = message .. " " .. FirstNonEmptyText(opts.memberNewerText, "Member newer/conflict skipped")
        .. ": " .. tostring(repairMetricsState.skippedMemberNewerCount) .. "."
    end
    return message
  end

  local function ClassifyRequestedRepairScope(domains, subdomains, whenEmpty)
    if #CloneCheckpointSubdomainList(subdomains) > 0 then
      return "precise"
    end
    if #CloneCheckpointDomainList(domains) > 0 then
      return "targeted"
    end
    local fallbackScope = string.lower(TrimText(whenEmpty))
    if fallbackScope ~= "" then
      return fallbackScope
    end
    return "full"
  end

  local function BuildFullSnapshotFallbackEscalationKinds(requestedScope)
    local resolvedRequestedScope = string.lower(TrimText(requestedScope))
    if resolvedRequestedScope == "precise" then
      return { "precise_to_full_snapshot" }
    end
    if resolvedRequestedScope == "targeted" then
      return { "targeted_to_full_snapshot" }
    end
    return {}
  end

  local function BuildDeltaRecoverySummary(memberKey, recoveryKind, queuedCount, recoveryDetail, recoveryError)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if resolvedMemberKey == "" then
      resolvedMemberKey = tostring(memberKey or "Unknown")
    end
    local resolvedQueuedCount = math.max(0, tonumber(queuedCount) or 0)
    local deferredPatchStateCount = type(recoveryDetail) == "table" and recoveryDetail.deferredPatchState == true and 1 or 0
    if recoveryKind == "coalesced"
      or (type(recoveryDetail) == "table" and recoveryDetail.coalescedExistingRepair == true)
    then
      return "Skipped delta recovery for " .. resolvedMemberKey .. ": matching repair already queued."
    end
    if recoveryKind == "aligned"
      or (resolvedQueuedCount == 0 and type(recoveryDetail) == "table" and recoveryDetail.skippedNoOp == true)
    then
      return "Skipped delta recovery for " .. resolvedMemberKey .. ": already aligned."
    end
    if resolvedQueuedCount == 0 and deferredPatchStateCount > 0 then
      local requestedScope = TrimText(type(recoveryDetail) == "table" and recoveryDetail.requestedScope or "")
      if requestedScope == "" then
        requestedScope = "targeted"
      end
      return "Deferred delta recovery for " .. resolvedMemberKey
        .. " while patch manifests load. Requested: " .. requestedScope
        .. " | Deferred manifest retries: " .. tostring(deferredPatchStateCount)
    end
    if resolvedQueuedCount == 0 then
      local failureMessage = "Delta recovery for " .. resolvedMemberKey .. " failed."
      if TrimText(recoveryError) ~= "" then
        failureMessage = failureMessage .. " " .. TrimText(recoveryError)
      end
      return failureMessage
    end

    local requestedScope = TrimText(type(recoveryDetail) == "table" and recoveryDetail.requestedScope or "")
    if requestedScope == "" then
      requestedScope = recoveryKind == "full" and "full" or "targeted"
    end
    local patchTransferCount = math.max(0, tonumber(type(recoveryDetail) == "table" and recoveryDetail.patchTransfers or 0) or 0)
    local patchScopeCount = math.max(0, tonumber(type(recoveryDetail) == "table" and recoveryDetail.patchSubdomains or 0) or 0)
    local snapshotTransferCount = math.max(0, tonumber(type(recoveryDetail) == "table" and recoveryDetail.snapshotTransfers or 0) or 0)
    if snapshotTransferCount == 0 and (recoveryKind == "scoped_snapshot" or recoveryKind == "full") then
      snapshotTransferCount = 1
    end
    local scopeEscalationCount = type(recoveryDetail) == "table"
      and recoveryDetail.scopeEscalated == true
      and recoveryDetail.fullSnapshotFallback ~= true
      and 1
      or 0
    local scopeEscalationKinds = CloneDecisionTextList(type(recoveryDetail) == "table" and recoveryDetail.scopeEscalationKinds or {})
    local fullFallbackCount = type(recoveryDetail) == "table" and recoveryDetail.fullSnapshotFallback == true and 1 or 0

    local summary = "Queued delta recovery for " .. resolvedMemberKey .. "."
    summary = summary
      .. " Transfers: " .. tostring(resolvedQueuedCount)
      .. " | Requested: " .. requestedScope
      .. " | Patch transfers: " .. tostring(patchTransferCount)
      .. " | Patch scopes: " .. tostring(patchScopeCount)
      .. " | Snapshot transfers: " .. tostring(snapshotTransferCount)
      .. BuildRepairScopeEscalationSummary(scopeEscalationCount, scopeEscalationKinds)
      .. " | Full fallback: " .. tostring(fullFallbackCount)
    if deferredPatchStateCount > 0 then
      summary = summary .. " | Deferred manifest retries: " .. tostring(deferredPatchStateCount)
    end
    return summary
  end

  profileSyncMetaOps.buildSessionMemberRepairOutcomeSummary = function(memberKey, sourceLabel, queuedCount, repairDetail, repairError, opts)
    opts = type(opts) == "table" and opts or {}
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if resolvedMemberKey == "" then
      resolvedMemberKey = tostring(memberKey or "Unknown")
    end
    local resolvedSourceLabel = TrimText(sourceLabel)
    if resolvedSourceLabel == "" then
      resolvedSourceLabel = "repair"
    end
    local displaySourceLabel = resolvedSourceLabel:gsub("^%l", string.upper)
    local resolvedState = string.lower(TrimText(opts.state))
    local resolvedQueuedCount = math.max(0, tonumber(queuedCount) or 0)
    local rowPatchTransferCount = math.max(0, tonumber(opts.rowPatchTransfers) or 0)
    local transferCount = math.max(resolvedQueuedCount, rowPatchTransferCount)
    local requestedScope = TrimText(opts.requestedScope)
    if requestedScope == "" then
      requestedScope = TrimText(type(repairDetail) == "table" and repairDetail.requestedScope or "")
    end
    if requestedScope == "" then
      requestedScope = ClassifyRequestedRepairScope(
        type(repairDetail) == "table" and repairDetail.requestedDomains or {},
        type(repairDetail) == "table" and repairDetail.requestedSubdomains or {},
        type(repairDetail) == "table" and repairDetail.repairMode or ""
      )
    end
    if resolvedState == "aligned" then
      return "Skipped " .. displaySourceLabel .. " for " .. resolvedMemberKey .. ": already aligned."
    end
    if resolvedState == "coalesced" then
      return "Skipped " .. displaySourceLabel .. " for " .. resolvedMemberKey .. ": matching repair already queued."
    end
    if resolvedState == "review" then
      return "Skipped " .. displaySourceLabel .. " for " .. resolvedMemberKey
        .. ": member newer or conflicting data should be reviewed first."
    end
    if resolvedState == "deferred" then
      if requestedScope == "" then
        requestedScope = "targeted"
      end
      return "Deferred " .. displaySourceLabel .. " for " .. resolvedMemberKey
        .. " while patch manifests load. Requested: " .. requestedScope
        .. " | Deferred manifest retries: 1"
    end
    if resolvedState == "failed" or transferCount == 0 then
      local failureMessage = displaySourceLabel .. " for " .. resolvedMemberKey .. " failed."
      if TrimText(repairError) ~= "" then
        failureMessage = failureMessage .. " " .. TrimText(repairError)
      end
      return failureMessage
    end

    if requestedScope == "" then
      requestedScope = "targeted"
    end
    local patchTransferCount = math.max(0, tonumber(type(repairDetail) == "table" and repairDetail.patchTransfers or 0) or 0)
    local patchScopeCount = math.max(0, tonumber(type(repairDetail) == "table" and repairDetail.patchSubdomains or 0) or 0)
    local snapshotTransferCount = math.max(0, tonumber(type(repairDetail) == "table" and repairDetail.snapshotTransfers or 0) or 0)
    if snapshotTransferCount == 0 and opts.fullSnapshotFallback == true then
      snapshotTransferCount = 1
    end
    local scopeEscalationCount = opts.scopeEscalated == true and opts.fullSnapshotFallback ~= true and 1 or 0
    local scopeEscalationKinds = CloneDecisionTextList(opts.scopeEscalationKinds)
    if #scopeEscalationKinds == 0 then
      scopeEscalationKinds = CloneDecisionTextList(type(repairDetail) == "table" and repairDetail.scopeEscalationKinds or {})
    end
    local fullFallbackCount = opts.fullSnapshotFallback == true and 1 or 0

    local summary = "Queued " .. displaySourceLabel .. " for " .. resolvedMemberKey .. "."
    summary = summary
      .. " Transfers: " .. tostring(transferCount)
      .. " | Requested: " .. requestedScope
      .. (rowPatchTransferCount > 0 and (" | Row patch transfers: " .. tostring(rowPatchTransferCount)) or "")
      .. " | Patch transfers: " .. tostring(patchTransferCount)
      .. " | Patch scopes: " .. tostring(patchScopeCount)
      .. " | Snapshot transfers: " .. tostring(snapshotTransferCount)
      .. BuildRepairScopeEscalationSummary(scopeEscalationCount, scopeEscalationKinds)
      .. " | Full fallback: " .. tostring(fullFallbackCount)
    if type(repairDetail) == "table" and repairDetail.deferredPatchState == true then
      summary = summary .. " | Deferred manifest retries: 1"
    end
    return summary
  end

  profileSyncMetaOps.persistSessionMemberRepairOutcome = function(activeSession, profileName, sessionId, memberKey, queuedCount, repairDetail, repairError, opts)
    opts = type(opts) == "table" and opts or {}
    local resolvedProfileName = TrimText(profileName)
    if resolvedProfileName == "" then
      resolvedProfileName = TrimText(type(activeSession) == "table" and activeSession.profileName or "")
    end
    local resolvedSessionId = TrimText(sessionId)
    if resolvedSessionId == "" then
      resolvedSessionId = TrimText(type(activeSession) == "table" and activeSession.id or "")
    end
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if resolvedProfileName == "" or resolvedSessionId == "" or resolvedMemberKey == "" then
      return false, nil, {
        state = "",
        requestedScope = "",
        summary = "",
        currentSectionChanged = false,
        stamped = false,
      }
    end

    local resolvedQueuedCount = math.max(0, tonumber(queuedCount) or 0)
    local rowPatchTransferCount = math.max(0, tonumber(opts.rowPatchTransfers) or 0)
    local effectiveQueuedCount = math.max(resolvedQueuedCount, rowPatchTransferCount)
    local requestedScope = TrimText(type(repairDetail) == "table" and repairDetail.requestedScope or "")
    if requestedScope == "" then
      requestedScope = ClassifyRequestedRepairScope(
        type(repairDetail) == "table" and repairDetail.requestedDomains or (type(opts.requestedDomains) == "table" and opts.requestedDomains or {}),
        type(repairDetail) == "table" and repairDetail.requestedSubdomains or (type(opts.requestedSubdomains) == "table" and opts.requestedSubdomains or {}),
        type(repairDetail) == "table" and repairDetail.repairMode or opts.requestedScope
      )
    end
    local scopeEscalationKinds = CloneDecisionTextList(type(repairDetail) == "table" and repairDetail.scopeEscalationKinds or {})
    local fullSnapshotFallback = type(repairDetail) == "table" and repairDetail.fullSnapshotFallback == true or false
    if not fullSnapshotFallback
      and requestedScope ~= "full"
      and type(repairDetail) == "table"
      and (repairDetail.forceFullSnapshot == true or TrimText(repairDetail.repairMode) == "full")
    then
      fullSnapshotFallback = true
    end
    if fullSnapshotFallback and #scopeEscalationKinds == 0 then
      scopeEscalationKinds = BuildFullSnapshotFallbackEscalationKinds(requestedScope)
    end
    local scopeEscalated = type(repairDetail) == "table" and repairDetail.scopeEscalated == true or #scopeEscalationKinds > 0
    local state = string.lower(TrimText(opts.state))
    if state == "" then
      if type(repairDetail) == "table" and repairDetail.coalescedExistingRepair == true then
        state = "coalesced"
      elseif type(repairDetail) == "table" and (repairDetail.skippedAligned == true or repairDetail.skippedNoOp == true) then
        state = "aligned"
      elseif type(repairDetail) == "table" and repairDetail.skippedMemberNewer == true then
        state = "review"
      elseif effectiveQueuedCount == 0 and type(repairDetail) == "table" and repairDetail.deferredPatchState == true then
        state = "deferred"
      elseif effectiveQueuedCount == 0 and TrimText(repairError) ~= "" then
        state = "failed"
      elseif fullSnapshotFallback then
        state = "full_fallback"
      elseif scopeEscalated then
        state = "widened"
      elseif effectiveQueuedCount > 0 then
        state = "recovered"
      else
        state = "failed"
      end
    end
    local repairKind = TrimText(opts.repairKind)
    if repairKind == "" then
      if state == "aligned" then
        repairKind = "aligned"
      elseif state == "review" then
        repairKind = "member_newer"
      else
        repairKind = TrimText(type(repairDetail) == "table" and repairDetail.repairMode or "")
      end
      if repairKind == "" then
        repairKind = requestedScope ~= "" and requestedScope or "repair"
      end
    end
    local summary = TrimText(opts.summary)
    if summary == "" and type(profileSyncMetaOps.buildSessionMemberRepairOutcomeSummary) == "function" then
      summary = profileSyncMetaOps.buildSessionMemberRepairOutcomeSummary(
        resolvedMemberKey,
        TrimText(opts.sourceLabel),
        effectiveQueuedCount,
        repairDetail,
        repairError,
        {
          state = state,
          requestedScope = requestedScope,
          rowPatchTransfers = rowPatchTransferCount,
          scopeEscalated = scopeEscalated,
          fullSnapshotFallback = fullSnapshotFallback,
          scopeEscalationKinds = scopeEscalationKinds,
        }
      )
    end
    local scopeEscalationKindsText = table.concat(scopeEscalationKinds, ",")

    local existingMember = nil
    if type(activeSession) == "table" then
      existingMember = FindSessionMember(activeSession, resolvedMemberKey)
    end
    local previousCurrentSessionDisplayContext = type(opts.currentSessionDisplayContext) == "table"
      and opts.currentSessionDisplayContext
      or nil
    local previousCurrentSessionDisplay = opts.previousCurrentSessionDisplay
    if type(activeSession) == "table" and type(existingMember) == "table" and opts.defer ~= false then
      if previousCurrentSessionDisplayContext == nil then
        previousCurrentSessionDisplayContext = INTERNAL_API.LIDCOUNCIL_BuildHostCurrentSessionDisplayContext(
          activeSession,
          resolvedProfileName,
          resolvedMemberKey,
          {
            syncCandidateSnapshot = type(opts.syncCandidateSnapshot) == "table" and opts.syncCandidateSnapshot or nil,
          }
        )
      end
      if previousCurrentSessionDisplay == nil then
        previousCurrentSessionDisplay = INTERNAL_API.LIDCOUNCIL_BuildHostCurrentSessionMemberDisplayState(
          activeSession,
          resolvedProfileName,
          resolvedMemberKey,
          existingMember,
          previousCurrentSessionDisplayContext
        )
      end
    end

    local identicalOutcome = false
    if type(existingMember) == "table" then
      identicalOutcome = string.lower(TrimText(existingMember.lastDeltaRecoveryState)) == state
        and TrimText(existingMember.lastDeltaRecoveryKind) == repairKind
        and TrimText(existingMember.lastDeltaRecoveryRequestedScope) == requestedScope
        and (existingMember.lastDeltaRecoveryScopeEscalated == true) == (scopeEscalated == true)
        and (existingMember.lastDeltaRecoveryFullSnapshotFallback == true) == (fullSnapshotFallback == true)
        and TrimText(existingMember.lastDeltaRecoveryScopeEscalationKinds) == scopeEscalationKindsText
        and TrimText(existingMember.lastDeltaRecoverySummary) == summary
    end
    local additionalFieldsChanged = false
    if type(existingMember) == "table" and type(opts.additionalFields) == "table" then
      for fieldName, fieldValue in pairs(opts.additionalFields) do
        local existingValue = existingMember[fieldName]
        local valuesMatch = false
        if type(fieldValue) == "number" or type(existingValue) == "number" then
          valuesMatch = tonumber(existingValue) == tonumber(fieldValue)
        elseif type(fieldValue) == "boolean" or type(existingValue) == "boolean" then
          valuesMatch = (existingValue == true) == (fieldValue == true)
        else
          valuesMatch = TrimText(existingValue) == TrimText(fieldValue)
        end
        if not valuesMatch then
          additionalFieldsChanged = true
          break
        end
      end
    end
    local needsFreshDeferredStamp = false
    if identicalOutcome and state == "deferred" and type(existingMember) == "table" then
      local existingRecoveryAt = math.max(0, tonumber(existingMember.lastDeltaRecoveryAt) or 0)
      local existingLastSyncAt = math.max(0, tonumber(existingMember.lastSyncAt) or 0)
      needsFreshDeferredStamp = existingLastSyncAt > existingRecoveryAt
    end
    if identicalOutcome and not additionalFieldsChanged and not needsFreshDeferredStamp then
      return true, existingMember, {
        state = state,
        requestedScope = requestedScope,
        summary = summary,
        currentSectionChanged = false,
        stamped = false,
        unchanged = true,
      }
    end

    local stampedAt = tonumber(time and time() or 0) or 0
    local memberUpdate = {
      lastDeltaRecoveryAt = stampedAt,
      lastDeltaRecoveryState = state,
      lastDeltaRecoveryKind = repairKind,
      lastDeltaRecoveryRequestedScope = requestedScope,
      lastDeltaRecoveryScopeEscalated = scopeEscalated == true,
      lastDeltaRecoveryFullSnapshotFallback = fullSnapshotFallback == true,
      lastDeltaRecoveryScopeEscalationKinds = scopeEscalationKindsText,
      lastDeltaRecoverySummary = summary,
      suppressProfileTouch = true,
    }
    if type(opts.additionalFields) == "table" then
      for fieldName, fieldValue in pairs(opts.additionalFields) do
        memberUpdate[fieldName] = fieldValue
      end
    end
    local ok, member = UpsertLootSessionMember(resolvedProfileName, resolvedSessionId, resolvedMemberKey, memberUpdate)

    local postUpdate = nil
    if ok and type(activeSession) == "table" then
      local updatedSyncCandidateSnapshot = type(opts.syncCandidateSnapshot) == "table"
        and opts.syncCandidateSnapshot
        or (previousCurrentSessionDisplay ~= nil and BuildActiveSyncCandidateSnapshot() or nil)
      local updatedCurrentSessionDisplayContext = type(opts.updatedCurrentSessionDisplayContext) == "table"
        and opts.updatedCurrentSessionDisplayContext
        or (
          previousCurrentSessionDisplay ~= nil
          and INTERNAL_API.LIDCOUNCIL_BuildHostCurrentSessionDisplayContextFromBase(
            activeSession,
            resolvedProfileName,
            resolvedMemberKey,
            previousCurrentSessionDisplayContext,
            updatedSyncCandidateSnapshot
          )
          or nil
        )
      postUpdate = INTERNAL_API.LIDCOUNCIL_HandleHostMemberPostUpdate(
        activeSession,
        resolvedProfileName,
        resolvedSessionId,
        resolvedMemberKey,
        existingMember,
        type(member) == "table" and member or nil,
        {
          refreshEditor = opts.refreshEditor,
          defer = opts.defer,
          previousCurrentSessionDisplay = previousCurrentSessionDisplay,
          currentSessionDisplayContext = previousCurrentSessionDisplayContext,
          updatedCurrentSessionDisplayContext = updatedCurrentSessionDisplayContext,
          syncCandidateSnapshot = updatedSyncCandidateSnapshot,
          skipRefreshWhenUnchanged = true,
          refreshSyncManagementWhenUnchanged = true,
        }
      )
    end
    return ok, member, {
      state = state,
      requestedScope = requestedScope,
      summary = summary,
      currentSectionChanged = type(postUpdate) == "table" and postUpdate.currentSectionChanged == true or false,
      stamped = ok == true,
      unchanged = false,
    }
  end

  profileSyncMetaOps.buildPreparedTransferKindList = function(transfers)
    local kinds = {}
    for _, transfer in ipairs(type(transfers) == "table" and transfers or {}) do
      local transferKind = string.upper(TrimText(type(transfer) == "table" and transfer.transferKind or ""))
      if transferKind ~= "" then
        kinds[#kinds + 1] = transferKind
      end
    end
    return CloneDecisionTextList(kinds)
  end

  profileSyncMetaOps.removeCheckpointDomain = function(domains, needle)
    local resolvedNeedle = string.lower(TrimText(needle))
    if resolvedNeedle == "" then
      return CloneCheckpointDomainList(domains)
    end
    local filtered = {}
    for _, domain in ipairs(type(domains) == "table" and domains or {}) do
      local resolvedDomain = string.lower(TrimText(domain))
      if resolvedDomain ~= "" and resolvedDomain ~= resolvedNeedle then
        filtered[#filtered + 1] = resolvedDomain
      end
    end
    return filtered
  end

  profileSyncMetaOps.buildCurrentSessionCheckpointSubdomains = function(sessionId)
    local subdomain = BuildSessionRecordCheckpointSubdomain(sessionId)
    if subdomain == "" then
      return {}
    end
    return { subdomain }
  end

  local MergeCheckpointSubdomainLists
  local FindActiveSyncCandidate

  profileSyncMetaOps.buildTargetedSessionRepairScope = function(domains, sessionId)
    local resolvedDomains = CloneCheckpointDomainList(domains)
    local targetedSubdomains = {}
    local hasSessionDomain = false
    for _, domain in ipairs(resolvedDomains) do
      if string.lower(TrimText(domain)) == "session" then
        hasSessionDomain = true
        break
      end
    end
    if hasSessionDomain then
      targetedSubdomains = profileSyncMetaOps.buildCurrentSessionCheckpointSubdomains(sessionId)
      if #targetedSubdomains > 0 then
        resolvedDomains = profileSyncMetaOps.removeCheckpointDomain(resolvedDomains, "session")
      end
    end
    return resolvedDomains, targetedSubdomains
  end

  profileSyncMetaOps.buildActiveSessionRosterLookup = function(activeSession)
    local rosterLookup = {}
    local function AddRosterKey(characterKey)
      local resolvedKey = NormalizeCharacterKey(characterKey)
      if resolvedKey ~= "" then
        rosterLookup[string.lower(resolvedKey)] = true
      end
    end
    if type(activeSession) == "table" then
      AddRosterKey(activeSession.host)
      for memberKey, member in pairs(activeSession.members or {}) do
        if type(member) == "table" and tostring(member.status or "JOINED") == "JOINED" then
          AddRosterKey(memberKey)
        end
      end
    end
    if type(deps.CollectGroupCharacterKeys) == "function" then
      for _, characterKey in ipairs(deps.CollectGroupCharacterKeys() or {}) do
        AddRosterKey(characterKey)
      end
    end
    return rosterLookup
  end

  profileSyncMetaOps.buildSessionLiveLootChecksum = function(profileName, activeSession)
    if type(profileSyncMetaOps.getSubchecksumManifest) ~= "function" or type(profileSyncMetaOps.calculateStableChecksum) ~= "function" then
      return ""
    end
    local manifest = profileSyncMetaOps.getSubchecksumManifest(profileName, { "loot" })
    if type(manifest) ~= "table" then
      return ""
    end
    local rosterLookup = profileSyncMetaOps.buildActiveSessionRosterLookup(activeSession)
    local byDomain = type(manifest.byDomain) == "table" and manifest.byDomain or {}
    local lootState = type(byDomain.loot) == "table" and byDomain.loot or {}
    local subchecksums = type(lootState.subchecksums) == "table" and lootState.subchecksums or {}
    local liveChecksums = {}
    for subdomain, checksum in pairs(subchecksums) do
      local resolvedSubdomain = TrimText(subdomain)
      if resolvedSubdomain ~= ""
        and profileSyncMetaOps.classifyLootRepairSubdomainTier(resolvedSubdomain, rosterLookup) == "live"
      then
        liveChecksums[resolvedSubdomain] = TrimText(checksum)
      end
    end
    if next(liveChecksums) == nil then
      return ""
    end
    return TrimText(profileSyncMetaOps.calculateStableChecksum(liveChecksums))
  end

  profileSyncMetaOps.buildSessionArchiveLootChecksum = function(profileName, activeSession)
    if type(profileSyncMetaOps.getSubchecksumManifest) ~= "function" or type(profileSyncMetaOps.calculateStableChecksum) ~= "function" then
      return ""
    end
    local manifest = profileSyncMetaOps.getSubchecksumManifest(profileName, { "loot", "session" })
    if type(manifest) ~= "table" then
      return ""
    end
    local rosterLookup = profileSyncMetaOps.buildActiveSessionRosterLookup(activeSession)
    local byDomain = type(manifest.byDomain) == "table" and manifest.byDomain or {}
    local lootState = type(byDomain.loot) == "table" and byDomain.loot or {}
    local subchecksums = type(lootState.subchecksums) == "table" and lootState.subchecksums or {}
    local sessionState = type(byDomain.session) == "table" and byDomain.session or {}
    local sessionSubchecksums = type(sessionState.subchecksums) == "table" and sessionState.subchecksums or {}
    local archiveChecksums = {}
    local currentSessionSubdomain = BuildSessionRecordCheckpointSubdomain(
      type(activeSession) == "table" and activeSession.id or ""
    )
    for subdomain, checksum in pairs(subchecksums) do
      local resolvedSubdomain = TrimText(subdomain)
      if resolvedSubdomain ~= ""
        and profileSyncMetaOps.classifyLootRepairSubdomainTier(resolvedSubdomain, rosterLookup) ~= "live"
      then
        archiveChecksums["loot:" .. resolvedSubdomain] = TrimText(checksum)
      end
    end
    for subdomain, checksum in pairs(sessionSubchecksums) do
      local resolvedSubdomain = TrimText(subdomain)
      if resolvedSubdomain ~= "" and string.lower(resolvedSubdomain) ~= string.lower(currentSessionSubdomain) then
        archiveChecksums["session:" .. resolvedSubdomain] = TrimText(checksum)
      end
    end
    return TrimText(profileSyncMetaOps.calculateStableChecksum(archiveChecksums))
  end

  profileSyncMetaOps.buildSessionArchiveScopeChecksums = function(profileName, activeSession)
    if type(profileSyncMetaOps.getSubchecksumManifest) ~= "function"
      or type(profileSyncMetaOps.calculateStableChecksum) ~= "function"
    then
      return {}
    end
    local manifest = profileSyncMetaOps.getSubchecksumManifest(profileName, { "loot", "session" })
    if type(manifest) ~= "table" then
      return {}
    end
    local rosterLookup = profileSyncMetaOps.buildActiveSessionRosterLookup(activeSession)
    local byDomain = type(manifest.byDomain) == "table" and manifest.byDomain or {}
    local lootState = type(byDomain.loot) == "table" and byDomain.loot or {}
    local lootSubchecksums = type(lootState.subchecksums) == "table" and lootState.subchecksums or {}
    local sessionState = type(byDomain.session) == "table" and byDomain.session or {}
    local sessionSubchecksums = type(sessionState.subchecksums) == "table" and sessionState.subchecksums or {}
    local buckets = {
      lootList = {},
      itemHistory = {},
      sessionHistory = {},
      funAwards = {},
    }
    for subdomain, checksum in pairs(lootSubchecksums) do
      local resolvedSubdomain = TrimText(subdomain)
      local tier = profileSyncMetaOps.classifyLootRepairSubdomainTier(resolvedSubdomain, rosterLookup)
      if tier == "stats" then
        buckets.funAwards[resolvedSubdomain] = TrimText(checksum)
      elseif tier ~= "" then
        buckets.lootList[resolvedSubdomain] = TrimText(checksum)
      end
    end
    local currentSessionSubdomain = BuildSessionRecordCheckpointSubdomain(
      type(activeSession) == "table" and activeSession.id or ""
    )
    for subdomain, checksum in pairs(sessionSubchecksums) do
      local resolvedSubdomain = string.lower(TrimText(subdomain))
      if resolvedSubdomain:find("^slb:", 1, false) then
        buckets.itemHistory[resolvedSubdomain] = TrimText(checksum)
      elseif resolvedSubdomain:find("^ssr:", 1, false)
        and resolvedSubdomain ~= string.lower(currentSessionSubdomain)
      then
        buckets.sessionHistory[resolvedSubdomain] = TrimText(checksum)
      end
    end
    return {
      lootList = TrimText(profileSyncMetaOps.calculateStableChecksum(buckets.lootList)),
      itemHistory = TrimText(profileSyncMetaOps.calculateStableChecksum(buckets.itemHistory)),
      sessionHistory = TrimText(profileSyncMetaOps.calculateStableChecksum(buckets.sessionHistory)),
      funAwards = TrimText(profileSyncMetaOps.calculateStableChecksum(buckets.funAwards)),
    }
  end

  function profileSyncMetaOps.normalizeHostMemberStatusState(state)
    local resolvedState = string.upper(TrimText(state))
    if resolvedState == "READY" or resolvedState == "SYNCED"
      or resolvedState == "ALIGNED" or resolvedState == "CONVERGED"
    then
      return "READY"
    end
    if resolvedState == "REVIEW" or resolvedState == "PARTIAL"
      or resolvedState == "FAILED" or resolvedState == "DECLINED"
    then
      return "REVIEW"
    end
    if resolvedState == "VALIDATING" or resolvedState == "REVALIDATING" then
      return "VALIDATING"
    end
    if resolvedState == "STALE" or resolvedState == "OUTDATED"
      or resolvedState == "ARCHIVE_PENDING"
    then
      return "STALE"
    end
    return "PENDING"
  end

  function profileSyncMetaOps.encodeHostMemberStatusMatrix(matrix)
    if type(matrix) ~= "table" then
      return ""
    end
    local stateCodes = {
      READY = "R",
      PENDING = "P",
      REVIEW = "V",
      VALIDATING = "T",
      STALE = "Y",
    }
    local encoded = { "1" }
    for _, fieldName in ipairs({
      "p1",
      "p2",
      "lootList",
      "itemHistory",
      "sessionHistory",
      "funAwards",
    }) do
      encoded[#encoded + 1] = stateCodes[profileSyncMetaOps.normalizeHostMemberStatusState(matrix[fieldName])] or "P"
    end
    return table.concat(encoded)
  end

  function profileSyncMetaOps.decodeHostMemberStatusMatrix(value)
    local encoded = TrimText(value)
    if #encoded ~= 7 or string.sub(encoded, 1, 1) ~= "1" then
      return nil
    end
    local codeStates = {
      R = "READY",
      P = "PENDING",
      V = "REVIEW",
      T = "VALIDATING",
      Y = "STALE",
    }
    local states = {}
    local fieldNames = {
      "p1",
      "p2",
      "lootList",
      "itemHistory",
      "sessionHistory",
      "funAwards",
    }
    for index, fieldName in ipairs(fieldNames) do
      local state = codeStates[string.sub(encoded, index + 1, index + 1)]
      if state == nil then
        return nil
      end
      states[fieldName] = state
    end
    states.p3 = INTERNAL_API.LIDCOUNCIL_AggregateHostMemberArchiveState_Impl(states)
    return states
  end

  function profileSyncMetaOps.getHostMemberStatusMatrixValue(member, requestedSessionId)
    if type(member) ~= "table" then
      return ""
    end
    local activeSession = GetActiveLootSession()
    local sessionId = FirstNonEmptyText(
      requestedSessionId,
      type(activeSession) == "table" and activeSession.id or ""
    )
    if sessionId == "" then
      return ""
    end
    local directSessionId = FirstNonEmptyText(
      member.hostSyncStatusSessionId,
      sessionRuntime.hostMemberSyncStatusSessionByMember[member]
    )
    if directSessionId == sessionId then
      local directValue = FirstNonEmptyText(
        member.hostSyncStatusMatrix,
        sessionRuntime.hostMemberSyncStatusByMember[member]
      )
      if type(profileSyncMetaOps.decodeHostMemberStatusMatrix(directValue)) == "table" then
        return directValue
      end
    end
    local memberKey = NormalizeCharacterKey(member.name or "")
    if memberKey == "" or sessionRuntime.hostMemberSyncStatusSessionId ~= sessionId then
      return ""
    end
    return TrimText(sessionRuntime.hostMemberSyncStatusByKey[
      string.lower(sessionId) .. "|" .. string.lower(memberKey)
    ])
  end

  function profileSyncMetaOps.getHostMemberStatusMatrixGeneration(member, requestedSessionId)
    if type(member) ~= "table" then
      return 0
    end
    local activeSession = GetActiveLootSession()
    local sessionId = FirstNonEmptyText(
      requestedSessionId,
      type(activeSession) == "table" and activeSession.id or ""
    )
    if sessionId == "" then
      return 0
    end
    local directSessionId = FirstNonEmptyText(
      member.hostSyncStatusSessionId,
      sessionRuntime.hostMemberSyncStatusSessionByMember[member]
    )
    if directSessionId == sessionId then
      return math.max(0, math.floor(tonumber(
        member.hostSyncStatusGeneration
          or sessionRuntime.hostMemberSyncStatusGenerationByMember[member]
          or 0
      ) or 0))
    end
    local memberKey = NormalizeCharacterKey(member.name or "")
    if memberKey == "" or sessionRuntime.hostMemberSyncStatusSessionId ~= sessionId then
      return 0
    end
    return math.max(0, math.floor(tonumber(sessionRuntime.hostMemberSyncStatusGenerationByKey[
      string.lower(sessionId) .. "|" .. string.lower(memberKey)
    ]) or 0))
  end

  function profileSyncMetaOps.resolveHostMemberStatusGeneration(
    currentValue,
    currentGeneration,
    nextValue,
    requestedGeneration,
    explicitGeneration
  )
    local currentEncoded = TrimText(currentValue)
    local nextEncoded = TrimText(nextValue)
    local currentValid = type(profileSyncMetaOps.decodeHostMemberStatusMatrix(currentEncoded)) == "table"
    if type(profileSyncMetaOps.decodeHostMemberStatusMatrix(nextEncoded)) ~= "table" then
      return false, currentEncoded, math.max(0, math.floor(tonumber(currentGeneration) or 0))
    end
    local currentResolvedGeneration = math.max(0, math.floor(tonumber(currentGeneration) or 0))
    if explicitGeneration == true then
      local nextGeneration = math.max(0, math.floor(tonumber(requestedGeneration) or 0))
      if currentValid then
        if nextGeneration == 0 and currentResolvedGeneration > 0 then
          return false, currentEncoded, currentResolvedGeneration
        end
        if nextEncoded ~= currentEncoded and nextGeneration <= currentResolvedGeneration then
          return false, currentEncoded, currentResolvedGeneration
        end
        if nextEncoded == currentEncoded and nextGeneration < currentResolvedGeneration then
          return false, currentEncoded, currentResolvedGeneration
        end
      end
      return true, nextEncoded, nextGeneration
    end
    if currentValid and currentEncoded == nextEncoded then
      return true, nextEncoded, currentResolvedGeneration
    end
    return true, nextEncoded, math.max(1, currentResolvedGeneration + 1)
  end

  function profileSyncMetaOps.ensureHostMemberStatusSession(sessionId)
    local resolvedSessionId = TrimText(sessionId)
    if resolvedSessionId == "" or sessionRuntime.hostMemberSyncStatusSessionId == resolvedSessionId then
      return
    end
    sessionRuntime.hostMemberSyncStatusSessionId = resolvedSessionId
    sessionRuntime.hostMemberSyncStatusByKey = {}
    sessionRuntime.hostMemberSyncStatusGenerationByKey = {}
    sessionRuntime.hostMemberReadinessProofByKey = {}
    sessionRuntime.hostMemberReadinessProofGenerationByKey = {}
  end

  function profileSyncMetaOps.recordReadinessTransition(
    sessionId,
    memberKey,
    previousValue,
    nextValue,
    generation,
    source,
    reason
  )
    if TrimText(previousValue) == TrimText(nextValue) then
      return
    end
    local entries = sessionRuntime.readinessTransitionLog
    entries[#entries + 1] = {
      at = time(),
      sessionId = TrimText(sessionId),
      memberKey = NormalizeCharacterKey(memberKey),
      previous = TrimText(previousValue),
      current = TrimText(nextValue),
      generation = math.max(0, math.floor(tonumber(generation) or 0)),
      source = TrimText(source),
      reason = TrimText(reason),
    }
    local previousMatrix = profileSyncMetaOps.decodeHostMemberStatusMatrix(previousValue) or {}
    local nextMatrix = profileSyncMetaOps.decodeHostMemberStatusMatrix(nextValue) or {}
    RecordRaidTestTraceEvent("READINESS_TRANSITION", TrimText(reason), {
      member = NormalizeCharacterKey(memberKey),
      source = TrimText(source),
      generation = math.max(0, math.floor(tonumber(generation) or 0)),
      p1 = FirstNonEmptyText(previousMatrix.p1, "UNKNOWN") .. ">" .. FirstNonEmptyText(nextMatrix.p1, "UNKNOWN"),
      p2 = FirstNonEmptyText(previousMatrix.p2, "UNKNOWN") .. ">" .. FirstNonEmptyText(nextMatrix.p2, "UNKNOWN"),
      p3 = FirstNonEmptyText(previousMatrix.p3, "UNKNOWN") .. ">" .. FirstNonEmptyText(nextMatrix.p3, "UNKNOWN"),
      session = TrimText(sessionId),
    })
    while #entries > 80 do
      table.remove(entries, 1)
    end
  end

  function profileSyncMetaOps.setHostMemberStatusMatrixValue(
    member,
    value,
    requestedSessionId,
    requestedGeneration,
    source,
    reason
  )
    if type(member) ~= "table" then
      return false
    end
    local encoded = TrimText(value)
    if type(profileSyncMetaOps.decodeHostMemberStatusMatrix(encoded)) ~= "table" then
      return false
    end
    local activeSession = GetActiveLootSession()
    local sessionId = FirstNonEmptyText(
      requestedSessionId,
      type(activeSession) == "table" and activeSession.id or ""
    )
    if sessionId == "" then
      return false
    end
    profileSyncMetaOps.ensureHostMemberStatusSession(sessionId)
    local previousValue = profileSyncMetaOps.getHostMemberStatusMatrixValue(member, sessionId)
    local previousGeneration = profileSyncMetaOps.getHostMemberStatusMatrixGeneration(member, sessionId)
    local accepted, resolvedValue, resolvedGeneration = profileSyncMetaOps.resolveHostMemberStatusGeneration(
      previousValue,
      previousGeneration,
      encoded,
      requestedGeneration,
      requestedGeneration ~= nil
    )
    if accepted ~= true then
      return false, previousGeneration
    end
    sessionRuntime.hostMemberSyncStatusByMember[member] = resolvedValue
    sessionRuntime.hostMemberSyncStatusSessionByMember[member] = sessionId
    sessionRuntime.hostMemberSyncStatusGenerationByMember[member] = resolvedGeneration
    member.hostSyncStatusMatrix = resolvedValue
    member.hostSyncStatusSessionId = sessionId
    member.hostSyncStatusGeneration = resolvedGeneration
    local memberKey = NormalizeCharacterKey(member.name or "")
    if memberKey ~= "" then
      local statusKey = string.lower(sessionId) .. "|" .. string.lower(memberKey)
      sessionRuntime.hostMemberSyncStatusByKey[statusKey] = resolvedValue
      sessionRuntime.hostMemberSyncStatusGenerationByKey[statusKey] = resolvedGeneration
      profileSyncMetaOps.recordReadinessTransition(
        sessionId,
        memberKey,
        previousValue,
        resolvedValue,
        resolvedGeneration,
        source,
        reason
      )
    end
    return true, resolvedGeneration
  end

  function profileSyncMetaOps.rememberHostMemberReadinessProof(member, requestedSessionId, requestedMemberKey, source)
    if type(member) ~= "table" then
      return nil
    end
    local sessionId = TrimText(requestedSessionId)
    local memberKey = NormalizeCharacterKey(FirstNonEmptyText(requestedMemberKey, member.name))
    if sessionId == "" or memberKey == "" then
      return nil
    end
    profileSyncMetaOps.ensureHostMemberStatusSession(sessionId)
    local proofKey = string.lower(sessionId) .. "|" .. string.lower(memberKey)
    local generation = math.max(0, math.floor(tonumber(
      sessionRuntime.hostMemberReadinessProofGenerationByKey[proofKey]
    ) or 0)) + 1
    local proof = {
      sessionId = sessionId,
      memberKey = memberKey,
      generation = generation,
      source = TrimText(source),
      status = member.status,
      addonVersion = member.addonVersion,
      lastSyncAt = member.lastSyncAt,
      sharedProfileId = member.sharedProfileId,
      profileId = member.profileId,
      settingsRevision = member.settingsRevision,
      settingsChecksum = member.settingsChecksum,
      permissionsRevision = member.permissionsRevision,
      permissionsChecksum = member.permissionsChecksum,
      operationalRevision = member.operationalRevision,
      operationalChecksum = member.operationalChecksum,
      lootRevision = member.lootRevision,
      lootChecksum = member.lootChecksum,
      sessionRevision = member.sessionRevision,
      sessionChecksum = member.sessionChecksum,
      liveLootChecksum = member.liveLootChecksum,
      lootListArchiveChecksum = member.lootListArchiveChecksum,
      itemHistoryArchiveChecksum = member.itemHistoryArchiveChecksum,
      sessionHistoryArchiveChecksum = member.sessionHistoryArchiveChecksum,
      funAwardsArchiveChecksum = member.funAwardsArchiveChecksum,
    }
    sessionRuntime.hostMemberReadinessProofByMember[member] = proof
    sessionRuntime.hostMemberReadinessProofSessionByMember[member] = sessionId
    sessionRuntime.hostMemberReadinessProofByKey[proofKey] = proof
    sessionRuntime.hostMemberReadinessProofGenerationByKey[proofKey] = generation
    return proof
  end

  function profileSyncMetaOps.getHostMemberReadinessProof(member, requestedSessionId, requestedMemberKey)
    local sessionId = TrimText(requestedSessionId)
    if sessionId == "" or sessionRuntime.hostMemberSyncStatusSessionId ~= sessionId then
      return nil
    end
    if type(member) == "table"
      and sessionRuntime.hostMemberReadinessProofSessionByMember[member] == sessionId
      and type(sessionRuntime.hostMemberReadinessProofByMember[member]) == "table"
    then
      return sessionRuntime.hostMemberReadinessProofByMember[member]
    end
    local memberKey = NormalizeCharacterKey(FirstNonEmptyText(
      requestedMemberKey,
      type(member) == "table" and member.name or ""
    ))
    if memberKey == "" then
      return nil
    end
    return sessionRuntime.hostMemberReadinessProofByKey[
      string.lower(sessionId) .. "|" .. string.lower(memberKey)
    ]
  end

  profileSyncMetaOps.preferSpecificLootRepairSubdomains = function(subdomains)
    local normalized = {}
    local seen = {}
    local hasRollEvents = false
    local hasVoteEvents = false
    for _, subdomain in ipairs(type(subdomains) == "table" and subdomains or {}) do
      local resolvedSubdomain = TrimText(subdomain)
      local lowerSubdomain = string.lower(resolvedSubdomain)
      if lowerSubdomain:find("^lre:", 1, false) then
        hasRollEvents = true
      elseif lowerSubdomain:find("^lve:", 1, false) then
        hasVoteEvents = true
      end
    end
    for _, subdomain in ipairs(type(subdomains) == "table" and subdomains or {}) do
      local resolvedSubdomain = TrimText(subdomain)
      local lowerSubdomain = string.lower(resolvedSubdomain)
      if resolvedSubdomain ~= "" then
        if not ((lowerSubdomain == "lrsr" and hasRollEvents) or (lowerSubdomain == "lrsv" and hasVoteEvents)) then
          if not seen[lowerSubdomain] then
            seen[lowerSubdomain] = true
            normalized[#normalized + 1] = resolvedSubdomain
          end
        end
      end
    end
    return normalized
  end

  profileSyncMetaOps.classifyLootRepairSubdomainTier = function(subdomain, rosterLookup)
    local resolvedSubdomain = TrimText(subdomain)
    local lowerSubdomain = string.lower(resolvedSubdomain)
    rosterLookup = type(rosterLookup) == "table" and rosterLookup or {}
    if resolvedSubdomain == "" then
      return ""
    end
    if lowerSubdomain == "lls" or lowerSubdomain:find("^llg:", 1, false) then
      return "live"
    end
    if lowerSubdomain:find("^lre:", 1, false) or lowerSubdomain:find("^lve:", 1, false)
      or lowerSubdomain == "lrsr" or lowerSubdomain == "lrsv" then
      return "stats"
    end
    if lowerSubdomain:find("^llr:", 1, false) or lowerSubdomain:find("^lmr:", 1, false) then
      local identity = NormalizeCharacterKey(resolvedSubdomain:match("^[^:]+:(.+)$") or "")
      if identity ~= "" and rosterLookup[string.lower(identity)] then
        return "live"
      end
      return "archive"
    end
    return "archive"
  end

  profileSyncMetaOps.splitRepairSubdomainsForActiveSession = function(activeSession, subdomains)
    local rosterLookup = profileSyncMetaOps.buildActiveSessionRosterLookup(activeSession)
    local nonLoot = {}
    local liveLoot = {}
    local statsLoot = {}
    local archiveLoot = {}
    for _, subdomain in ipairs(profileSyncMetaOps.preferSpecificLootRepairSubdomains(subdomains)) do
      local resolvedSubdomain = TrimText(subdomain)
      local parentDomain = type(profileSyncMetaOps.getSubdomainParentDomain) == "function"
        and string.lower(TrimText(profileSyncMetaOps.getSubdomainParentDomain(resolvedSubdomain)))
        or ""
      if parentDomain ~= "loot" then
        nonLoot[#nonLoot + 1] = resolvedSubdomain
      else
        local tier = profileSyncMetaOps.classifyLootRepairSubdomainTier(resolvedSubdomain, rosterLookup)
        if tier == "live" then
          liveLoot[#liveLoot + 1] = resolvedSubdomain
        elseif tier == "stats" then
          statsLoot[#statsLoot + 1] = resolvedSubdomain
        else
          archiveLoot[#archiveLoot + 1] = resolvedSubdomain
        end
      end
    end
    return nonLoot, liveLoot, statsLoot, archiveLoot
  end

  profileSyncMetaOps.buildAutomaticHostRepairScope = function(memberKey, domains, sessionId, candidateOverride)
    local resolvedDomains = CloneCheckpointDomainList(domains)
    local targetedSubdomains = {}
    local requestedDomainLookup = {}
    for _, domain in ipairs(resolvedDomains) do
      requestedDomainLookup[string.lower(TrimText(domain))] = true
    end

    local candidate = type(candidateOverride) == "table" and candidateOverride or FindActiveSyncCandidate(memberKey)
    if type(candidate) == "table" and type(candidate.preciseDifferentSubdomainsByDomain) == "table" then
      local preciseDomainLookup = {}
      local hostRepairDomains = type(candidate.effectiveHostRepairDomains) == "table" and candidate.effectiveHostRepairDomains or candidate.hostRepairDomains or {}
      for _, domain in ipairs(hostRepairDomains) do
        local normalizedDomain = string.lower(TrimText(domain))
        local preciseSubdomains = candidate.preciseDifferentSubdomainsByDomain[normalizedDomain] or {}
        if normalizedDomain ~= "" and requestedDomainLookup[normalizedDomain] and #preciseSubdomains > 0 then
          preciseDomainLookup[normalizedDomain] = true
          for _, subdomain in ipairs(profileSyncMetaOps.preferSpecificLootRepairSubdomains(preciseSubdomains)) do
            targetedSubdomains[#targetedSubdomains + 1] = subdomain
          end
        end
      end
      if next(preciseDomainLookup) ~= nil then
        local filtered = {}
        for _, domain in ipairs(resolvedDomains) do
          local normalizedDomain = string.lower(TrimText(domain))
          if normalizedDomain ~= "" and not preciseDomainLookup[normalizedDomain] then
            filtered[#filtered + 1] = normalizedDomain
          end
        end
        resolvedDomains = filtered
      end
    end

    local remainingDomains, sessionSubdomains = profileSyncMetaOps.buildTargetedSessionRepairScope(
      resolvedDomains,
      sessionId
    )
    return remainingDomains, MergeCheckpointSubdomainLists(targetedSubdomains, sessionSubdomains)
  end

  profileSyncMetaOps.filterRepairSubdomainsByDomain = function(subdomains, includeDomain)
    local resolvedInclude = string.lower(TrimText(includeDomain))
    local filtered = {}
    for _, subdomain in ipairs(type(subdomains) == "table" and subdomains or {}) do
      local resolvedSubdomain = TrimText(subdomain)
      if resolvedSubdomain ~= ""
        and type(profileSyncMetaOps.getSubdomainParentDomain) == "function"
        and string.lower(TrimText(profileSyncMetaOps.getSubdomainParentDomain(resolvedSubdomain))) == resolvedInclude
      then
        filtered[#filtered + 1] = resolvedSubdomain
      end
    end
    return filtered
  end

  profileSyncMetaOps.excludeRepairSubdomainsByDomain = function(subdomains, excludedDomain)
    local resolvedExcluded = string.lower(TrimText(excludedDomain))
    local filtered = {}
    for _, subdomain in ipairs(type(subdomains) == "table" and subdomains or {}) do
      local resolvedSubdomain = TrimText(subdomain)
      local parentDomain = type(profileSyncMetaOps.getSubdomainParentDomain) == "function"
        and string.lower(TrimText(profileSyncMetaOps.getSubdomainParentDomain(resolvedSubdomain)))
        or ""
      if resolvedSubdomain ~= "" and parentDomain ~= resolvedExcluded then
        filtered[#filtered + 1] = resolvedSubdomain
      end
    end
    return filtered
  end

  profileSyncMetaOps.hasMeaningfulArchiveLootLedgerRow = function(profile, characterKey)
    local resolvedKey = NormalizeCharacterKey(characterKey)
    local row = type(profile) == "table" and type(profile.lootLedger) == "table" and profile.lootLedger[resolvedKey] or nil
    if type(row) ~= "table" then
      return false
    end
    -- Retain zero-point roster rows. A fresh member still needs to see every
    -- character in the host Loot List, even before that character has loot.
    return TrimText(row.character) ~= ""
      or type(row.items) == "table"
      or tonumber(row.totalPoints) ~= nil
  end

  profileSyncMetaOps.hasMeaningfulArchiveLootLedgerMeta = function(profile, characterKey)
    local resolvedKey = NormalizeCharacterKey(characterKey)
    local meta = type(profile) == "table" and type(profile.lootLedgerMeta) == "table" and profile.lootLedgerMeta[resolvedKey] or nil
    if type(meta) ~= "table" then
      return false
    end
    local penaltyPoints = tonumber(meta.penaltyPoints) or 0
    local classFile = TrimText(meta.classFile)
    local className = TrimText(meta.className)
    local specName = TrimText(meta.specName)
    local specID = tonumber(meta.specID)
    specID = specID and specID > 0 and math.floor(specID) or nil
    local specIcon = TrimText(meta.specIcon)
    local note = TrimText(meta.note)
    local mainCharacter = TrimText(meta.mainCharacter)
    local mainAltRole = string.upper(TrimText(meta.mainAltRole))
    if mainAltRole ~= "ALT" then
      mainAltRole = "MAIN"
    end
    if string.lower(mainCharacter) == string.lower(resolvedKey) then
      mainCharacter = ""
      mainAltRole = "MAIN"
    elseif mainCharacter ~= "" then
      mainAltRole = "ALT"
    end
    return penaltyPoints ~= 0
      or classFile ~= ""
      or className ~= ""
      or specName ~= ""
      or specID ~= nil
      or specIcon ~= ""
      or note ~= ""
      or mainCharacter ~= ""
      or mainAltRole ~= "MAIN"
  end

  profileSyncMetaOps.shouldIncludeDeferredArchiveLootSubdomain = function(profile, subdomain)
    local resolvedSubdomain = string.lower(TrimText(subdomain))
    local identity = NormalizeCharacterKey((TrimText(subdomain):match("^[^:]+:(.+)$")) or "")
    if resolvedSubdomain:find("^llr:", 1, false) then
      return identity ~= "" and profileSyncMetaOps.hasMeaningfulArchiveLootLedgerRow(profile, identity)
    elseif resolvedSubdomain:find("^lmr:", 1, false) then
      return identity ~= "" and profileSyncMetaOps.hasMeaningfulArchiveLootLedgerMeta(profile, identity)
    end
    return true
  end

  profileSyncMetaOps.buildFreshMemberLootSubdomainPlan = function(profileName, activeSession)
    if type(deps.GetLootProfile) ~= "function" or type(profileSyncMetaOps.getSubdomainKeysForDomain) ~= "function" then
      return {}, {}
    end

    local sourceProfile = select(1, deps.GetLootProfile(profileName))
    if type(sourceProfile) ~= "table" then
      return {}, {}
    end

    local rosterLookup = profileSyncMetaOps.buildActiveSessionRosterLookup(activeSession)

    local essential = {}
    local deferred = {}
    for _, subdomain in ipairs(profileSyncMetaOps.getSubdomainKeysForDomain("loot", sourceProfile) or {}) do
      local resolvedSubdomain = TrimText(subdomain)
      if resolvedSubdomain ~= "" then
        local tier = profileSyncMetaOps.classifyLootRepairSubdomainTier(resolvedSubdomain, rosterLookup)
        if tier == "live" then
          essential[#essential + 1] = resolvedSubdomain
        elseif tier == "archive" then
          if profileSyncMetaOps.shouldIncludeDeferredArchiveLootSubdomain(sourceProfile, resolvedSubdomain) then
            deferred[#deferred + 1] = resolvedSubdomain
          end
        else
          deferred[#deferred + 1] = resolvedSubdomain
        end
      end
    end

    return CloneCheckpointSubdomainList(essential), CloneCheckpointSubdomainList(deferred)
  end

  profileSyncMetaOps.buildFreshMemberSessionArchiveSubdomains = function(profileName, sessionId)
    if type(deps.GetLootProfile) ~= "function" or type(profileSyncMetaOps.getSubdomainKeysForDomain) ~= "function" then
      return {}
    end
    local sourceProfile = select(1, deps.GetLootProfile(profileName))
    if type(sourceProfile) ~= "table" then
      return {}
    end
    local currentSessionLookup = {}
    for _, subdomain in ipairs(profileSyncMetaOps.buildCurrentSessionCheckpointSubdomains(sessionId)) do
      currentSessionLookup[string.lower(TrimText(subdomain))] = true
    end
    local archive = {}
    for _, subdomain in ipairs(profileSyncMetaOps.getSubdomainKeysForDomain("session", sourceProfile) or {}) do
      local resolvedSubdomain = TrimText(subdomain)
      if resolvedSubdomain ~= "" and not currentSessionLookup[string.lower(resolvedSubdomain)] then
        archive[#archive + 1] = resolvedSubdomain
      end
    end
    return CloneCheckpointSubdomainList(archive)
  end

  profileSyncMetaOps.buildLatestCompletedSessionHistorySubdomain = function(profileName, activeSession)
    if type(deps.GetLootProfile) ~= "function" then
      return "", nil
    end
    local sourceProfile = select(1, deps.GetLootProfile(profileName))
    local latestSession = INTERNAL_API.LIDCOUNCIL_SelectLatestCompletedSessionRecord_Impl(
      type(sourceProfile) == "table" and sourceProfile.sessions or nil,
      type(activeSession) == "table" and activeSession.id or ""
    )
    if type(latestSession) ~= "table" then
      return "", nil
    end
    return BuildSessionRecordCheckpointSubdomain(latestSession.id), latestSession
  end

  profileSyncMetaOps.buildLivePreciseStatePrewarmDomains = function(domains)
    return MergeComparedDomains({ "loot", "session" }, domains)
  end

  profileSyncMetaOps.buildLivePreciseStatePatchSubdomains = function(profileName, activeSession, extraSubdomains)
    local essentialLootSubdomains = select(
      1,
      profileSyncMetaOps.buildFreshMemberLootSubdomainPlan(profileName, activeSession)
    )
    local mergedLootSubdomains = MergeCheckpointSubdomainLists(
      essentialLootSubdomains,
      profileSyncMetaOps.filterRepairSubdomainsByDomain(extraSubdomains, "loot")
    )
    if type(deps.FilterLootProfilePatchCapableSubdomains) == "function" then
      mergedLootSubdomains = deps.FilterLootProfilePatchCapableSubdomains(mergedLootSubdomains)
    end
    return CloneCheckpointSubdomainList(mergedLootSubdomains)
  end

  local function PrewarmMemberPreciseLiveSyncState(activeSession, profileName, sessionId, memberKey, opts)
    opts = type(opts) == "table" and opts or {}
    local resolvedProfileName = TrimText(profileName)
    local resolvedSessionId = TrimText(sessionId)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if type(activeSession) ~= "table"
      or resolvedProfileName == ""
      or resolvedSessionId == ""
      or resolvedMemberKey == ""
    then
      return 0, 0
    end

    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if not AreCharacterKeysSame(activeSession.host or "", selfKey)
      or not IsJoinedSessionCharacter(activeSession, resolvedMemberKey)
    then
      return 0, 0
    end

    local prewarmDomains = profileSyncMetaOps.buildLivePreciseStatePrewarmDomains(opts.domains)
    local patchSubdomains = profileSyncMetaOps.buildLivePreciseStatePatchSubdomains(
      resolvedProfileName,
      activeSession,
      opts.subdomains
    )
    local normalizedPrewarmDomains = CloneCheckpointDomainList(prewarmDomains)
    local normalizedPatchSubdomains = CloneCheckpointSubdomainList(patchSubdomains)
    table.sort(normalizedPrewarmDomains, function(left, right)
      return string.lower(TrimText(left)) < string.lower(TrimText(right))
    end)
    table.sort(normalizedPatchSubdomains, function(left, right)
      return string.lower(TrimText(left)) < string.lower(TrimText(right))
    end)
    local prewarmRequestKey = string.lower(resolvedSessionId) .. "|" .. string.lower(resolvedMemberKey)
    local prewarmRequestSignature = table.concat({
      table.concat(normalizedPrewarmDomains, "\30"),
      table.concat(normalizedPatchSubdomains, "\30"),
      opts.force == true and "1" or "0",
    }, "\31")
    local prewarmNow = GetProfileCheckpointSyncTime()
    local recentPrewarmRequest = sessionRuntime.recentMemberPrecisePrewarmRequests[prewarmRequestKey]
    if type(recentPrewarmRequest) == "table" then
      local recentRequestedAt = math.max(0, tonumber(recentPrewarmRequest.requestedAt or recentPrewarmRequest.updatedAt) or 0)
      if recentRequestedAt <= 0
        or (prewarmNow - recentRequestedAt) >= sessionConfig.memberPrecisePrewarmRetentionSeconds
      then
        sessionRuntime.recentMemberPrecisePrewarmRequests[prewarmRequestKey] = nil
        recentPrewarmRequest = nil
      end
    end
    if type(recentPrewarmRequest) == "table"
      and TrimText(recentPrewarmRequest.signature) == prewarmRequestSignature
      and (prewarmNow - math.max(0, tonumber(recentPrewarmRequest.requestedAt) or 0))
        < sessionConfig.memberPrecisePrewarmDedupeSeconds
    then
      if type(RecordProfileSyncDecision) == "function" then
        RecordProfileSyncDecision("prewarm_precise_state", {
          action = "suppressed_unchanged",
          sessionId = resolvedSessionId,
          profileName = resolvedProfileName,
          mode = TrimText(opts.mode),
          reason = TrimText(opts.reason),
          target = resolvedMemberKey,
          targetCount = 1,
          queuedCount = 0,
          requestedDomains = CloneCheckpointDomainList(prewarmDomains),
          requestedSubdomains = CloneCheckpointSubdomainList(patchSubdomains),
          chunkCount = 0,
        })
      end
      return 0, 0
    end
    local requestedSubchecks = type(profileSyncMetaOps.sendSubchecksumRequests) == "function"
      and profileSyncMetaOps.sendSubchecksumRequests(resolvedMemberKey, prewarmDomains, {
        force = opts.force == true,
        auto = true,
      })
      or 0
    local requestedPatchManifests = type(deps.SendProfilePatchManifestRequests) == "function" and #patchSubdomains > 0
      and deps.SendProfilePatchManifestRequests(resolvedMemberKey, patchSubdomains, {
        force = opts.force == true,
        auto = true,
      })
      or 0

    if prewarmRequestSignature ~= "" then
      sessionRuntime.recentMemberPrecisePrewarmRequests[prewarmRequestKey] = {
        signature = prewarmRequestSignature,
        requestedAt = prewarmNow,
      }
    end

    if type(RecordProfileSyncDecision) == "function" then
      RecordProfileSyncDecision("prewarm_precise_state", {
        action = (requestedSubchecks > 0 or requestedPatchManifests > 0) and "requested" or "skipped",
        sessionId = resolvedSessionId,
        profileName = resolvedProfileName,
        mode = TrimText(opts.mode),
        reason = TrimText(opts.reason),
        target = resolvedMemberKey,
        targetCount = 1,
        queuedCount = math.max(0, tonumber(requestedSubchecks) or 0) + math.max(0, tonumber(requestedPatchManifests) or 0),
        requestedDomains = CloneCheckpointDomainList(prewarmDomains),
        requestedSubdomains = CloneCheckpointSubdomainList(patchSubdomains),
        chunkCount = math.max(0, tonumber(requestedSubchecks) or 0) + math.max(0, tonumber(requestedPatchManifests) or 0),
      })
    end

    return requestedSubchecks, requestedPatchManifests
  end

  local function BuildJoinManifestRepairTimerKey(sessionId, memberKey)
    return string.lower(TrimText(sessionId)) .. "|" .. string.lower(NormalizeCharacterKey(memberKey))
  end

  profileSyncMetaOps.getJoinManifestProofTombstone = function(proofIdentity)
    local resolvedIdentity = tostring(proofIdentity or "")
    if resolvedIdentity == "" then
      return nil
    end
    local tombstone = sessionRuntime.joinManifestProofTombstones[resolvedIdentity]
    return type(tombstone) == "table" and tombstone or nil
  end

  profileSyncMetaOps.filterTerminalJoinManifestProofDomains = function(sessionId, memberKey, profileRevision, domains)
    local resolvedSessionId = TrimText(sessionId)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    local resolvedProfileRevision = tostring(profileRevision or "")
    local requestedDomains = CloneCheckpointDomainList(domains)
    if resolvedSessionId == "" or resolvedMemberKey == "" or resolvedProfileRevision == "" then
      return requestedDomains
    end

    local blockedDomains = {}
    for _, tombstone in pairs(sessionRuntime.joinManifestProofTombstones) do
      if type(tombstone) == "table"
        and string.lower(TrimText(tombstone.sessionId)) == string.lower(resolvedSessionId)
        and AreCharacterKeysSame(tombstone.memberKey, resolvedMemberKey)
        and tostring(tombstone.profileRevision or "") == resolvedProfileRevision
      then
        for _, domain in ipairs(CloneCheckpointDomainList(tombstone.domains)) do
          blockedDomains[domain] = true
        end
      end
    end

    local filteredDomains = {}
    for _, domain in ipairs(requestedDomains) do
      if blockedDomains[domain] ~= true then
        filteredDomains[#filteredDomains + 1] = domain
      end
    end
    return filteredDomains
  end

  profileSyncMetaOps.markJoinManifestProofTerminal = function(pendingState, failureReason)
    if type(pendingState) ~= "table" then
      return false
    end
    local proofIdentity = tostring(pendingState.proofIdentity or "")
    if proofIdentity == "" then
      return false
    end
    sessionRuntime.joinManifestProofTombstones[proofIdentity] = {
      proofIdentity = proofIdentity,
      token = TrimText(pendingState.token),
      sessionId = TrimText(pendingState.sessionId),
      profileName = TrimText(pendingState.profileName),
      memberKey = NormalizeCharacterKey(pendingState.memberKey),
      profileRevision = tostring(pendingState.profileRevision or ""),
      domains = CloneCheckpointDomainList(
        type(pendingState.proofDomains) == "table" and pendingState.proofDomains or pendingState.domains
      ),
      subdomains = CloneCheckpointSubdomainList(pendingState.subdomains),
      attempts = math.max(0, tonumber(pendingState.preciseProofAttempts) or 0),
      maxAttempts = math.max(1, tonumber(pendingState.maxPreciseProofAttempts) or 4),
      failedAt = GetProfileCheckpointSyncTime(),
      failureReason = TrimText(failureReason),
    }
    return true
  end

  profileSyncMetaOps.clearJoinManifestProofTombstones = function(sessionId, memberKey)
    local resolvedSessionId = TrimText(sessionId)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if resolvedSessionId == "" then
      return 0
    end
    local removed = 0
    for proofIdentity, tombstone in pairs(sessionRuntime.joinManifestProofTombstones) do
      if type(tombstone) == "table"
        and string.lower(TrimText(tombstone.sessionId)) == string.lower(resolvedSessionId)
        and (resolvedMemberKey == "" or AreCharacterKeysSame(tombstone.memberKey, resolvedMemberKey))
      then
        sessionRuntime.joinManifestProofTombstones[proofIdentity] = nil
        removed = removed + 1
      end
    end
    return removed
  end

  profileSyncMetaOps.takeJoinManifestProofRearmState = function(sessionId, memberKey)
    local resolvedSessionId = TrimText(sessionId)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if resolvedSessionId == "" or resolvedMemberKey == "" then
      return nil
    end

    local rearmState = type(profileSyncMetaOps.getPendingJoinManifestRepair) == "function"
      and profileSyncMetaOps.getPendingJoinManifestRepair(resolvedSessionId, resolvedMemberKey)
      or nil
    local hadPrecisePending = type(rearmState) == "table" and rearmState.requirePreciseProof == true
    if type(rearmState) ~= "table" or rearmState.requirePreciseProof ~= true then
      rearmState = nil
      local latestFailedAt = -1
      for _, tombstone in pairs(sessionRuntime.joinManifestProofTombstones) do
        if type(tombstone) == "table"
          and string.lower(TrimText(tombstone.sessionId)) == string.lower(resolvedSessionId)
          and AreCharacterKeysSame(tombstone.memberKey, resolvedMemberKey)
        then
          local failedAt = math.max(0, tonumber(tombstone.failedAt) or 0)
          if rearmState == nil or failedAt >= latestFailedAt then
            rearmState = tombstone
            latestFailedAt = failedAt
          end
        end
      end
    end

    local copy = nil
    if type(rearmState) == "table" then
      copy = {
        profileName = TrimText(rearmState.profileName),
        domains = CloneCheckpointDomainList(
          type(rearmState.proofDomains) == "table" and rearmState.proofDomains or rearmState.domains
        ),
        subdomains = CloneCheckpointSubdomainList(rearmState.subdomains),
        maxPreciseProofAttempts = math.max(1, tonumber(rearmState.maxPreciseProofAttempts or rearmState.maxAttempts) or 4),
      }
    end
    if hadPrecisePending and type(profileSyncMetaOps.clearPendingJoinManifestRepair) == "function" then
      profileSyncMetaOps.clearPendingJoinManifestRepair(resolvedSessionId, resolvedMemberKey)
    end
    profileSyncMetaOps.clearJoinManifestProofTombstones(resolvedSessionId, resolvedMemberKey)
    return copy
  end

  local function BuildMissingMemberHistoryTimerKey(sessionId, memberKey)
    return string.lower(TrimText(sessionId)) .. "|" .. string.lower(NormalizeCharacterKey(memberKey))
  end

  profileSyncMetaOps.getPendingJoinManifestRepair = function(sessionId, memberKey)
    local resolvedSessionId = TrimText(sessionId)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if resolvedSessionId == "" or resolvedMemberKey == "" then
      return nil
    end
    local pendingKey = BuildJoinManifestRepairTimerKey(resolvedSessionId, resolvedMemberKey)
    local pendingState = sessionRuntime.pendingJoinManifestRepairTimers.joinManifest[pendingKey]
    if type(pendingState) == "table" then
      local now = GetProfileCheckpointSyncTime()
      local updatedAt = math.max(0, tonumber(pendingState.updatedAt or pendingState.queuedAt) or 0)
      if updatedAt <= 0 or (now - updatedAt) >= sessionConfig.pendingJoinManifestRepairRetentionSeconds then
        -- Matrix construction also reads this state. Expire it in place instead
        -- of publishing recursively while an existing MEMBER payload is built.
        if pendingState.requirePreciseProof == true then
          profileSyncMetaOps.markJoinManifestProofTerminal(
            pendingState,
            "precise_archive_proof_pending_state_expired"
          )
        end
        sessionRuntime.pendingJoinManifestRepairTimers.joinManifest[pendingKey] = nil
        return nil
      end
    end
    if type(pendingState) == "table" and pendingState.kind == "join_manifest" then
      return pendingState
    end
    return nil
  end

  profileSyncMetaOps.upsertPendingJoinManifestRepair = function(sessionId, memberKey, pendingState)
    local resolvedSessionId = TrimText(sessionId)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if resolvedSessionId == "" or resolvedMemberKey == "" or type(pendingState) ~= "table" then
      return false
    end
    local now = GetProfileCheckpointSyncTime()
    pendingState.kind = "join_manifest"
    pendingState.sessionId = resolvedSessionId
    pendingState.memberKey = resolvedMemberKey
    pendingState.queuedAt = math.max(0, tonumber(pendingState.queuedAt) or now)
    pendingState.updatedAt = now
    pendingState.domains = CloneCheckpointDomainList(type(pendingState.domains) == "table" and pendingState.domains or {})
    pendingState.proofDomains = CloneCheckpointDomainList(
      type(pendingState.proofDomains) == "table" and pendingState.proofDomains or pendingState.domains
    )
    pendingState.subdomains = CloneCheckpointSubdomainList(type(pendingState.subdomains) == "table" and pendingState.subdomains or {})
    pendingState.requestedComparisonDomains = CloneCheckpointDomainList(
      type(pendingState.requestedComparisonDomains) == "table" and pendingState.requestedComparisonDomains or {}
    )
    sessionRuntime.pendingJoinManifestRepairTimers.joinManifest[
      BuildJoinManifestRepairTimerKey(resolvedSessionId, resolvedMemberKey)
    ] = pendingState
    if type(profileSyncMetaOps.publishJoinManifestValidationState) == "function" then
      profileSyncMetaOps.publishJoinManifestValidationState(resolvedSessionId, resolvedMemberKey)
    end
    return true
  end

  profileSyncMetaOps.clearPendingJoinManifestRepair = function(sessionId, memberKey)
    local resolvedSessionId = TrimText(sessionId)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if resolvedSessionId == "" or resolvedMemberKey == "" then
      return
    end
    local pendingKey = BuildJoinManifestRepairTimerKey(resolvedSessionId, resolvedMemberKey)
    local hadPendingState = type(sessionRuntime.pendingJoinManifestRepairTimers.joinManifest[pendingKey]) == "table"
    sessionRuntime.pendingJoinManifestRepairTimers.joinManifest[pendingKey] = nil
    if hadPendingState and type(profileSyncMetaOps.publishJoinManifestValidationState) == "function" then
      profileSyncMetaOps.publishJoinManifestValidationState(resolvedSessionId, resolvedMemberKey)
    end
  end

  do
    local sendProfileSubchecksumRequests = profileSyncMetaOps.sendSubchecksumRequests
    profileSyncMetaOps.sendSubchecksumRequests = function(memberKey, domains, options)
      if type(sendProfileSubchecksumRequests) ~= "function" then
        return 0
      end
      local resolvedOptions = {}
      for key, value in pairs(type(options) == "table" and options or {}) do
        resolvedOptions[key] = value
      end

      local activeSession, activeProfileName = GetActiveLootSession()
      local resolvedSessionId = TrimText(type(activeSession) == "table" and activeSession.id or "")
      local resolvedMemberKey = NormalizeCharacterKey(memberKey)
      local pendingState = resolvedSessionId ~= ""
        and resolvedMemberKey ~= ""
        and profileSyncMetaOps.getPendingJoinManifestRepair(resolvedSessionId, resolvedMemberKey)
        or nil
      if type(pendingState) == "table"
        and pendingState.requirePreciseProof == true
        and TrimText(pendingState.token) ~= ""
      then
        local requestedDomains = CloneCheckpointDomainList(domains)
        local pendingDomains = CloneCheckpointDomainList(
          type(pendingState.proofDomains) == "table" and pendingState.proofDomains or pendingState.domains
        )
        local samePendingScope = #requestedDomains == #pendingDomains
        if samePendingScope then
          local pendingLookup = {}
          for _, domain in ipairs(pendingDomains) do
            pendingLookup[string.lower(TrimText(domain))] = true
          end
          for _, domain in ipairs(requestedDomains) do
            if pendingLookup[string.lower(TrimText(domain))] ~= true then
              samePendingScope = false
              break
            end
          end
        end
        if samePendingScope then
          resolvedOptions.requestToken = TrimText(pendingState.token)
        elseif resolvedOptions.auto == true then
          -- A different automatic scope is neither a retry nor permission to
          -- mutate the in-flight proof identity. The deferred scheduler owns
          -- changed-identity rearming and will issue a fresh token explicitly.
          return 0
        end
      elseif resolvedOptions.auto == true
        and type(activeSession) == "table"
        and TrimText(activeProfileName) ~= ""
      then
        local syncCandidate = select(1, GetActiveSyncCandidateContext(resolvedMemberKey))
        local profileRevision = BuildLocalRepairRevisionSignature(
          activeSession,
          activeProfileName,
          syncCandidate
        )
        domains = profileSyncMetaOps.filterTerminalJoinManifestProofDomains(
          resolvedSessionId,
          resolvedMemberKey,
          profileRevision,
          domains
        )
        if #domains == 0 then
          return 0
        end
      end
      return sendProfileSubchecksumRequests(memberKey, domains, resolvedOptions)
    end
  end

  profileSyncMetaOps.getPendingPatchStateRetry = function(sessionId, memberKey)
    local resolvedSessionId = TrimText(sessionId)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if resolvedSessionId == "" or resolvedMemberKey == "" then
      return nil
    end
    local pendingKey = "patchstate|" .. BuildJoinManifestRepairTimerKey(resolvedSessionId, resolvedMemberKey)
    local pendingState = sessionRuntime.pendingJoinManifestRepairTimers.patchStateRetry[pendingKey]
    if type(pendingState) == "table" then
      local now = GetProfileCheckpointSyncTime()
      local updatedAt = math.max(0, tonumber(pendingState.updatedAt or pendingState.queuedAt) or 0)
      if updatedAt <= 0 or (now - updatedAt) >= sessionConfig.pendingPatchStateRetryRetentionSeconds then
        sessionRuntime.pendingJoinManifestRepairTimers.patchStateRetry[pendingKey] = nil
        return nil
      end
    end
    if type(pendingState) == "table"
      and pendingState.kind == "patch_state_retry"
      and TrimText(pendingState.token) ~= ""
    then
      return pendingState
    end
    return nil
  end

  profileSyncMetaOps.upsertPendingPatchStateRetry = function(sessionId, memberKey, pendingState)
    local resolvedSessionId = TrimText(sessionId)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    local resolvedToken = TrimText(type(pendingState) == "table" and pendingState.token or "")
    if resolvedSessionId == "" or resolvedMemberKey == "" or resolvedToken == "" then
      return false
    end
    local now = GetProfileCheckpointSyncTime()
    pendingState.kind = "patch_state_retry"
    pendingState.token = resolvedToken
    pendingState.sessionId = resolvedSessionId
    pendingState.memberKey = resolvedMemberKey
    pendingState.queuedAt = math.max(0, tonumber(pendingState.queuedAt) or now)
    pendingState.updatedAt = now
    pendingState.subdomains = CloneCheckpointSubdomainList(type(pendingState.subdomains) == "table" and pendingState.subdomains or {})
    sessionRuntime.pendingJoinManifestRepairTimers.patchStateRetry[
      "patchstate|" .. BuildJoinManifestRepairTimerKey(resolvedSessionId, resolvedMemberKey)
    ] = pendingState
    return true
  end

  profileSyncMetaOps.getPendingPatchStateRetryToken = function(sessionId, memberKey)
    local pendingState = type(profileSyncMetaOps.getPendingPatchStateRetry) == "function"
      and profileSyncMetaOps.getPendingPatchStateRetry(sessionId, memberKey)
      or nil
    return type(pendingState) == "table" and TrimText(pendingState.token) or nil
  end

  profileSyncMetaOps.upsertPendingPatchStateRetryToken = function(sessionId, memberKey, token)
    local resolvedToken = TrimText(token)
    if resolvedToken == "" then
      return false
    end
    local pendingState = type(profileSyncMetaOps.getPendingPatchStateRetry) == "function"
      and profileSyncMetaOps.getPendingPatchStateRetry(sessionId, memberKey)
      or {}
    pendingState.token = resolvedToken
    return profileSyncMetaOps.upsertPendingPatchStateRetry(sessionId, memberKey, pendingState)
  end

  profileSyncMetaOps.clearPendingPatchStateRetry = function(sessionId, memberKey)
    local resolvedSessionId = TrimText(sessionId)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if resolvedSessionId == "" or resolvedMemberKey == "" then
      return
    end
    sessionRuntime.pendingJoinManifestRepairTimers.patchStateRetry[
      "patchstate|" .. BuildJoinManifestRepairTimerKey(resolvedSessionId, resolvedMemberKey)
    ] = nil
  end

  profileSyncMetaOps.clearPendingPatchStateRetryToken = function(sessionId, memberKey)
    profileSyncMetaOps.clearPendingPatchStateRetry(sessionId, memberKey)
  end

  local function ScheduleDeferredJoinManifestRepair(profileName, sessionId, memberKey, domains, subdomains, opts)
    opts = type(opts) == "table" and opts or {}
    local resolvedProfileName = TrimText(profileName)
    local resolvedSessionId = TrimText(sessionId)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    local resolvedDomains = CloneCheckpointDomainList(domains)
    local resolvedSubdomains = CloneCheckpointSubdomainList(subdomains)
    if resolvedProfileName == "" or resolvedSessionId == "" or resolvedMemberKey == ""
      or (#resolvedDomains == 0 and #resolvedSubdomains == 0)
    then
      return false
    end

    local scheduleCandidate = select(1, GetActiveSyncCandidateContext(resolvedMemberKey))
    local resolvedProfileId = TrimText(select(1, deps.GetLootProfileId(resolvedProfileName)) or "")
    local resolvedMemberProfileId = FirstNonEmptyText(
      type(scheduleCandidate) == "table" and scheduleCandidate.profileId or nil,
      type(scheduleCandidate) == "table" and scheduleCandidate.remoteProfileId or nil
    )

    local function StripBroadDomainsForPreciseSubdomains(domainList, subdomainList)
      local preciseDomainLookup = {}
      for _, subdomain in ipairs(type(subdomainList) == "table" and subdomainList or {}) do
        local parentDomain = type(profileSyncMetaOps.getSubdomainParentDomain) == "function"
          and string.lower(TrimText(profileSyncMetaOps.getSubdomainParentDomain(subdomain)))
          or ""
        if parentDomain ~= "" then
          preciseDomainLookup[parentDomain] = true
        end
      end
      if next(preciseDomainLookup) == nil then
        return CloneCheckpointDomainList(domainList)
      end
      local narrowedDomains = {}
      for _, domain in ipairs(type(domainList) == "table" and domainList or {}) do
        local resolvedDomain = string.lower(TrimText(domain))
        if resolvedDomain ~= "" and not preciseDomainLookup[resolvedDomain] then
          narrowedDomains[#narrowedDomains + 1] = resolvedDomain
        end
      end
      return narrowedDomains
    end

    local requestedRepairDomains = StripBroadDomainsForPreciseSubdomains(resolvedDomains, resolvedSubdomains)
    local requestedProofDomains = CloneCheckpointDomainList(resolvedDomains)
    local requestedRepairSubdomains = CloneCheckpointSubdomainList(resolvedSubdomains)
    local scheduleActiveSession = select(1, GetActiveLootSession())
    local profileRevision = BuildLocalRepairRevisionSignature(
      scheduleActiveSession,
      resolvedProfileName,
      scheduleCandidate,
      opts.profileRevision
    )
    local proofIdentity = INTERNAL_API.LIDCOUNCIL_BuildJoinManifestProofIdentity_Impl({
      sessionId = resolvedSessionId,
      memberKey = resolvedMemberKey,
      profileRevision = profileRevision,
      domains = requestedProofDomains,
      subdomains = requestedRepairSubdomains,
    })
    if proofIdentity == "" then
      return false, "invalid_proof_identity"
    end

    local pendingState = type(profileSyncMetaOps.getPendingJoinManifestRepair) == "function"
      and profileSyncMetaOps.getPendingJoinManifestRepair(resolvedSessionId, resolvedMemberKey)
      or nil
    local terminalState = profileSyncMetaOps.getJoinManifestProofTombstone(proofIdentity)
    local lifecycle = INTERNAL_API.LIDCOUNCIL_ResolveJoinManifestProofRequest_Impl({
      proofIdentity = proofIdentity,
      pendingState = pendingState,
      terminalState = terminalState,
      manualRearm = opts.manualRearm == true,
    })
    if lifecycle.action == "reuse_pending" then
      local wasPreciseProof = pendingState.requirePreciseProof == true
      pendingState.requirePreciseProof = wasPreciseProof or opts.requirePreciseProof == true
      pendingState.proofDomains = CloneCheckpointDomainList(requestedProofDomains)
      pendingState.requestedComparisonDomains = pendingState.requirePreciseProof == true
        and CloneCheckpointDomainList(
          MergeComparedDomains(pendingState.requestedComparisonDomains, requestedProofDomains)
        )
        or CloneCheckpointDomainList(pendingState.requestedComparisonDomains)
      pendingState.maxPreciseProofAttempts = math.max(
        math.max(1, tonumber(pendingState.maxPreciseProofAttempts) or 0),
        math.max(1, tonumber(opts.maxPreciseProofAttempts) or 4)
      )
      pendingState.updatedAt = GetProfileCheckpointSyncTime()
      local reused = profileSyncMetaOps.upsertPendingJoinManifestRepair(
        resolvedSessionId,
        resolvedMemberKey,
        pendingState
      )
      if reused
        and not wasPreciseProof
        and pendingState.requirePreciseProof == true
        and #pendingState.proofDomains > 0
        and type(profileSyncMetaOps.sendSubchecksumRequests) == "function"
      then
        profileSyncMetaOps.sendSubchecksumRequests(resolvedMemberKey, pendingState.proofDomains, {
          force = true,
          auto = true,
          requestToken = TrimText(pendingState.token),
        })
      end
      return reused, reused and "pending_reused" or "pending_reuse_failed", TrimText(pendingState.token)
    end
    if lifecycle.action == "suppress_terminal" then
      if type(RecordProfileSyncDecision) == "function" then
        RecordProfileSyncDecision("aligned_replica_archive_repair", {
          action = "precise_proof_terminal_suppressed",
          sessionId = resolvedSessionId,
          profileName = resolvedProfileName,
          mode = TrimText(opts.mode) ~= "" and TrimText(opts.mode) or "BACKGROUND",
          reason = "aligned_replica_manifest_required",
          target = resolvedMemberKey,
          targetCount = 1,
          queuedCount = 0,
          requestedDomains = CloneCheckpointDomainList(requestedProofDomains),
          requestedSubdomains = CloneCheckpointSubdomainList(requestedRepairSubdomains),
          requestedScope = "precise",
          error = "Precise archive proof retry limit is in terminal cooldown for this revision and scope.",
        })
      end
      return false, "precise_proof_terminal_cooldown"
    end

    -- Reaching a different identity is itself an allowed rearm event. Retire
    -- older terminal identities for this member so a later revision/scope
    -- transition is evaluated from the newly armed lifecycle.
    profileSyncMetaOps.clearJoinManifestProofTombstones(resolvedSessionId, resolvedMemberKey)

    local token = string.format("JMR-%d-%d", tonumber(time and time() or 0) or 0, math.random(1000, 9999))
    pendingState = {
      kind = "join_manifest",
      token = token,
      proofIdentity = proofIdentity,
      profileRevision = profileRevision,
      profileName = resolvedProfileName,
      sessionId = resolvedSessionId,
      memberKey = resolvedMemberKey,
      profileId = resolvedProfileId,
      memberProfileId = resolvedMemberProfileId,
      domains = CloneCheckpointDomainList(requestedRepairDomains),
      proofDomains = CloneCheckpointDomainList(requestedProofDomains),
      subdomains = CloneCheckpointSubdomainList(requestedRepairSubdomains),
      requestedComparisonDomains = opts.requirePreciseProof == true
        and CloneCheckpointDomainList(requestedProofDomains)
        or {},
      requirePreciseProof = opts.requirePreciseProof == true,
      preciseProofAttempts = 0,
      maxPreciseProofAttempts = math.max(1, tonumber(opts.maxPreciseProofAttempts) or 4),
    }
    profileSyncMetaOps.upsertPendingJoinManifestRepair(resolvedSessionId, resolvedMemberKey, pendingState)
    if pendingState.requirePreciseProof == true
      and #pendingState.proofDomains > 0
      and type(profileSyncMetaOps.sendSubchecksumRequests) == "function"
    then
      profileSyncMetaOps.sendSubchecksumRequests(resolvedMemberKey, pendingState.proofDomains, {
        force = true,
        auto = true,
        requestToken = token,
      })
    end

    local function RunDeferredRepair()
      local currentPending = type(profileSyncMetaOps.getPendingJoinManifestRepair) == "function"
        and profileSyncMetaOps.getPendingJoinManifestRepair(resolvedSessionId, resolvedMemberKey)
        or nil
      if type(currentPending) ~= "table" or currentPending.token ~= token then
        return
      end
      local currentDomains = CloneCheckpointDomainList(currentPending.domains)
      local currentProofDomains = CloneCheckpointDomainList(
        type(currentPending.proofDomains) == "table" and currentPending.proofDomains or currentPending.domains
      )
      local currentSubdomains = CloneCheckpointSubdomainList(currentPending.subdomains)

      local activeSession, activeProfileName = GetActiveLootSession()
      local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
      if not activeSession
        or not DoesActiveSessionMatch(activeSession, activeProfileName, resolvedSessionId, resolvedProfileName)
        or not AreCharacterKeysSame(activeSession.host or "", selfKey)
        or not IsJoinedSessionCharacter(activeSession, resolvedMemberKey)
      then
        profileSyncMetaOps.clearPendingJoinManifestRepair(resolvedSessionId, resolvedMemberKey)
        return
      end

      local syncCandidate = select(1, GetActiveSyncCandidateContext(resolvedMemberKey))
      if currentPending.requirePreciseProof == true then
        local currentProfileRevision = BuildLocalRepairRevisionSignature(
          activeSession,
          resolvedProfileName,
          syncCandidate
        )
        local currentProofIdentity = INTERNAL_API.LIDCOUNCIL_BuildJoinManifestProofIdentity_Impl({
          sessionId = resolvedSessionId,
          memberKey = resolvedMemberKey,
          profileRevision = currentProfileRevision,
          domains = currentProofDomains,
          subdomains = currentSubdomains,
        })
        if currentProofIdentity ~= "" and currentProofIdentity ~= tostring(currentPending.proofIdentity or "") then
          profileSyncMetaOps.clearPendingJoinManifestRepair(resolvedSessionId, resolvedMemberKey)
          ScheduleDeferredJoinManifestRepair(
            resolvedProfileName,
            resolvedSessionId,
            resolvedMemberKey,
            currentProofDomains,
            currentSubdomains,
            {
              requirePreciseProof = true,
              maxPreciseProofAttempts = currentPending.maxPreciseProofAttempts,
              mode = "BACKGROUND",
            }
          )
          return
        end
      end
      local validationState = INTERNAL_API.LIDCOUNCIL_ResolveJoinManifestValidationState_Impl(
        currentPending,
        {
          sessionId = resolvedSessionId,
          profileName = resolvedProfileName,
          memberKey = resolvedMemberKey,
          profileId = TrimText(select(1, deps.GetLootProfileId(resolvedProfileName)) or ""),
          memberProfileId = FirstNonEmptyText(
            type(syncCandidate) == "table" and syncCandidate.profileId or nil,
            type(syncCandidate) == "table" and syncCandidate.remoteProfileId or nil
          ),
        }
      )
      if currentPending.requirePreciseProof == true and type(validationState) ~= "table" then
        profileSyncMetaOps.clearPendingJoinManifestRepair(resolvedSessionId, resolvedMemberKey)
        return
      end
      if currentPending.requirePreciseProof == true then
        local preciseProofReady = INTERNAL_API.LIDCOUNCIL_IsJoinManifestPreciseProofReady_Impl(
          syncCandidate,
          currentPending.token,
          currentProofDomains
        )
        if not preciseProofReady then
          local proofDecision = INTERNAL_API.LIDCOUNCIL_ResolveJoinManifestProofPoll_Impl({
            proofReady = false,
            requestState = type(syncCandidate) == "table" and syncCandidate.preciseRequestState or "",
            completedAttempts = currentPending.preciseProofAttempts,
            maxAttempts = currentPending.maxPreciseProofAttempts,
          })
          currentPending.preciseProofAttempts = proofDecision.attempts
          currentPending.updatedAt = GetProfileCheckpointSyncTime()
          if proofDecision.action == "wait_for_precise_proof" then
            if type(Compat) == "table" and type(Compat.After) == "function" then
              Compat.After(sessionConfig.profileSyncJoinManifestProofPollSeconds, RunDeferredRepair)
            end
            return
          end
          if proofDecision.action == "retry_precise_proof"
            and type(Compat) == "table" and type(Compat.After) == "function"
          then
            if type(profileSyncMetaOps.sendSubchecksumRequests) == "function" then
              profileSyncMetaOps.sendSubchecksumRequests(resolvedMemberKey, currentProofDomains, {
                force = true,
                auto = true,
                requestToken = TrimText(currentPending.token),
              })
            end
            Compat.After(sessionConfig.profileSyncJoinManifestRepairDelaySeconds, RunDeferredRepair)
            return
          end
          profileSyncMetaOps.markJoinManifestProofTerminal(
            currentPending,
            "precise_archive_proof_retry_exhausted"
          )
          profileSyncMetaOps.clearPendingJoinManifestRepair(resolvedSessionId, resolvedMemberKey)
          if type(RecordProfileSyncDecision) == "function" then
            RecordProfileSyncDecision("aligned_replica_archive_repair", {
              action = "precise_proof_timeout",
              sessionId = resolvedSessionId,
              profileName = resolvedProfileName,
              mode = "BACKGROUND",
              reason = "aligned_replica_manifest_required",
              target = resolvedMemberKey,
              targetCount = 1,
              queuedCount = 0,
              requestedDomains = CloneCheckpointDomainList(currentProofDomains),
              requestedSubdomains = CloneCheckpointSubdomainList(currentSubdomains),
              requestedScope = "precise",
              error = "Precise archive proof did not arrive; broad fallback was suppressed.",
            })
          end
          sessionLifecycleOps.emitSyncRuntimeStateNotice(resolvedSessionId, resolvedProfileName, "deferred_join_repair_failed", {
            memberKey = resolvedMemberKey,
            sender = resolvedMemberKey,
            localDomains = currentProofDomains,
            skipIfSame = true,
            refreshEditor = false,
            error = "Precise archive proof did not arrive; broad fallback was suppressed.",
            printWhenChangedOnly = true,
          })
          return
        end
      end
      profileSyncMetaOps.clearPendingJoinManifestRepair(resolvedSessionId, resolvedMemberKey)
      local repairDomains, repairSubdomains = profileSyncMetaOps.buildAutomaticHostRepairScope(
        resolvedMemberKey,
        currentDomains,
        resolvedSessionId,
        syncCandidate
      )
      if #currentSubdomains > 0 then
        local explicitDomainLookup = {}
        local currentPreciseLookupByDomain = {}
        local narrowedDeferredSubdomains = {}
        for _, subdomain in ipairs(repairSubdomains) do
          local resolvedSubdomain = TrimText(subdomain)
          local parentDomain = type(profileSyncMetaOps.getSubdomainParentDomain) == "function"
            and string.lower(TrimText(profileSyncMetaOps.getSubdomainParentDomain(resolvedSubdomain)))
            or ""
          if resolvedSubdomain ~= "" and parentDomain ~= "" then
            currentPreciseLookupByDomain[parentDomain] = currentPreciseLookupByDomain[parentDomain] or {}
            currentPreciseLookupByDomain[parentDomain][string.lower(resolvedSubdomain)] = true
          end
        end
        for _, subdomain in ipairs(currentSubdomains) do
          local resolvedSubdomain = TrimText(subdomain)
          local parentDomain = type(profileSyncMetaOps.getSubdomainParentDomain) == "function"
            and string.lower(TrimText(profileSyncMetaOps.getSubdomainParentDomain(resolvedSubdomain)))
            or ""
          if resolvedSubdomain ~= "" then
            if parentDomain ~= "" then
              explicitDomainLookup[parentDomain] = true
            end
            local domainLookup = parentDomain ~= "" and currentPreciseLookupByDomain[parentDomain] or nil
            if not domainLookup or domainLookup[string.lower(resolvedSubdomain)] then
              narrowedDeferredSubdomains[#narrowedDeferredSubdomains + 1] = resolvedSubdomain
            end
          end
        end
        local retainedCurrentSubdomains = {}
        for _, subdomain in ipairs(repairSubdomains) do
          local parentDomain = type(profileSyncMetaOps.getSubdomainParentDomain) == "function"
            and string.lower(TrimText(profileSyncMetaOps.getSubdomainParentDomain(subdomain)))
            or ""
          if parentDomain == "" or not explicitDomainLookup[parentDomain] then
            retainedCurrentSubdomains[#retainedCurrentSubdomains + 1] = subdomain
          end
        end
        repairDomains = StripBroadDomainsForPreciseSubdomains(repairDomains, currentSubdomains)
        repairSubdomains = MergeCheckpointSubdomainLists(
          retainedCurrentSubdomains,
          narrowedDeferredSubdomains
        )
      end
      if type(profileSyncMetaOps.resolveHostRepairScopeForMember) == "function" then
        local effectiveRepairDomains, effectiveRepairSubdomains = profileSyncMetaOps.resolveHostRepairScopeForMember(
          resolvedMemberKey,
          repairDomains,
          repairSubdomains,
          {
            syncCandidate = syncCandidate,
          }
        )
        repairDomains = CloneCheckpointDomainList(effectiveRepairDomains)
        repairSubdomains = CloneCheckpointSubdomainList(effectiveRepairSubdomains)
      end
      if #repairDomains == 0 and #repairSubdomains == 0 then
        sessionLifecycleOps.emitSyncRuntimeStateNotice(resolvedSessionId, resolvedProfileName, "deferred_join_repair_aligned", {
          memberKey = resolvedMemberKey,
          sender = resolvedMemberKey,
          localDomains = currentDomains,
          skipIfSame = true,
          refreshEditor = false,
          printWhenChangedOnly = true,
        })
        return
      end

      local queuedRepair, queuedRepairCount, repairError, repairDetail = QueueLiveFirstRepairTransfersForMember(activeSession, resolvedProfileName, resolvedSessionId, resolvedMemberKey, {
        mode = "BACKGROUND",
        reason = (#repairSubdomains > 0 and #repairDomains == 0)
          and "join_repair_precise_deferred"
          or (#repairSubdomains > 0 and "join_repair_targeted_deferred" or "join_repair_deferred"),
        domains = repairDomains,
        subdomains = repairSubdomains,
        syncCandidate = syncCandidate,
      })
      local queuedTransfers = math.max(0, tonumber(queuedRepairCount) or 0)
      if queuedRepair and queuedTransfers > 0 then
        sessionLifecycleOps.emitSyncRuntimeStateNotice(resolvedSessionId, resolvedProfileName, "deferred_join_repair_sent", {
          memberKey = resolvedMemberKey,
          sender = resolvedMemberKey,
          localDomains = currentDomains,
          skipIfSame = true,
          refreshEditor = false,
          printWhenChangedOnly = true,
          coalesceWindowSeconds = 2.0,
          coalesceKey = "deferred_join_repair|" .. string.lower(TrimText(resolvedMemberKey)),
          coalesceSignature = "deferred_join_repair_progress",
        })
      elseif queuedRepair and type(repairDetail) == "table" and repairDetail.deferredPatchState == true then
        sessionLifecycleOps.emitSyncRuntimeStateNotice(resolvedSessionId, resolvedProfileName, "deferred_join_repair_waiting", {
          memberKey = resolvedMemberKey,
          sender = resolvedMemberKey,
          localDomains = currentDomains,
          skipIfSame = true,
          refreshEditor = false,
          printWhenChangedOnly = true,
          coalesceWindowSeconds = 2.0,
          coalesceKey = "deferred_join_repair|" .. string.lower(TrimText(resolvedMemberKey)),
          coalesceSignature = "deferred_join_repair_progress",
        })
      elseif queuedRepair and ((type(repairDetail) == "table" and repairDetail.skippedNoOp == true) or queuedTransfers <= 0) then
        sessionLifecycleOps.emitSyncRuntimeStateNotice(resolvedSessionId, resolvedProfileName, "deferred_join_repair_aligned", {
          memberKey = resolvedMemberKey,
          sender = resolvedMemberKey,
          localDomains = currentDomains,
          skipIfSame = true,
          refreshEditor = false,
          printWhenChangedOnly = true,
        })
      elseif repairError then
        sessionLifecycleOps.emitSyncRuntimeStateNotice(resolvedSessionId, resolvedProfileName, "deferred_join_repair_failed", {
          memberKey = resolvedMemberKey,
          sender = resolvedMemberKey,
          localDomains = currentDomains,
          skipIfSame = true,
          refreshEditor = false,
          error = repairError,
          printWhenChangedOnly = true,
        })
      end
    end

    if type(Compat) == "table" and type(Compat.After) == "function" then
      Compat.After(sessionConfig.profileSyncJoinManifestRepairDelaySeconds, RunDeferredRepair)
    else
      RunDeferredRepair()
    end
    return true, "scheduled", token
  end

  local function ScheduleDeferredMissingMemberArchiveScope(profileName, sessionId, memberKey, archiveScope, subdomains)
    local resolvedProfileName = TrimText(profileName)
    local resolvedSessionId = TrimText(sessionId)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    local scopeNames = {
      lootlist = "lootList",
      itemhistory = "itemHistory",
      sessionhistory = "sessionHistory",
      funawards = "funAwards",
    }
    local resolvedScope = scopeNames[string.lower(TrimText(archiveScope))] or ""
    local resolvedSubdomains = CloneCheckpointSubdomainList(subdomains)
    local domainsByScope = {
      lootList = { "loot" },
      itemHistory = { "session" },
      sessionHistory = { "session" },
      funAwards = { "loot" },
    }
    local reasonsByScope = {
      lootList = "missing_member_loot_list_archive_background_deferred",
      itemHistory = "missing_member_item_history_archive_background_deferred",
      sessionHistory = "missing_member_session_history_archive_background_deferred",
      funAwards = "missing_member_fun_awards_archive_background_deferred",
    }
    PruneAgedSessionRuntimeTracking(GetProfileCheckpointSyncTime())
    if resolvedProfileName == "" or resolvedSessionId == "" or resolvedMemberKey == "" or resolvedScope == "" then
      return false, "Missing member history sync target is incomplete."
    end
    if #resolvedSubdomains == 0 and resolvedScope ~= "funAwards" then
      return false, nil
    end

    local timerKey = BuildMissingMemberHistoryTimerKey(resolvedSessionId, resolvedMemberKey)
      .. "|" .. string.lower(resolvedScope)
    local now = GetProfileCheckpointSyncTime()
    local pendingTimerState = sessionRuntime.pendingMissingMemberHistoryTimers[timerKey]
    if type(pendingTimerState) == "table"
      and TrimText(pendingTimerState.profileName) == resolvedProfileName
      and TrimText(pendingTimerState.sessionId) == resolvedSessionId
      and NormalizeCharacterKey(pendingTimerState.memberKey) == resolvedMemberKey
      and TrimText(pendingTimerState.archiveScope) == resolvedScope
      and TrimText(pendingTimerState.token) ~= ""
    then
      pendingTimerState.subdomains = CloneCheckpointSubdomainList(
        MergeCheckpointSubdomainLists(pendingTimerState.subdomains, resolvedSubdomains)
      )
      pendingTimerState.updatedAt = now
      return true, nil
    end

    local token = string.format("MMH-%d-%d", tonumber(time and time() or 0) or 0, math.random(1000, 9999))
    sessionRuntime.pendingMissingMemberHistoryTimers[timerKey] = {
      token = token,
      queuedAt = now,
      updatedAt = now,
      profileName = resolvedProfileName,
      sessionId = resolvedSessionId,
      memberKey = resolvedMemberKey,
      archiveScope = resolvedScope,
      domains = CloneCheckpointDomainList(domainsByScope[resolvedScope]),
      reason = reasonsByScope[resolvedScope],
      subdomains = CloneCheckpointSubdomainList(resolvedSubdomains),
    }

    local function QueueDeferredHistorySubdomains(activeSession, domains, subdomains, reason)
      local authoritativeArchiveScope = resolvedScope == "funAwards" and "FUN_AWARDS" or ""
      if #subdomains == 0 and authoritativeArchiveScope == "" then
        return false, 0, nil
      end
      if type(profileSyncMetaOps.queueMissingMemberBootstrapSnapshotScope) == "function" then
        local queued, queuedCount, queueError = profileSyncMetaOps.queueMissingMemberBootstrapSnapshotScope(
          activeSession,
          resolvedProfileName,
          resolvedSessionId,
          resolvedMemberKey,
          "BACKGROUND",
          reason,
          domains,
          subdomains,
          {
            resolvedSessionId = resolvedSessionId,
            resolvedMemberKey = resolvedMemberKey,
            authoritativeArchiveScope = authoritativeArchiveScope,
          }
        )
        if queued then
          return true, math.max(0, tonumber(queuedCount) or 0), nil
        end
        return false, 0, queueError
      end
      local preparedSnapshot, prepareError = PrepareProfileSnapshotTransfer(resolvedProfileName, {
        domains = domains,
        subdomains = subdomains,
        authoritativeArchiveScope = authoritativeArchiveScope,
      })
      if not preparedSnapshot then
        return false, 0, prepareError
      end
      local queued, queuedCountOrError, queueError = QueueProfileSnapshotForMember(resolvedProfileName, resolvedSessionId, resolvedMemberKey, {
        mode = "BACKGROUND",
        reason = reason,
        domains = domains,
        subdomains = subdomains,
        preparedSnapshot = preparedSnapshot,
        authoritativeArchiveScope = authoritativeArchiveScope,
      })
      if queued then
        return true, math.max(0, tonumber(queuedCountOrError) or 0), nil
      end
      return false, 0, queueError or queuedCountOrError
    end

    local function RunDeferredHistorySync()
      local currentPending = sessionRuntime.pendingMissingMemberHistoryTimers[timerKey]
      if type(currentPending) ~= "table" or TrimText(currentPending.token) ~= token then
        return
      end
      sessionRuntime.pendingMissingMemberHistoryTimers[timerKey] = nil
      local currentDomains = CloneCheckpointDomainList(currentPending.domains)
      local currentSubdomains = CloneCheckpointSubdomainList(currentPending.subdomains)

      local activeSession, activeProfileName = GetActiveLootSession()
      local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
      if not activeSession
        or not DoesActiveSessionMatch(activeSession, activeProfileName, resolvedSessionId, resolvedProfileName)
        or not AreCharacterKeysSame(activeSession.host or "", selfKey)
        or not IsJoinedSessionCharacter(activeSession, resolvedMemberKey)
      then
        return
      end

      if type(profileSyncMetaOps.sendSubchecksumRequests) == "function" then
        profileSyncMetaOps.sendSubchecksumRequests(resolvedMemberKey, currentDomains, {
          force = false,
          auto = true,
        })
      end

      local queuedScope, queuedScopeCount, queueScopeError = QueueDeferredHistorySubdomains(
        activeSession,
        currentDomains,
        currentSubdomains,
        currentPending.reason
      )
      if queuedScope and math.max(0, tonumber(queuedScopeCount) or 0) > 0 then
        Print(
          "Queued the deferred " .. tostring(resolvedScope) .. " sync for " .. tostring(resolvedMemberKey)
          .. " after the live bootstrap finished."
        )
      elseif TrimText(queueScopeError) ~= "" then
        Print(tostring(queueScopeError))
      end
    end

    if type(Compat) == "table" and type(Compat.After) == "function" then
      Compat.After(sessionConfig.profileSyncMissingMemberHistoryDelaySeconds, RunDeferredHistorySync)
    else
      RunDeferredHistorySync()
    end
    return true, nil
  end

  profileSyncMetaOps.scheduleMemberArchiveScopesFromChecksums = function(activeSession, profileName, sessionId, memberKey, member)
    if type(activeSession) ~= "table" or type(member) ~= "table"
      or type(profileSyncMetaOps.buildSessionArchiveScopeChecksums) ~= "function"
    then
      return 0
    end
    local expectedChecksums = profileSyncMetaOps.buildSessionArchiveScopeChecksums(profileName, activeSession)
    local allArchiveScopesAligned = true
    for scopeName, checksumField in pairs({
      lootList = "lootListArchiveChecksum",
      itemHistory = "itemHistoryArchiveChecksum",
      sessionHistory = "sessionHistoryArchiveChecksum",
      funAwards = "funAwardsArchiveChecksum",
    }) do
      local expectedChecksum = TrimText(expectedChecksums[scopeName])
      local memberChecksum = TrimText(member[checksumField])
      if expectedChecksum == ""
        or memberChecksum == ""
        or string.lower(expectedChecksum) ~= string.lower(memberChecksum)
      then
        allArchiveScopesAligned = false
        break
      end
    end
    if allArchiveScopesAligned then
      return 0
    end
    local _, deferredLootSubdomains = profileSyncMetaOps.buildFreshMemberLootSubdomainPlan(profileName, activeSession)
    local deferredSessionSubdomains = profileSyncMetaOps.buildFreshMemberSessionArchiveSubdomains(profileName, sessionId)
    local funAwardsSubdomains, lootListSubdomains = profileSyncMetaOps.splitDeferredMissingMemberLootSubdomains(
      deferredLootSubdomains
    )
    local itemHistorySubdomains, sessionHistorySubdomains = profileSyncMetaOps.splitDeferredMissingMemberSessionSubdomains(
      deferredSessionSubdomains
    )
    local scopeDefinitions = {
      {
        scope = "lootList",
        checksumField = "lootListArchiveChecksum",
        subdomains = lootListSubdomains,
      },
      {
        scope = "itemHistory",
        checksumField = "itemHistoryArchiveChecksum",
        subdomains = itemHistorySubdomains,
      },
      {
        scope = "sessionHistory",
        checksumField = "sessionHistoryArchiveChecksum",
        subdomains = sessionHistorySubdomains,
      },
      {
        scope = "funAwards",
        checksumField = "funAwardsArchiveChecksum",
        subdomains = funAwardsSubdomains,
      },
    }
    local scheduled = 0
    local localProfileId = TrimText(select(1, deps.GetLootProfileId(profileName)) or "")
    local memberProfileId = FirstNonEmptyText(member.sharedProfileId, member.profileId)
    local existingReplicaJoinKey = string.lower(NormalizeCharacterKey(memberKey))
    local existingReplica = TrimText(sessionRuntime.existingReplicaJoinSessionId) == TrimText(sessionId)
      and type(sessionRuntime.existingReplicaJoinByMember) == "table"
      and sessionRuntime.existingReplicaJoinByMember[existingReplicaJoinKey] == true
    local matchingProfileIdentity = localProfileId ~= ""
      and memberProfileId ~= ""
      and string.lower(localProfileId) == string.lower(memberProfileId)
    local routeScopes = {}
    for _, definition in ipairs(scopeDefinitions) do
      local expectedChecksum = TrimText(expectedChecksums[definition.scope])
      local memberChecksum = TrimText(member[definition.checksumField])
      local transaction = type(member.p3ArchiveTransactions) == "table"
        and member.p3ArchiveTransactions[definition.scope]
        or nil
      local transactionState = string.lower(TrimText(type(transaction) == "table" and transaction.state or ""))
      local sameExpectedTransaction = type(transaction) == "table"
        and expectedChecksum ~= ""
        and expectedChecksum == TrimText(transaction.expectedChecksum)
      local attemptLimitReached = sameExpectedTransaction
        and transactionState ~= "checksum_confirmed"
        and math.max(0, tonumber(transaction.attempts) or 0) >= math.max(1, tonumber(transaction.maxAttempts) or 3)
      local transactionPending = sameExpectedTransaction
        and (transactionState == "queued"
          or transactionState == "sending"
          or transactionState == "receiver_queued"
          or transactionState == "retrying")
      local handledLatestHistoryCatchup = false
      if definition.scope == "sessionHistory"
        and existingReplica
        and matchingProfileIdentity
        and expectedChecksum ~= ""
        and memberChecksum ~= ""
        and string.lower(expectedChecksum) ~= string.lower(memberChecksum)
        and type(profileSyncMetaOps.queueLatestSessionHistoryCatchup) == "function"
      then
        local handled, queuedCount = profileSyncMetaOps.queueLatestSessionHistoryCatchup(
          activeSession,
          profileName,
          sessionId,
          memberKey,
          member,
          "latest_session_history_join_catchup"
        )
        handledLatestHistoryCatchup = handled == true
        if math.max(0, tonumber(queuedCount) or 0) > 0 then
          scheduled = scheduled + 1
        end
      end
      routeScopes[#routeScopes + 1] = {
        scope = definition.scope,
        memberChecksum = memberChecksum,
        needsRepair = expectedChecksum ~= "" and expectedChecksum ~= memberChecksum
        and (#definition.subdomains > 0 or definition.scope == "funAwards")
        and not transactionPending and not attemptLimitReached
        and not (sameExpectedTransaction and transactionState == "failed"),
        latestHistoryCatchupHandled = handledLatestHistoryCatchup,
      }
      if handledLatestHistoryCatchup then
        routeScopes[#routeScopes].needsRepair = false
      end
    end
    local routePlan = INTERNAL_API.LIDCOUNCIL_BuildAlignedReplicaArchivePlan_Impl({
      existingReplica = existingReplica,
      localProfileId = localProfileId,
      memberProfileId = memberProfileId,
      scopes = routeScopes,
    })
    if routePlan.canReuseExistingReplica ~= true then
      local broadScopeLookup = {}
      for _, scope in ipairs(routePlan.broadArchiveScopes) do
        broadScopeLookup[scope] = true
      end
      for _, definition in ipairs(scopeDefinitions) do
        if broadScopeLookup[definition.scope] then
          local scopeScheduled = ScheduleDeferredMissingMemberArchiveScope(
            profileName,
            sessionId,
            memberKey,
            definition.scope,
            definition.subdomains
          )
          if scopeScheduled then
            scheduled = scheduled + 1
          end
        end
      end
    end
    if #routePlan.preciseDomains > 0 then
      local preciseRepairScheduled, preciseRepairScheduleReason = ScheduleDeferredJoinManifestRepair(
        profileName,
        sessionId,
        memberKey,
        routePlan.preciseDomains,
        nil,
        {
          requirePreciseProof = true,
          maxPreciseProofAttempts = 4,
        }
      )
      if preciseRepairScheduled then
        scheduled = scheduled + 1
      end
      if type(RecordProfileSyncDecision) == "function" then
        RecordProfileSyncDecision("aligned_replica_archive_repair", {
          action = preciseRepairScheduled and "manifest_requested"
            or (preciseRepairScheduleReason == "precise_proof_terminal_cooldown"
              and "manifest_terminal_suppressed"
              or "manifest_request_failed"),
          sessionId = TrimText(sessionId),
          profileName = TrimText(profileName),
          mode = "BACKGROUND",
          reason = "aligned_replica_manifest_required",
          target = NormalizeCharacterKey(memberKey),
          targetCount = 1,
          queuedCount = 0,
          requestedDomains = CloneCheckpointDomainList(routePlan.preciseDomains),
          requestedSubdomains = {},
          requestedScope = "precise",
          error = preciseRepairScheduled and "" or TrimText(preciseRepairScheduleReason),
        })
      end
    end
    return scheduled
  end

  MergeCheckpointSubdomainLists = function(...)
    local merged = {}
    local seen = {}
    for index = 1, select("#", ...) do
      for _, subdomain in ipairs(type(select(index, ...)) == "table" and select(index, ...) or {}) do
        local value = TrimText(subdomain)
        local seenKey = string.lower(value)
        if value ~= "" and not seen[seenKey] then
          seen[seenKey] = true
          merged[#merged + 1] = value
        end
      end
    end
    return merged
  end

  local function BuildProfileCheckpointStateKey(sessionId, profileName)
    return string.lower(TrimText(sessionId)) .. "|" .. string.lower(TrimText(profileName))
  end

  local function CollectLiveSyncTargets(activeSession, selfKey, targetMemberKey)
    local targets = {}
    local seenTargets = {}
    local function AddLiveSyncTarget(characterKey)
      local resolvedKey = NormalizeCharacterKey(characterKey)
      local targetIndexKey = string.lower(resolvedKey)
      if resolvedKey ~= "" and not seenTargets[targetIndexKey] and not AreCharacterKeysSame(resolvedKey, selfKey) and IsJoinedSessionCharacter(activeSession, resolvedKey) then
        targets[#targets + 1] = resolvedKey
        seenTargets[targetIndexKey] = true
      end
    end

    local requestedTarget = NormalizeCharacterKey(targetMemberKey)
    if requestedTarget ~= "" then
      AddLiveSyncTarget(requestedTarget)
    else
      AddLiveSyncTarget(activeSession.host)
      for memberKey, member in pairs(activeSession.members or {}) do
        if type(member) == "table" and tostring(member.status or "JOINED") == "JOINED" then
          AddLiveSyncTarget(memberKey)
        end
      end
      table.sort(targets)
    end
    return targets
  end

  local function BuildLiveSyncTargetSignature(activeSession, selfKey, targetMemberKey)
    local targets = CollectLiveSyncTargets(activeSession, selfKey, targetMemberKey)
    if #targets == 0 then
      return ""
    end
    for index, value in ipairs(targets) do
      targets[index] = string.lower(TrimText(value))
    end
    return table.concat(targets, "\30")
  end

  local function BuildProfileCheckpointRowSignatureDigest(rowSignaturesBySubdomain)
    rowSignaturesBySubdomain = type(rowSignaturesBySubdomain) == "table" and rowSignaturesBySubdomain or {}
    local orderedSubdomains = {}
    for subdomain, rowSignatures in pairs(rowSignaturesBySubdomain) do
      if TrimText(subdomain) ~= "" and type(rowSignatures) == "table" then
        orderedSubdomains[#orderedSubdomains + 1] = TrimText(subdomain)
      end
    end
    table.sort(orderedSubdomains, function(left, right)
      return string.lower(left) < string.lower(right)
    end)
    local digestParts = {}
    for _, subdomain in ipairs(orderedSubdomains) do
      local orderedRowIds = {}
      local rowSignatures = rowSignaturesBySubdomain[subdomain]
      for rowId in pairs(type(rowSignatures) == "table" and rowSignatures or {}) do
        local resolvedRowId = tostring(rowId or "")
        if resolvedRowId ~= "" then
          orderedRowIds[#orderedRowIds + 1] = resolvedRowId
        end
      end
      table.sort(orderedRowIds)
      for _, rowId in ipairs(orderedRowIds) do
        digestParts[#digestParts + 1] = table.concat({
          string.lower(subdomain),
          rowId,
          tostring(type(rowSignatures) == "table" and rowSignatures[rowId] or ""),
        }, "\30")
      end
    end
    return table.concat(digestParts, "\31")
  end

  local function BuildProfileCheckpointRequestSignature(pendingState)
    pendingState = type(pendingState) == "table" and pendingState or {}
    local domains = CloneCheckpointDomainList(pendingState.domains)
    local subdomains = CloneCheckpointSubdomainList(pendingState.subdomains)
    table.sort(domains, function(left, right)
      return string.lower(TrimText(left)) < string.lower(TrimText(right))
    end)
    table.sort(subdomains, function(left, right)
      return string.lower(TrimText(left)) < string.lower(TrimText(right))
    end)
    return table.concat({
      table.concat(domains, "\30"),
      table.concat(subdomains, "\30"),
      BuildProfileCheckpointRowSignatureDigest(pendingState.prebuiltRowSignaturesBySubdomain),
    }, "\31")
  end

  local function BuildProfileCheckpointTransportSignature(activeSession, selfKey, pendingState)
    local requestSignature = BuildProfileCheckpointRequestSignature(pendingState)
    local targetSignature = BuildLiveSyncTargetSignature(activeSession, selfKey, nil)
    return table.concat({
      requestSignature,
      targetSignature,
    }, "\31"), requestSignature, targetSignature
  end

  local function SendActiveProfileCheckpointNow(profileName, pendingState)
    pendingState = type(pendingState) == "table" and pendingState or {}
    local activeSession, activeProfileName = GetActiveLootSession()
    if not activeSession or not activeProfileName then
      return false, "No active session."
    end

    local requestedProfileName = TrimText(profileName)
    if requestedProfileName ~= "" and not DoesActiveSessionMatch(activeSession, activeProfileName, activeSession.id, requestedProfileName) then
      return false, "No matching active session profile."
    end

    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if selfKey == "" or not AreCharacterKeysSame(activeSession.host or "", selfKey) or not IsJoinedSessionCharacter(activeSession, selfKey) then
      return false, "Only the joined session host can send live profile checkpoints."
    end

    local requestedDomains = CloneCheckpointDomainList(pendingState.domains)
    local requestedSubdomains = CloneCheckpointSubdomainList(pendingState.subdomains)
    if #requestedDomains == 0 and #requestedSubdomains == 0 then
      return false, "No checkpoint scope requested."
    end

    local prebuiltRowsBySubdomain = type(pendingState.prebuiltRowsBySubdomain) == "table" and pendingState.prebuiltRowsBySubdomain or nil
    local targets = CollectLiveSyncTargets(activeSession, selfKey, nil)
    if #targets == 0 then
      return false, "No joined session members."
    end

    local checkpointReason = TrimText(pendingState.reason) ~= "" and TrimText(pendingState.reason) or "checkpoint"
    local checkpointRepairSyncCandidateSnapshot = BuildActiveSyncCandidateSnapshot()
    local checkpointRepairDisplayBaseContext = INTERNAL_API.LIDCOUNCIL_BuildHostCurrentSessionDisplayContext(
      activeSession,
      activeProfileName,
      nil,
      {
        syncCandidateSnapshot = checkpointRepairSyncCandidateSnapshot,
      }
    )
    local checkpointCurrentSectionProbe = INTERNAL_API.LIDCOUNCIL_BuildHostCurrentSectionDisplayProbe(
      activeSession,
      activeProfileName,
      {
        hostCurrentSessionDisplayBaseContext = checkpointRepairDisplayBaseContext,
        syncCandidateSnapshot = checkpointRepairSyncCandidateSnapshot,
      }
    )
    local sentCount = 0
    local repairMetricsState = sessionLifecycleOps.createRepairMetricsState()
    local lastQueueError = nil
    local repairRefreshState = {}
    local function RecordCheckpointRepairOutcome(memberKey, queuedCount, repairDetail, repairError, outcomeOpts)
      local _, _, persistResult = profileSyncMetaOps.persistDisplayedSessionMemberRepairOutcome(
        activeSession,
        activeProfileName,
        activeSession.id,
        memberKey,
        queuedCount,
        repairDetail,
        repairError,
        {
          sourceLabel = "checkpoint repair",
          currentSessionDisplayBaseContext = checkpointRepairDisplayBaseContext,
          syncCandidateSnapshot = checkpointRepairSyncCandidateSnapshot,
          rowPatchTransfers = type(outcomeOpts) == "table" and outcomeOpts.rowPatchTransfers or nil,
          requestedDomains = type(outcomeOpts) == "table" and outcomeOpts.requestedDomains or nil,
          requestedSubdomains = type(outcomeOpts) == "table" and outcomeOpts.requestedSubdomains or nil,
          refreshEditor = false,
        }
      )
      repairRefreshState = sessionUiOps.mergeRepairOutcomePersistResult(repairRefreshState, persistResult)
    end
    local rowPatchSubdomains = {}
    local rowPatchLookup = {}
    if type(prebuiltRowsBySubdomain) == "table" and #requestedSubdomains > 0 and type(PrepareProfileSnapshotTransfer) == "function" then
      local subdomainLookup = {}
      for _, subdomain in ipairs(requestedSubdomains) do
        subdomainLookup[string.lower(TrimText(subdomain))] = true
      end
      for subdomain, rows in pairs(prebuiltRowsBySubdomain) do
        if subdomainLookup[string.lower(TrimText(subdomain))] and type(rows) == "table" and #rows > 0 then
          local resolvedSubdomain = TrimText(subdomain)
          rowPatchSubdomains[#rowPatchSubdomains + 1] = resolvedSubdomain
          rowPatchLookup[string.lower(resolvedSubdomain)] = true
        end
      end
      table.sort(rowPatchSubdomains)
    end
    local targetPlans = {}
    local rowPatchGroups = {}
    for _, memberKey in ipairs(targets) do
      local effectiveDomains, effectiveSubdomains, scopeDetail = profileSyncMetaOps.resolveHostRepairScopeForMember(
        memberKey,
        requestedDomains,
        requestedSubdomains,
        {}
      )
      if type(scopeDetail) == "table" and scopeDetail.skippedNoOp == true then
        local prepareDetail = {
          repairMode = ClassifyRequestedRepairScope(requestedDomains, requestedSubdomains, "targeted"),
          requestedScope = ClassifyRequestedRepairScope(requestedDomains, requestedSubdomains, "targeted"),
          requestedDomains = CloneCheckpointDomainList(requestedDomains),
          requestedSubdomains = CloneCheckpointSubdomainList(requestedSubdomains),
          skippedNoOp = true,
        }
        sessionLifecycleOps.accumulateSkippedRepairMetrics(repairMetricsState, prepareDetail)
        RecordCheckpointRepairOutcome(memberKey, 0, prepareDetail, nil)
      else
        local rowScopedSubdomains = {}
        local remainingSubdomains = {}
        if #rowPatchSubdomains > 0 then
          for _, subdomain in ipairs(effectiveSubdomains) do
            local resolvedSubdomain = TrimText(subdomain)
            local compareKey = string.lower(resolvedSubdomain)
            if compareKey ~= "" and rowPatchLookup[compareKey] then
              rowScopedSubdomains[#rowScopedSubdomains + 1] = resolvedSubdomain
            elseif compareKey ~= "" then
              remainingSubdomains[#remainingSubdomains + 1] = resolvedSubdomain
            end
          end
          rowScopedSubdomains = CloneCheckpointSubdomainList(rowScopedSubdomains)
          remainingSubdomains = CloneCheckpointSubdomainList(remainingSubdomains)
        else
          remainingSubdomains = CloneCheckpointSubdomainList(effectiveSubdomains)
        end
        targetPlans[memberKey] = {
          domains = CloneCheckpointDomainList(effectiveDomains),
          subdomains = remainingSubdomains,
        }
        if #rowScopedSubdomains > 0 then
          local normalizedScope = CloneCheckpointSubdomainList(rowScopedSubdomains)
          table.sort(normalizedScope, function(left, right)
            return string.lower(TrimText(left)) < string.lower(TrimText(right))
          end)
          local scopeKey = table.concat(normalizedScope, "|")
          local group = rowPatchGroups[scopeKey]
          if type(group) ~= "table" then
            group = {
              targets = {},
              subdomains = CloneCheckpointSubdomainList(rowScopedSubdomains),
            }
            rowPatchGroups[scopeKey] = group
          end
          group.targets[#group.targets + 1] = memberKey
        end
      end
    end

    for _, group in pairs(rowPatchGroups) do
      local preparedRowPatch, prepareError = PrepareProfileSnapshotTransfer(activeProfileName, {
        domains = #requestedDomains > 0 and requestedDomains or nil,
        subdomains = group.subdomains,
        prebuiltRowsBySubdomain = prebuiltRowsBySubdomain,
        })
      if type(preparedRowPatch) == "table" and TrimText(preparedRowPatch.transferKind) == "ROWPATCHES" then
        local ok, queuedCountOrError, queueBatchDetail = deps.SendPreparedProfileSnapshotBatch(preparedRowPatch, activeSession.id, group.targets, {
          mode = "LIVE",
          reason = checkpointReason,
        })
        if ok then
          local queuedMembers = math.max(0, tonumber(queuedCountOrError) or #group.targets)
          sentCount = sentCount + queuedMembers
          sessionLifecycleOps.accumulateQueuedRowPatchMetrics(repairMetricsState, queuedMembers, group.subdomains, {
            memberCount = queuedMembers,
            mergedCount = type(queueBatchDetail) == "table" and queueBatchDetail.mergedCount or 0,
            exactDuplicateCount = type(queueBatchDetail) == "table" and queueBatchDetail.exactDuplicateCount or 0,
          })
          for _, memberKey in ipairs(group.targets) do
            RecordCheckpointRepairOutcome(memberKey, 1, {
              repairMode = #group.subdomains > 0 and "precise" or (#requestedDomains > 0 and "targeted" or "full"),
              requestedScope = #group.subdomains > 0 and "precise" or (#requestedDomains > 0 and "targeted" or "full"),
              requestedDomains = CloneCheckpointDomainList(requestedDomains),
              requestedSubdomains = CloneCheckpointSubdomainList(group.subdomains),
            }, nil, {
              rowPatchTransfers = 1,
              requestedDomains = requestedDomains,
              requestedSubdomains = group.subdomains,
            })
          end
        else
          if TrimText(queuedCountOrError) ~= "" then
            lastQueueError = queuedCountOrError
          end
          for _, memberKey in ipairs(group.targets) do
            local plan = type(targetPlans[memberKey]) == "table" and targetPlans[memberKey] or {
              domains = {},
              subdomains = {},
            }
            plan.subdomains = MergeCheckpointSubdomainLists(plan.subdomains, group.subdomains)
            targetPlans[memberKey] = plan
          end
        end
      else
        if TrimText(prepareError) ~= "" then
          lastQueueError = prepareError
        end
        for _, memberKey in ipairs(group.targets) do
          local plan = type(targetPlans[memberKey]) == "table" and targetPlans[memberKey] or {
            domains = {},
            subdomains = {},
          }
          plan.subdomains = MergeCheckpointSubdomainLists(plan.subdomains, group.subdomains)
          targetPlans[memberKey] = plan
        end
      end
    end

    local plannedTargets = {}
    for memberKey, plan in pairs(targetPlans) do
      if type(plan) == "table" and (#(plan.domains or {}) > 0 or #(plan.subdomains or {}) > 0) then
        plannedTargets[#plannedTargets + 1] = memberKey
      end
    end
    table.sort(plannedTargets)

    local fallbackPlannedTargets = {}
    local fallbackPlannedLookup = {}
    local function AddFallbackPlannedTarget(memberKey)
      local resolvedMemberKey = NormalizeCharacterKey(memberKey)
      local compareKey = string.lower(resolvedMemberKey)
      if resolvedMemberKey ~= "" and not fallbackPlannedLookup[compareKey] then
        fallbackPlannedLookup[compareKey] = true
        fallbackPlannedTargets[#fallbackPlannedTargets + 1] = resolvedMemberKey
      end
    end

    local preparedPlanGroups = {}
    local preparedPlanGroupKeys = {}
    for _, memberKey in ipairs(plannedTargets) do
      local plan = targetPlans[memberKey]
      local preparedTransfers = nil
      local prepareError = nil
      local prepareDetail = nil
      if type(BuildPreparedProfileRepairTransfers) == "function" then
        preparedTransfers, prepareError, prepareDetail = BuildPreparedProfileRepairTransfers(
          activeProfileName,
          activeSession.id,
          memberKey,
          {
            mode = "LIVE",
            reason = checkpointReason,
            domains = plan.domains,
            subdomains = plan.subdomains,
          }
        )
        prepareDetail = profileSyncMetaOps.applyPreparedRepairScopeToDetail(
          prepareDetail,
          plan.domains,
          plan.subdomains,
          plan.domains,
          plan.subdomains
        )
        if type(preparedTransfers) == "table" and #preparedTransfers > 0 then
          preparedTransfers, _, prepareDetail = profileSyncMetaOps.dedupePreparedRepairTransfers(preparedTransfers, prepareDetail)
        end
      end

      if type(preparedTransfers) ~= "table"
        or #preparedTransfers == 0
        or profileSyncMetaOps.shouldRetryPreparedRepairForPatchState(prepareDetail)
      then
        AddFallbackPlannedTarget(memberKey)
      else
        local groupSignature = table.concat({
          profileSyncMetaOps.buildPreparedRepairTransferBatchSignature(preparedTransfers),
          profileSyncMetaOps.buildRepairQueueStepSignature({
            mode = "LIVE",
            reason = checkpointReason,
            domains = plan.domains,
            subdomains = plan.subdomains,
            skipScopePrune = true,
          }),
        }, "\31")
        if groupSignature == "" then
          AddFallbackPlannedTarget(memberKey)
        else
          local group = preparedPlanGroups[groupSignature]
          if type(group) ~= "table" then
            group = {
              targets = {},
              preparedTransfers = preparedTransfers,
              prepareDetail = prepareDetail,
              domains = CloneCheckpointDomainList(plan.domains),
              subdomains = CloneCheckpointSubdomainList(plan.subdomains),
            }
            preparedPlanGroups[groupSignature] = group
            preparedPlanGroupKeys[#preparedPlanGroupKeys + 1] = groupSignature
          end
          group.targets[#group.targets + 1] = memberKey
        end
      end
    end

    table.sort(preparedPlanGroupKeys)
    for _, groupKey in ipairs(preparedPlanGroupKeys) do
      local group = preparedPlanGroups[groupKey]
      local groupTargets = type(group) == "table" and type(group.targets) == "table" and group.targets or {}
      table.sort(groupTargets)

      local perMemberQueuedCounts = {}
      local perMemberErrors = {}
      local queuedAny = false
      for _, preparedTransfer in ipairs(type(group) == "table" and type(group.preparedTransfers) == "table" and group.preparedTransfers or {}) do
        if #groupTargets > 1 and type(deps.SendPreparedProfileSnapshotBatch) == "function" then
          local ok, queuedCountOrError, queueBatchDetail = deps.SendPreparedProfileSnapshotBatch(preparedTransfer, activeSession.id, groupTargets, {
            mode = "LIVE",
            reason = checkpointReason,
            domains = type(group) == "table" and group.domains or nil,
            subdomains = type(group) == "table" and group.subdomains or nil,
            preparedSnapshot = preparedTransfer,
          })
          if ok then
            queuedAny = true
            sessionLifecycleOps.accumulateOutboundQueueMetrics(repairMetricsState, queueBatchDetail)
            for _, targetMemberKey in ipairs(groupTargets) do
              local targetIndexKey = string.lower(TrimText(targetMemberKey))
              perMemberQueuedCounts[targetIndexKey] = math.max(0, tonumber(perMemberQueuedCounts[targetIndexKey]) or 0) + 1
            end
          elseif TrimText(queuedCountOrError) ~= "" then
            lastQueueError = TrimText(queuedCountOrError)
            for _, targetMemberKey in ipairs(groupTargets) do
              perMemberErrors[string.lower(TrimText(targetMemberKey))] = TrimText(queuedCountOrError)
            end
          end
        else
          for _, targetMemberKey in ipairs(groupTargets) do
            local ok, queuedCountOrError, queueBatchDetail = QueueProfileSnapshotForMember(
              activeProfileName,
              activeSession.id,
              targetMemberKey,
              {
                mode = "LIVE",
                reason = checkpointReason,
                domains = type(group) == "table" and group.domains or nil,
                subdomains = type(group) == "table" and group.subdomains or nil,
                preparedSnapshot = preparedTransfer,
              }
            )
            local targetIndexKey = string.lower(TrimText(targetMemberKey))
            if ok then
              queuedAny = true
              sessionLifecycleOps.accumulateOutboundQueueMetrics(repairMetricsState, queueBatchDetail)
              perMemberQueuedCounts[targetIndexKey] = math.max(0, tonumber(perMemberQueuedCounts[targetIndexKey]) or 0)
                + math.max(1, tonumber(queuedCountOrError) or 1)
            elseif TrimText(queuedCountOrError) ~= "" then
              lastQueueError = TrimText(queuedCountOrError)
              perMemberErrors[targetIndexKey] = TrimText(queuedCountOrError)
            end
          end
        end
      end

      if queuedAny then
        local batchedQueuedCount = 0
        for _, targetMemberKey in ipairs(groupTargets) do
          batchedQueuedCount = batchedQueuedCount + math.max(
            0,
            tonumber(perMemberQueuedCounts[string.lower(TrimText(targetMemberKey))]) or 0
          )
        end
        if #groupTargets > 1 and type(RecordProfileSyncDecision) == "function" then
          RecordProfileSyncDecision("queue_checkpoint_prepared_group", {
            action = "queued_batched_group",
            sessionId = activeSession.id,
            profileName = activeProfileName,
            mode = "LIVE",
            reason = checkpointReason,
            targetCount = #groupTargets,
            queuedCount = batchedQueuedCount,
            transferCount = #(type(group) == "table" and type(group.preparedTransfers) == "table" and group.preparedTransfers or {}),
            duplicatePreparedTransfers = math.max(0, tonumber(
              type(group) == "table" and type(group.prepareDetail) == "table" and group.prepareDetail.duplicatePreparedTransfers or 0
            ) or 0),
            transferKinds = CloneDecisionTextList(
              type(group) == "table" and type(group.prepareDetail) == "table" and group.prepareDetail.transferKinds or {}
            ),
            requestedDomains = CloneCheckpointDomainList(type(group) == "table" and group.domains or {}),
            requestedSubdomains = CloneCheckpointSubdomainList(type(group) == "table" and group.subdomains or {}),
          })
        end
        for _, targetMemberKey in ipairs(groupTargets) do
          local queuedRepairCount = math.max(
            0,
            tonumber(perMemberQueuedCounts[string.lower(TrimText(targetMemberKey))]) or 0
          )
          if queuedRepairCount > 0 then
            sentCount = sentCount + queuedRepairCount
            sessionLifecycleOps.accumulateQueuedRepairMetrics(
              repairMetricsState,
              queuedRepairCount,
              type(group) == "table" and group.prepareDetail or nil
            )
            RecordCheckpointRepairOutcome(targetMemberKey, queuedRepairCount, type(group) == "table" and group.prepareDetail or nil, nil, {
              requestedDomains = type(group) == "table" and group.domains or nil,
              requestedSubdomains = type(group) == "table" and group.subdomains or nil,
            })
          elseif TrimText(perMemberErrors[string.lower(TrimText(targetMemberKey))]) ~= "" then
            RecordCheckpointRepairOutcome(
              targetMemberKey,
              0,
              type(group) == "table" and group.prepareDetail or {
                repairMode = ClassifyRequestedRepairScope(
                  type(group) == "table" and group.domains or {},
                  type(group) == "table" and group.subdomains or {},
                  "targeted"
                ),
                requestedScope = ClassifyRequestedRepairScope(
                  type(group) == "table" and group.domains or {},
                  type(group) == "table" and group.subdomains or {},
                  "targeted"
                ),
                requestedDomains = CloneCheckpointDomainList(type(group) == "table" and group.domains or {}),
                requestedSubdomains = CloneCheckpointSubdomainList(type(group) == "table" and group.subdomains or {}),
              },
              perMemberErrors[string.lower(TrimText(targetMemberKey))],
              {
                requestedDomains = type(group) == "table" and group.domains or nil,
                requestedSubdomains = type(group) == "table" and group.subdomains or nil,
              }
            )
          else
            AddFallbackPlannedTarget(targetMemberKey)
          end
        end
      else
        for _, targetMemberKey in ipairs(groupTargets) do
          AddFallbackPlannedTarget(targetMemberKey)
        end
      end
    end

    table.sort(fallbackPlannedTargets)
    for _, memberKey in ipairs(fallbackPlannedTargets) do
      local plan = targetPlans[memberKey]
      local queuedRepair, queuedCount, queueError, prepareDetail = QueuePreparedRepairTransfersForMember(
        activeProfileName,
        activeSession.id,
        memberKey,
        {
          mode = "LIVE",
          reason = checkpointReason,
          domains = plan.domains,
          subdomains = plan.subdomains,
          skipScopePrune = true,
        }
      )
      if queuedRepair then
        local queuedRepairCount = math.max(0, tonumber(queuedCount) or 0)
        if queuedRepairCount > 0 then
          sentCount = sentCount + queuedRepairCount
          sessionLifecycleOps.accumulateQueuedRepairMetrics(repairMetricsState, queuedRepairCount, prepareDetail)
        else
          sessionLifecycleOps.accumulateSkippedRepairMetrics(repairMetricsState, prepareDetail)
        end
        RecordCheckpointRepairOutcome(memberKey, queuedRepairCount, prepareDetail, nil, {
          requestedDomains = plan.domains,
          requestedSubdomains = plan.subdomains,
        })
      elseif TrimText(queueError) ~= "" then
        lastQueueError = queueError
        RecordCheckpointRepairOutcome(memberKey, 0, type(prepareDetail) == "table" and prepareDetail or {
          repairMode = ClassifyRequestedRepairScope(plan.domains, plan.subdomains, "targeted"),
          requestedScope = ClassifyRequestedRepairScope(plan.domains, plan.subdomains, "targeted"),
          requestedDomains = CloneCheckpointDomainList(plan.domains),
          requestedSubdomains = CloneCheckpointSubdomainList(plan.subdomains),
        }, queueError, {
          requestedDomains = plan.domains,
          requestedSubdomains = plan.subdomains,
        })
      end
    end

    sessionUiOps.applyRepairOutcomeRefreshState(repairRefreshState, {
      activeSession = activeSession,
      profileName = activeProfileName,
      previousHostCurrentSectionProbe = checkpointCurrentSectionProbe,
      hostCurrentSessionDisplayBaseContext = checkpointRepairDisplayBaseContext,
      syncCandidateSnapshot = checkpointRepairSyncCandidateSnapshot,
      fallbackScope = "CURRENT",
    })

    if sentCount > 0 or repairMetricsState.deferredPatchStateCount > 0 then
      local scopeCount = (#requestedSubdomains > 0 and #requestedSubdomains or #requestedDomains)
      local scopeLabel = #requestedSubdomains > 0 and "scope" or "domain"
      local checkpointMessage = sessionLifecycleOps.buildCheckpointRepairDispatchMessage(sentCount, repairMetricsState, {
        scopeCount = scopeCount,
        scopeLabel = scopeLabel,
        includeRowPatchTransfers = true,
        includeSnapshotTransfers = true,
        includeSkippedAligned = true,
      })
      sessionLifecycleOps.emitRepairRuntimeState(activeSession.id, activeProfileName, "live_checkpoint", sentCount > 0 and "success" or "info",
        checkpointMessage, {
          sender = selfKey,
          printNotice = false,
        })
      return true, sentCount
    end

    if repairMetricsState.skippedAlignedCount > 0 and TrimText(lastQueueError) == "" then
      sessionLifecycleOps.emitRepairRuntimeState(activeSession.id, activeProfileName, "live_checkpoint", "info",
        "Skipped a live checkpoint send because the requested scope was already aligned for "
          .. sessionLifecycleOps.buildJoinedMemberCountLabel(repairMetricsState.skippedAlignedCount) .. ".", {
          sender = selfKey,
          printNotice = false,
        })
      return true, 0
    end
    return false, lastQueueError or "No live checkpoint transfer was queued."
  end

  local function FlushQueuedProfileCheckpointSync(stateKey, expectedTimerToken)
    local resolvedKey = TrimText(stateKey)
    if resolvedKey == "" then
      return
    end
    PruneAgedSessionRuntimeTracking(GetProfileCheckpointSyncTime())
    local timerState = sessionRuntime.pendingProfileCheckpointTimers[resolvedKey]
    if expectedTimerToken ~= nil and (type(timerState) ~= "table"
      or math.max(0, tonumber(timerState.token) or 0) ~= math.max(0, tonumber(expectedTimerToken) or 0))
    then
      return
    end
    local pending = sessionRuntime.pendingProfileCheckpointSyncs[resolvedKey]
    sessionRuntime.pendingProfileCheckpointSyncs[resolvedKey] = nil
    sessionRuntime.pendingProfileCheckpointTimers[resolvedKey] = nil
    if type(pending) ~= "table" then
      return
    end
    local sentAt = GetProfileCheckpointSyncTime()
    sessionRuntime.lastProfileCheckpointSyncAt[resolvedKey] = sentAt
    local activeSession, activeProfileName = GetActiveLootSession()
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    local checkpointTransportSignature = TrimText(type(pending) == "table" and pending.__checkpointTransportSignature or "")
    if checkpointTransportSignature == ""
      and type(activeSession) == "table"
      and TrimText(activeSession.id) == TrimText(type(pending) == "table" and pending.sessionId or "")
      and DoesActiveSessionMatch(activeSession, activeProfileName, activeSession.id, pending.profileName)
    then
      checkpointTransportSignature = select(1, BuildProfileCheckpointTransportSignature(activeSession, selfKey, pending))
    end
    local queued, _ = SendActiveProfileCheckpointNow(pending.profileName, pending)
    if queued and checkpointTransportSignature ~= "" then
      sessionRuntime.recentProfileCheckpointRequestStates[resolvedKey] = {
        transportSignature = checkpointTransportSignature,
        sentAt = sentAt,
      }
    end
  end

  INTERNAL_API.LIDCOUNCIL_QueueActiveProfileCheckpointFlow_Impl = function(profileName, opts)
    opts = type(opts) == "table" and opts or {}
    local activeSession, activeProfileName = GetActiveLootSession()
    if not activeSession or not activeProfileName then
      return false, "No active session."
    end

    local requestedProfileName = TrimText(profileName)
    if requestedProfileName ~= "" and not DoesActiveSessionMatch(activeSession, activeProfileName, activeSession.id, requestedProfileName) then
      return false, "No matching active session profile."
    end

    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if selfKey == "" or not AreCharacterKeysSame(activeSession.host or "", selfKey) or not IsJoinedSessionCharacter(activeSession, selfKey) then
      return false, "Only the joined session host can queue live checkpoints."
    end

    local now = GetProfileCheckpointSyncTime()
    PruneAgedSessionRuntimeTracking(now)

    local domains = CloneCheckpointDomainList(opts.domains)
    local subdomains = CloneCheckpointSubdomainList(opts.subdomains)
    if #domains == 0 and #subdomains == 0 then
      return false, "No checkpoint scope requested."
    end

    local stateKey = BuildProfileCheckpointStateKey(activeSession.id, activeProfileName)
    local hadPendingTimer = sessionRuntime.pendingProfileCheckpointTimers[stateKey] ~= nil
    local pending = type(sessionRuntime.pendingProfileCheckpointSyncs[stateKey]) == "table" and sessionRuntime.pendingProfileCheckpointSyncs[stateKey] or {
      sessionId = TrimText(activeSession.id),
      profileName = TrimText(activeProfileName),
      reason = TrimText(opts.reason),
      domains = {},
      subdomains = {},
      prebuiltRowsBySubdomain = {},
      prebuiltRowSignaturesBySubdomain = {},
      queuedAt = now,
    }
    local previousCheckpointRequestSignature = TrimText(type(pending) == "table" and pending.__checkpointRequestSignature or "")
    local previousCheckpointTargetSignature = TrimText(type(pending) == "table" and pending.__checkpointTargetSignature or "")
    pending.sessionId = TrimText(activeSession.id)
    pending.profileName = TrimText(activeProfileName)
    pending.updatedAt = now
    if TrimText(opts.reason) ~= "" then
      pending.reason = TrimText(opts.reason)
    end
    pending.domains = CloneCheckpointDomainList(MergeComparedDomains(pending.domains, domains))
    pending.subdomains = CloneCheckpointSubdomainList(MergeCheckpointSubdomainLists(pending.subdomains, subdomains))
    if type(opts.prebuiltRowsBySubdomain) == "table" then
      pending.prebuiltRowsBySubdomain = type(pending.prebuiltRowsBySubdomain) == "table" and pending.prebuiltRowsBySubdomain or {}
      for subdomain, rows in pairs(opts.prebuiltRowsBySubdomain) do
        local resolvedSubdomain = TrimText(subdomain)
        if resolvedSubdomain ~= "" and type(rows) == "table" and #rows > 0 then
          local mergedById = {}
          for _, row in ipairs(type(pending.prebuiltRowsBySubdomain[resolvedSubdomain]) == "table" and pending.prebuiltRowsBySubdomain[resolvedSubdomain] or {}) do
            local rowId = tostring(type(row) == "table" and row.id or "")
            if rowId ~= "" then
              mergedById[rowId] = row
            end
          end
          for _, row in ipairs(rows) do
            local rowId = tostring(type(row) == "table" and row.id or "")
            if rowId ~= "" then
              mergedById[rowId] = row
            end
          end
          local mergedRows = {}
          for _, row in pairs(mergedById) do
            mergedRows[#mergedRows + 1] = row
          end
          table.sort(mergedRows, function(left, right)
            return tostring(type(left) == "table" and left.id or "") < tostring(type(right) == "table" and right.id or "")
          end)
          pending.prebuiltRowsBySubdomain[resolvedSubdomain] = mergedRows
        end
      end
    end
    if type(opts.prebuiltRowSignaturesBySubdomain) == "table" then
      pending.prebuiltRowSignaturesBySubdomain = type(pending.prebuiltRowSignaturesBySubdomain) == "table"
        and pending.prebuiltRowSignaturesBySubdomain
        or {}
      for subdomain, rowSignatures in pairs(opts.prebuiltRowSignaturesBySubdomain) do
        local resolvedSubdomain = TrimText(subdomain)
        if resolvedSubdomain ~= "" and type(rowSignatures) == "table" then
          local mergedRowSignatures = type(pending.prebuiltRowSignaturesBySubdomain[resolvedSubdomain]) == "table"
            and pending.prebuiltRowSignaturesBySubdomain[resolvedSubdomain]
            or {}
          for rowId, rowSignature in pairs(rowSignatures) do
            local resolvedRowId = tostring(rowId or "")
            if resolvedRowId ~= "" then
              mergedRowSignatures[resolvedRowId] = tostring(rowSignature or "")
            end
          end
          pending.prebuiltRowSignaturesBySubdomain[resolvedSubdomain] = mergedRowSignatures
        end
      end
    end
    local checkpointTransportSignature, checkpointRequestSignature, checkpointTargetSignature =
      BuildProfileCheckpointTransportSignature(activeSession, selfKey, pending)
    if hadPendingTimer
      and previousCheckpointRequestSignature ~= ""
      and previousCheckpointRequestSignature == checkpointRequestSignature
      and previousCheckpointTargetSignature == checkpointTargetSignature
    then
      return true, "queued"
    end
    local recentCheckpointState = sessionRuntime.recentProfileCheckpointRequestStates[stateKey]
    if type(recentCheckpointState) == "table" then
      local recentSentAt = math.max(0, tonumber(recentCheckpointState.sentAt) or 0)
      if recentSentAt <= 0
        or (now - recentSentAt) >= sessionConfig.recentProfileCheckpointRequestRetentionSeconds
      then
        sessionRuntime.recentProfileCheckpointRequestStates[stateKey] = nil
        recentCheckpointState = nil
      end
    end
    if type(recentCheckpointState) == "table"
      and recentCheckpointState.transportSignature == checkpointTransportSignature
    then
      return true, "unchanged"
    end
    pending.__checkpointRequestSignature = checkpointRequestSignature
    pending.__checkpointTargetSignature = checkpointTargetSignature
    pending.__checkpointTransportSignature = checkpointTransportSignature
    sessionRuntime.pendingProfileCheckpointSyncs[stateKey] = pending

    if opts.immediate == true then
      sessionRuntime.pendingProfileCheckpointTimers[stateKey] = nil
      sessionRuntime.pendingProfileCheckpointSyncs[stateKey] = nil
      local sentAt = now
      sessionRuntime.lastProfileCheckpointSyncAt[stateKey] = sentAt
      local queued, queueState = SendActiveProfileCheckpointNow(activeProfileName, pending)
      if queued and checkpointTransportSignature ~= "" then
        sessionRuntime.recentProfileCheckpointRequestStates[stateKey] = {
          transportSignature = checkpointTransportSignature,
          sentAt = sentAt,
        }
      end
      return queued, queueState
    end

    if sessionRuntime.pendingProfileCheckpointTimers[stateKey] then
      return true, "queued"
    end

    local lastSent = tonumber(sessionRuntime.lastProfileCheckpointSyncAt[stateKey]) or 0
    local delay = sessionConfig.profileCheckpointSyncDelaySeconds
    if lastSent > 0 and (now - lastSent) < sessionConfig.profileCheckpointSyncMinIntervalSeconds then
      delay = math.max(delay, sessionConfig.profileCheckpointSyncMinIntervalSeconds - math.max(0, now - lastSent))
    end

    if type(Compat) ~= "table" or type(Compat.After) ~= "function" then
      sessionRuntime.pendingProfileCheckpointSyncs[stateKey] = nil
      sessionRuntime.lastProfileCheckpointSyncAt[stateKey] = now
      local queued, queueState = SendActiveProfileCheckpointNow(activeProfileName, pending)
      if queued and checkpointTransportSignature ~= "" then
        sessionRuntime.recentProfileCheckpointRequestStates[stateKey] = {
          transportSignature = checkpointTransportSignature,
          sentAt = now,
        }
      end
      return queued, queueState
    end

    sessionRuntime.profileCheckpointTimerToken = math.max(0, tonumber(sessionRuntime.profileCheckpointTimerToken) or 0) + 1
    local timerToken = sessionRuntime.profileCheckpointTimerToken
    sessionRuntime.pendingProfileCheckpointTimers[stateKey] = {
      queuedAt = now,
      token = timerToken,
    }
    Compat.After(delay, function()
      FlushQueuedProfileCheckpointSync(stateKey, timerToken)
    end)
    return true, "queued"
  end

  profileSyncMetaOps.buildSessionMemberCheckpointSignature = function(memberData)
    if type(memberData) ~= "table" then
      return ""
    end
    return table.concat({
      TrimText(memberData.status or "JOINED"),
      tostring(math.max(0, tonumber(memberData.joinedAt) or 0)),
      tostring(math.max(0, tonumber(memberData.leftAt) or 0)),
      TrimText(memberData.addonVersion),
      TrimText(memberData.clientVersion),
      TrimText(memberData.className),
      TrimText(memberData.classFile),
      TrimText(memberData.specName),
      TrimText(memberData.specIcon),
      memberData.localAutoPassEnabled == true and "1" or "0",
      TrimText(memberData.profileMaster),
      TrimText(memberData.role),
      FirstNonEmptyText(memberData.sharedProfileId, memberData.profileId),
      tostring(math.max(0, tonumber(memberData.settingsRevision) or 0)),
      tostring(math.max(0, tonumber(memberData.permissionsRevision) or 0)),
      tostring(math.max(0, tonumber(memberData.operationalRevision) or 0)),
      tostring(math.max(0, tonumber(memberData.lootRevision) or 0)),
      tostring(math.max(0, tonumber(memberData.sessionRevision) or 0)),
      tostring(math.max(0, tonumber(memberData.profileUpdatedAt) or 0)),
      TrimText(memberData.settingsChecksum),
      TrimText(memberData.permissionsChecksum),
      TrimText(memberData.operationalChecksum),
      TrimText(memberData.lootChecksum),
      TrimText(memberData.sessionChecksum),
      TrimText(memberData.liveLootChecksum),
      TrimText(memberData.archiveLootChecksum),
      TrimText(memberData.lootListArchiveChecksum),
      TrimText(memberData.itemHistoryArchiveChecksum),
      TrimText(memberData.sessionHistoryArchiveChecksum),
      TrimText(memberData.funAwardsArchiveChecksum),
    }, "\31")
  end

  profileSyncMetaOps.buildSessionMemberCheckpointState = function(profileName, sessionId, memberKey, memberData)
    local subdomain = BuildSessionRecordCheckpointSubdomain(sessionId)
    local resolvedProfileName = TrimText(profileName)
    local resolvedSessionId = TrimText(sessionId)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if subdomain == "" or resolvedProfileName == "" or resolvedSessionId == "" or resolvedMemberKey == "" then
      return nil
    end

    local activeSession, activeProfileName = GetActiveLootSession()
    activeSession = type(activeSession) == "table" and activeSession or nil
    local hasMatchingActiveSession = type(activeSession) == "table"
      and DoesActiveSessionMatch(activeSession, activeProfileName, resolvedSessionId, resolvedProfileName)
    local resolvedActiveProfileName = hasMatchingActiveSession
      and FirstNonEmptyText(activeProfileName, resolvedProfileName)
      or resolvedProfileName
    local member = type(memberData) == "table"
      and memberData
      or (hasMatchingActiveSession
        and type(activeSession.members) == "table"
        and activeSession.members[resolvedMemberKey]
        or nil)
    if type(member) ~= "table" then
      return nil
    end
    local rowId = "session:member:" .. resolvedMemberKey
    local rowSignature = type(profileSyncMetaOps.buildSessionMemberCheckpointSignature) == "function"
      and profileSyncMetaOps.buildSessionMemberCheckpointSignature(member)
      or ""
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    local targetSignature = hasMatchingActiveSession
      and BuildLiveSyncTargetSignature(activeSession, selfKey, nil)
      or ""
    local stateKey = BuildProfileCheckpointStateKey(
      hasMatchingActiveSession and activeSession.id or resolvedSessionId,
      resolvedActiveProfileName
    )
    local recentCheckpointStateKey = stateKey ~= ""
      and (string.lower(stateKey) .. "|member|" .. string.lower(resolvedMemberKey))
      or ""
    local remotePayload = {
      session = {
        members = {},
      },
    }
    remotePayload.session.members[resolvedMemberKey] = member
    return {
      subdomain = subdomain,
      rowId = rowId,
      rowSignature = rowSignature,
      targetSignature = targetSignature,
      stateKey = stateKey,
      recentCheckpointStateKey = recentCheckpointStateKey,
      prebuiltRowsBySubdomain = {
        [subdomain] = {
          {
            id = rowId,
            subdomain = subdomain,
            applySpec = {
              kind = "keyed_entry",
              tableField = "session.members",
              key = resolvedMemberKey,
            },
            remotePayload = remotePayload,
          },
        },
      },
      prebuiltRowSignaturesBySubdomain = {
        [subdomain] = {
          [rowId] = rowSignature,
        },
      },
    }
  end

  local function QueueSessionRecordCheckpoint(profileName, sessionId, reason, memberKey, opts)
    opts = type(opts) == "table" and opts or {}
    local subdomain = BuildSessionRecordCheckpointSubdomain(sessionId)
    if subdomain == "" then
      return false, "Session checkpoint scope is unavailable."
    end
    local prebuiltRowsBySubdomain = nil
    local prebuiltRowSignaturesBySubdomain = nil
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if resolvedMemberKey ~= "" then
      local checkpointState = type(opts.prebuiltCheckpointState) == "table"
        and opts.prebuiltCheckpointState
        or (type(profileSyncMetaOps.buildSessionMemberCheckpointState) == "function"
          and profileSyncMetaOps.buildSessionMemberCheckpointState(profileName, sessionId, resolvedMemberKey, nil)
          or nil)
      local rowId = tostring(type(checkpointState) == "table" and checkpointState.rowId or "")
      local rowSignature = TrimText(type(checkpointState) == "table" and checkpointState.rowSignature or "")
      local targetSignature = TrimText(type(checkpointState) == "table" and checkpointState.targetSignature or "")
      local stateKey = TrimText(type(checkpointState) == "table" and checkpointState.stateKey or "")
      local now = GetProfileCheckpointSyncTime()
      PruneAgedSessionRuntimeTracking(now)
      local recentCheckpointStateKey = stateKey ~= ""
        and FirstNonEmptyText(
          TrimText(type(checkpointState) == "table" and checkpointState.recentCheckpointStateKey or ""),
          string.lower(stateKey) .. "|member|" .. string.lower(resolvedMemberKey)
        )
        or ""
      if stateKey ~= ""
        and rowId ~= ""
        and rowSignature ~= ""
        and sessionRuntime.pendingProfileCheckpointTimers[stateKey]
      then
        local pending = sessionRuntime.pendingProfileCheckpointSyncs[stateKey]
        local queuedRowSignatures = type(pending) == "table" and pending.prebuiltRowSignaturesBySubdomain or nil
        local queuedSubdomain = type(queuedRowSignatures) == "table" and queuedRowSignatures[subdomain] or nil
        local pendingTargetSignature = TrimText(type(pending) == "table" and pending.__checkpointTargetSignature or "")
        if type(queuedSubdomain) == "table"
          and queuedSubdomain[rowId] == rowSignature
          and (targetSignature == "" or pendingTargetSignature == targetSignature)
        then
          if type(RecordProfileSyncDecision) == "function" then
            RecordProfileSyncDecision("queue_session_record_checkpoint", {
              action = "covered_by_pending",
              sessionId = TrimText(sessionId),
              profileName = TrimText(profileName),
              target = resolvedMemberKey,
              targetCount = 1,
              queuedCount = 0,
              requestedScope = "precise",
              requestedDomains = { "session" },
              requestedSubdomains = { subdomain },
            })
          end
          return true, "queued"
        end
      end
      local recentCheckpointState = recentCheckpointStateKey ~= ""
        and sessionRuntime.recentSessionMemberCheckpointStates[recentCheckpointStateKey]
        or nil
      if recentCheckpointStateKey ~= "" and type(recentCheckpointState) == "table" then
        local recentQueuedAt = math.max(0, tonumber(recentCheckpointState.queuedAt) or 0)
        if recentQueuedAt <= 0
          or (now - recentQueuedAt) >= sessionConfig.recentSessionMemberCheckpointRetentionSeconds
        then
          sessionRuntime.recentSessionMemberCheckpointStates[recentCheckpointStateKey] = nil
          recentCheckpointState = nil
        end
      end
      if type(recentCheckpointState) == "table"
        and recentCheckpointState.signature == rowSignature
        and recentCheckpointState.targetSignature == targetSignature
      then
        if type(RecordProfileSyncDecision) == "function" then
          RecordProfileSyncDecision("queue_session_record_checkpoint", {
            action = "suppressed_unchanged",
            sessionId = TrimText(sessionId),
            profileName = TrimText(profileName),
            target = resolvedMemberKey,
            targetCount = 1,
            queuedCount = 0,
            requestedScope = "precise",
            requestedDomains = { "session" },
            requestedSubdomains = { subdomain },
          })
        end
        return true, "unchanged"
      end
      prebuiltRowsBySubdomain = type(checkpointState) == "table" and checkpointState.prebuiltRowsBySubdomain or nil
      prebuiltRowSignaturesBySubdomain = type(checkpointState) == "table" and checkpointState.prebuiltRowSignaturesBySubdomain or nil
      local queued, queueState = INTERNAL_API.LIDCOUNCIL_QueueActiveProfileCheckpointFlow_Impl(profileName, {
        reason = TrimText(reason) ~= "" and TrimText(reason) or "session_checkpoint",
        domains = { "session" },
        subdomains = { subdomain },
        prebuiltRowsBySubdomain = prebuiltRowsBySubdomain,
        prebuiltRowSignaturesBySubdomain = prebuiltRowSignaturesBySubdomain,
      })
      if type(RecordProfileSyncDecision) == "function" and TrimText(rowSignature) ~= "" then
        RecordProfileSyncDecision("queue_session_record_checkpoint", {
          action = queued and FirstNonEmptyText(queueState, "queued") or "failed",
          sessionId = TrimText(sessionId),
          profileName = TrimText(profileName),
          target = resolvedMemberKey,
          targetCount = 1,
          queuedCount = queued and 1 or 0,
          requestedScope = "precise",
          requestedDomains = { "session" },
          requestedSubdomains = { subdomain },
        })
      end
      if queued and recentCheckpointStateKey ~= "" and targetSignature ~= "" then
        sessionRuntime.recentSessionMemberCheckpointStates[recentCheckpointStateKey] = {
          signature = rowSignature,
          targetSignature = targetSignature,
          queuedAt = now,
        }
      end
      return queued, queueState
    end
    return INTERNAL_API.LIDCOUNCIL_QueueActiveProfileCheckpointFlow_Impl(profileName, {
      reason = TrimText(reason) ~= "" and TrimText(reason) or "session_checkpoint",
      domains = { "session" },
      subdomains = { subdomain },
      prebuiltRowsBySubdomain = prebuiltRowsBySubdomain,
      prebuiltRowSignaturesBySubdomain = prebuiltRowSignaturesBySubdomain,
    })
  end

  local function HasComparedDomain(domains, domain)
    local needle = string.lower(TrimText(domain))
    if needle == "" then
      return false
    end
    for _, value in ipairs(type(domains) == "table" and domains or {}) do
      if string.lower(TrimText(value)) == needle then
        return true
      end
    end
    return false
  end

  local function AreCheckpointScopeListsEqual(left, right)
    local leftList = type(left) == "table" and left or {}
    local rightList = type(right) == "table" and right or {}
    if #leftList ~= #rightList then
      return false
    end
    local rightLookup = {}
    for _, value in ipairs(rightList) do
      rightLookup[string.lower(TrimText(value))] = true
    end
    for _, value in ipairs(leftList) do
      if not rightLookup[string.lower(TrimText(value))] then
        return false
      end
    end
    return true
  end

  local function GetRepairRequestModeRank(mode)
    local resolvedMode = string.upper(TrimText(mode))
    if resolvedMode == "LIVE" then
      return 2
    end
    if resolvedMode == "BACKGROUND" then
      return 1
    end
    return 0
  end

  local function BuildNormalizedRepairListSignature(values)
    local ordered = {}
    local included = {}
    for _, value in ipairs(type(values) == "table" and values or {}) do
      local resolvedValue = TrimText(value)
      local resolvedKey = string.lower(resolvedValue)
      if resolvedValue ~= "" and not included[resolvedKey] then
        included[resolvedKey] = true
        ordered[#ordered + 1] = resolvedKey
      end
    end
    table.sort(ordered)
    return table.concat(ordered, "\30")
  end

  profileSyncMetaOps.buildPreparedRepairTransferChunkSignature = function(preparedTransfer)
    local chunkParts = {}
    for _, chunk in ipairs(type(preparedTransfer) == "table" and type(preparedTransfer.chunks) == "table" and preparedTransfer.chunks or {}) do
      local resolvedChunk = tostring(chunk or "")
      chunkParts[#chunkParts + 1] = tostring(#resolvedChunk) .. ":" .. resolvedChunk
    end
    return table.concat(chunkParts, "\29")
  end

  profileSyncMetaOps.buildPreparedRepairTransferSignature = function(preparedTransfer)
    preparedTransfer = type(preparedTransfer) == "table" and preparedTransfer or {}
    return table.concat({
      TrimText(preparedTransfer.profileName),
      TrimText(preparedTransfer.profileId),
      string.upper(TrimText(preparedTransfer.transferKind)),
      BuildNormalizedRepairListSignature(preparedTransfer.domains),
      BuildNormalizedRepairListSignature(preparedTransfer.subdomains),
      BuildNormalizedRepairListSignature(preparedTransfer.requestedDomains),
      BuildNormalizedRepairListSignature(preparedTransfer.requestedSubdomains),
      TrimText(preparedTransfer.requestedScope),
      TrimText(preparedTransfer.fallbackEscalation),
      preparedTransfer.scopeEscalated == true and "1" or "0",
      preparedTransfer.fullSnapshotFallback == true and "1" or "0",
      BuildNormalizedRepairListSignature(preparedTransfer.fallbackReasons),
      profileSyncMetaOps.buildPreparedRepairTransferChunkSignature(preparedTransfer),
    }, "\31")
  end

  profileSyncMetaOps.syncPreparedRepairTransferDetailCounts = function(detail, transfers, duplicateCount)
    detail = type(detail) == "table" and detail or {}
    detail.transferKinds = profileSyncMetaOps.buildPreparedTransferKindList(transfers)
    detail.patchTransfers = 0
    detail.snapshotTransfers = 0
    for _, preparedTransfer in ipairs(type(transfers) == "table" and transfers or {}) do
      local transferKind = string.upper(TrimText(type(preparedTransfer) == "table" and preparedTransfer.transferKind or ""))
      if transferKind == "PATCHES" or transferKind == "ROWPATCHES" then
        detail.patchTransfers = detail.patchTransfers + 1
      elseif transferKind ~= "" then
        detail.snapshotTransfers = detail.snapshotTransfers + 1
      end
    end
    detail.duplicatePreparedTransfers = math.max(0, tonumber(duplicateCount) or 0)
    detail.dedupedTransferCount = #(type(transfers) == "table" and transfers or {})
    return detail
  end

  profileSyncMetaOps.dedupePreparedRepairTransfers = function(transfers, detail)
    if type(transfers) ~= "table" or #transfers <= 1 then
      return transfers, 0, profileSyncMetaOps.syncPreparedRepairTransferDetailCounts(detail, transfers, 0)
    end

    local uniqueTransfers = {}
    local seenSignatures = {}
    local duplicateCount = 0
    for _, preparedTransfer in ipairs(transfers) do
      local transferSignature = profileSyncMetaOps.buildPreparedRepairTransferSignature(preparedTransfer)
      if transferSignature ~= "" and seenSignatures[transferSignature] == true then
        duplicateCount = duplicateCount + 1
      else
        seenSignatures[transferSignature] = true
        uniqueTransfers[#uniqueTransfers + 1] = preparedTransfer
      end
    end
    return uniqueTransfers, duplicateCount, profileSyncMetaOps.syncPreparedRepairTransferDetailCounts(detail, uniqueTransfers, duplicateCount)
  end

  profileSyncMetaOps.buildRepairQueueStepSignature = function(step)
    step = type(step) == "table" and step or {}
    return table.concat({
      string.upper(TrimText(step.mode)),
      TrimText(step.reason),
      step.skipScopePrune == true and "1" or "0",
      BuildNormalizedRepairListSignature(step.domains),
      BuildNormalizedRepairListSignature(step.subdomains),
    }, "\31")
  end

  profileSyncMetaOps.dedupeRepairQueueSteps = function(steps)
    if type(steps) ~= "table" or #steps <= 1 then
      return steps, 0
    end

    local uniqueSteps = {}
    local seenSignatures = {}
    local duplicateCount = 0
    for _, step in ipairs(steps) do
      local stepSignature = profileSyncMetaOps.buildRepairQueueStepSignature(step)
      if seenSignatures[stepSignature] == true then
        duplicateCount = duplicateCount + 1
      else
        seenSignatures[stepSignature] = true
        uniqueSteps[#uniqueSteps + 1] = step
      end
    end
    return uniqueSteps, duplicateCount
  end

  profileSyncMetaOps.hasRepairFallbackReason = function(reasons, needle)
    local resolvedNeedle = string.lower(TrimText(needle))
    if resolvedNeedle == "" then
      return false
    end
    for _, reasonValue in ipairs(type(reasons) == "table" and reasons or {}) do
      if string.lower(TrimText(reasonValue)) == resolvedNeedle then
        return true
      end
    end
    return false
  end

  profileSyncMetaOps.shouldRetryPreparedRepairForPatchState = function(prepareDetail)
    local patchStateFallbackSubdomains = CloneCheckpointSubdomainList(
      type(prepareDetail) == "table" and prepareDetail.patchStateFallbackSubdomains or {}
    )
    local snapshotFallbackSubdomains = CloneCheckpointSubdomainList(
      type(prepareDetail) == "table" and prepareDetail.snapshotFallbackSubdomains or {}
    )
    return #patchStateFallbackSubdomains > 0
      and AreCheckpointScopeListsEqual(patchStateFallbackSubdomains, snapshotFallbackSubdomains)
      and (
        profileSyncMetaOps.hasRepairFallbackReason(
          type(prepareDetail) == "table" and prepareDetail.fallbackReasons or {},
          "missing_patch_state"
        )
        or profileSyncMetaOps.hasRepairFallbackReason(
          type(prepareDetail) == "table" and prepareDetail.fallbackReasons or {},
          "patch_manifest_token_mismatch"
        )
        or profileSyncMetaOps.hasRepairFallbackReason(
          type(prepareDetail) == "table" and prepareDetail.fallbackReasons or {},
          "no_patch_ready_subdomains"
        )
      )
  end

  profileSyncMetaOps.buildPreparedRepairTransferBatchSignature = function(transfers)
    local signatures = {}
    for _, preparedTransfer in ipairs(type(transfers) == "table" and transfers or {}) do
      signatures[#signatures + 1] = profileSyncMetaOps.buildPreparedRepairTransferSignature(preparedTransfer)
    end
    return table.concat(signatures, "\28")
  end

  profileSyncMetaOps.applyPreparedRepairScopeToDetail = function(detail, requestedDomains, requestedSubdomains, effectiveDomains, effectiveSubdomains)
    detail = type(detail) == "table" and detail or {}
    detail.requestedDomains = CloneCheckpointDomainList(requestedDomains)
    detail.requestedSubdomains = CloneCheckpointSubdomainList(requestedSubdomains)
    detail.effectiveDomains = CloneCheckpointDomainList(effectiveDomains)
    detail.effectiveSubdomains = CloneCheckpointSubdomainList(effectiveSubdomains)
    if TrimText(detail.requestedScope) == "" then
      detail.requestedScope = ClassifyRequestedRepairScope(
        detail.requestedDomains,
        detail.requestedSubdomains,
        #detail.requestedSubdomains > 0 and "precise" or (#detail.requestedDomains > 0 and "targeted" or "full")
      )
    end
    return detail
  end

  profileSyncMetaOps.applyOutboundQueueStatsToRepairDetail = function(detail, queueDetail)
    if type(detail) ~= "table" or type(queueDetail) ~= "table" then
      return detail
    end
    detail.queueMergeCount = math.max(0, tonumber(detail.queueMergeCount) or 0)
      + math.max(0, tonumber(queueDetail.queueMergeCount) or tonumber(queueDetail.mergedCount) or 0)
    detail.queueExactDuplicateCount = math.max(0, tonumber(detail.queueExactDuplicateCount) or 0)
      + math.max(
        0,
        tonumber(queueDetail.queueExactDuplicateCount) or tonumber(queueDetail.exactDuplicateCount) or 0
      )
    return detail
  end

  local function BuildSessionMemberRepairStateSignature(memberData)
    memberData = type(memberData) == "table" and memberData or {}
    return table.concat({
      TrimText(memberData.status or "JOINED"),
      tostring(math.max(0, tonumber(memberData.joinedAt) or 0)),
      tostring(math.max(0, tonumber(memberData.leftAt) or 0)),
      FirstNonEmptyText(memberData.sharedProfileId, memberData.profileId),
      tostring(math.max(0, tonumber(memberData.settingsRevision) or 0)),
      tostring(math.max(0, tonumber(memberData.permissionsRevision) or 0)),
      tostring(math.max(0, tonumber(memberData.operationalRevision) or 0)),
      tostring(math.max(0, tonumber(memberData.lootRevision) or 0)),
      tostring(math.max(0, tonumber(memberData.sessionRevision) or 0)),
      tostring(math.max(0, tonumber(memberData.profileUpdatedAt) or 0)),
      TrimText(memberData.settingsChecksum),
      TrimText(memberData.permissionsChecksum),
      TrimText(memberData.operationalChecksum),
      TrimText(memberData.lootChecksum),
      TrimText(memberData.sessionChecksum),
      TrimText(memberData.liveLootChecksum),
      TrimText(memberData.archiveLootChecksum),
      TrimText(memberData.lootListArchiveChecksum),
      TrimText(memberData.itemHistoryArchiveChecksum),
      TrimText(memberData.sessionHistoryArchiveChecksum),
      TrimText(memberData.funAwardsArchiveChecksum),
    }, "\31")
  end

  BuildLocalRepairRevisionSignature = function(activeSession, profileName, syncCandidate, prebuiltSignature)
    local resolvedProfileName = TrimText(profileName)
    local candidateSignature = TrimText(prebuiltSignature)
    if candidateSignature ~= "" then
      return candidateSignature
    end
    candidateSignature = TrimText(type(syncCandidate) == "table" and syncCandidate.localRevisionSignature or "")
    if candidateSignature ~= "" then
      return candidateSignature
    end
    local localProfileId = TrimText(select(1, deps.GetLootProfileId(resolvedProfileName)) or "")
    local localRevisionSummary = type(GetLootProfileRevisionSummary) == "function"
      and GetLootProfileRevisionSummary(resolvedProfileName)
      or {}
    if type(deps.NormalizeRevisionSummary) == "function" then
      localRevisionSummary = deps.NormalizeRevisionSummary(localRevisionSummary, resolvedProfileName, localProfileId)
    end
    localRevisionSummary = type(localRevisionSummary) == "table" and localRevisionSummary or {}
    localRevisionSummary.liveLootChecksum = profileSyncMetaOps.buildSessionLiveLootChecksum(
      resolvedProfileName,
      activeSession
    )
    localRevisionSummary.archiveLootChecksum = profileSyncMetaOps.buildSessionArchiveLootChecksum(
      resolvedProfileName,
      activeSession
    )
    return table.concat({
      FirstNonEmptyText(localRevisionSummary.profileId, localProfileId),
      tostring(math.max(0, tonumber(localRevisionSummary.settings) or 0)),
      tostring(math.max(0, tonumber(localRevisionSummary.permissions) or 0)),
      tostring(math.max(0, tonumber(localRevisionSummary.operational) or 0)),
      tostring(math.max(0, tonumber(localRevisionSummary.loot) or tonumber(localRevisionSummary.operational) or 0)),
      tostring(math.max(0, tonumber(localRevisionSummary.session) or tonumber(localRevisionSummary.operational) or 0)),
      tostring(math.max(0, tonumber(localRevisionSummary.updatedAt) or 0)),
      TrimText(localRevisionSummary.settingsChecksum),
      TrimText(localRevisionSummary.permissionsChecksum),
      TrimText(localRevisionSummary.operationalChecksum),
      TrimText(localRevisionSummary.lootChecksum),
      TrimText(localRevisionSummary.sessionChecksum),
      TrimText(localRevisionSummary.liveLootChecksum),
      TrimText(localRevisionSummary.archiveLootChecksum),
    }, "\31")
  end

  local function BuildRecentMemberRepairRequestStateKey(sessionId, memberKey)
    local resolvedSessionId = TrimText(sessionId)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if resolvedSessionId == "" or resolvedMemberKey == "" then
      return ""
    end
    return string.lower(resolvedSessionId) .. "|" .. string.lower(resolvedMemberKey)
  end

  local function DoesRecentMemberRepairStateCoverScope(recentState, requestedDomains, requestedSubdomains, requestedForceFullSnapshot)
    recentState = type(recentState) == "table" and recentState or {}
    if requestedForceFullSnapshot == true then
      return recentState.forceFullSnapshot == true
    end
    if recentState.forceFullSnapshot == true then
      return true
    end
    local recentDomains = CloneCheckpointDomainList(recentState.domains)
    local recentSubdomains = CloneCheckpointSubdomainList(recentState.subdomains)
    for _, domain in ipairs(type(requestedDomains) == "table" and requestedDomains or {}) do
      if not HasComparedDomain(recentDomains, domain) then
        return false
      end
    end
    local recentSubdomainLookup = {}
    for _, subdomain in ipairs(recentSubdomains) do
      local resolvedSubdomain = string.lower(TrimText(subdomain))
      if resolvedSubdomain ~= "" then
        recentSubdomainLookup[resolvedSubdomain] = true
      end
    end
    for _, subdomain in ipairs(type(requestedSubdomains) == "table" and requestedSubdomains or {}) do
      local resolvedSubdomain = TrimText(subdomain)
      local resolvedKey = string.lower(resolvedSubdomain)
      if resolvedKey ~= "" and recentSubdomainLookup[resolvedKey] ~= true then
        -- A transfer with explicit leaves is not a whole-domain transfer. For
        -- example, the Fun Awards leaves live under `loot`, but must not
        -- suppress the separate Loot List archive leaves for the same domain.
        if #recentSubdomains > 0 then
          return false
        end
        local parentDomain = type(profileSyncMetaOps.getSubdomainParentDomain) == "function"
          and string.lower(TrimText(profileSyncMetaOps.getSubdomainParentDomain(resolvedSubdomain)))
          or ""
        if parentDomain == "" or not HasComparedDomain(recentDomains, parentDomain) then
          return false
        end
      end
    end
    return true
  end

  local function GetRecentMemberRepairRequestState(sessionId, memberKey)
    local stateKey = BuildRecentMemberRepairRequestStateKey(sessionId, memberKey)
    if stateKey == "" then
      return nil
    end
    local recentState = sessionRuntime.recentMemberRepairRequestStates[stateKey]
    if type(recentState) ~= "table" then
      sessionRuntime.recentMemberRepairRequestStates[stateKey] = nil
      return nil
    end
    local now = GetProfileCheckpointSyncTime()
    local updatedAt = math.max(0, tonumber(recentState.updatedAt or recentState.queuedAt) or 0)
    if updatedAt <= 0 or (now - updatedAt) >= sessionConfig.memberRepairRequestRetentionSeconds then
      sessionRuntime.recentMemberRepairRequestStates[stateKey] = nil
      return nil
    end
    return recentState
  end

  local function RememberRecentMemberRepairRequestState(sessionId, memberKey, requestState)
    local stateKey = BuildRecentMemberRepairRequestStateKey(sessionId, memberKey)
    if stateKey == "" or type(requestState) ~= "table" then
      return false
    end
    local now = GetProfileCheckpointSyncTime()
    local existingState = GetRecentMemberRepairRequestState(sessionId, memberKey)
    local nextState = {
      sessionId = TrimText(sessionId),
      profileName = TrimText(requestState.profileName),
      memberKey = NormalizeCharacterKey(memberKey),
      mode = TrimText(requestState.mode),
      forceFullSnapshot = requestState.forceFullSnapshot == true,
      domains = CloneCheckpointDomainList(requestState.domains),
      subdomains = CloneCheckpointSubdomainList(requestState.subdomains),
      localRevisionSignature = TrimText(requestState.localRevisionSignature),
      memberStateSignature = TrimText(requestState.memberStateSignature),
      transportSignature = TrimText(requestState.transportSignature),
      queuedAt = math.max(
        0,
        tonumber(requestState.queuedAt) or tonumber(type(existingState) == "table" and existingState.queuedAt or 0) or now
      ),
      updatedAt = now,
    }
    if type(existingState) == "table"
      and nextState.localRevisionSignature ~= ""
      and nextState.localRevisionSignature == TrimText(existingState.localRevisionSignature)
      and nextState.memberStateSignature == TrimText(existingState.memberStateSignature)
    then
      nextState.domains = CloneCheckpointDomainList(MergeComparedDomains(existingState.domains, nextState.domains))
      nextState.subdomains = CloneCheckpointSubdomainList(MergeCheckpointSubdomainLists(existingState.subdomains, nextState.subdomains))
      nextState.forceFullSnapshot = nextState.forceFullSnapshot or existingState.forceFullSnapshot == true
      if GetRepairRequestModeRank(existingState.mode) > GetRepairRequestModeRank(nextState.mode) then
        nextState.mode = TrimText(existingState.mode)
      end
    end
    sessionRuntime.recentMemberRepairRequestStates[stateKey] = nextState
    return true, nextState
  end

  local function BuildRecentMemberRepairRequestState(activeSession, profileName, sessionId, memberKey, requestedDomains, requestedSubdomains, opts)
    opts = type(opts) == "table" and opts or {}
    local resolvedProfileName = TrimText(profileName)
    local resolvedSessionId = TrimText(sessionId)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if resolvedProfileName == "" or resolvedSessionId == "" or resolvedMemberKey == "" then
      return nil
    end
    local mode = TrimText(opts.mode) ~= "" and TrimText(opts.mode) or "LIVE"
    local syncCandidate = type(opts.syncCandidate) == "table" and opts.syncCandidate or nil
    local localRevisionSignature = BuildLocalRepairRevisionSignature(
      activeSession,
      resolvedProfileName,
      syncCandidate,
      opts.localRepairRevisionSignature
    )
    local memberStateSignature = BuildSessionMemberRepairStateSignature(select(1, FindSessionMember(activeSession, resolvedMemberKey)))
    local forceFullSnapshot = opts.forceFullSnapshot == true
    return {
      sessionId = resolvedSessionId,
      profileName = resolvedProfileName,
      memberKey = resolvedMemberKey,
      mode = mode,
      forceFullSnapshot = forceFullSnapshot,
      domains = CloneCheckpointDomainList(requestedDomains),
      subdomains = CloneCheckpointSubdomainList(requestedSubdomains),
      localRevisionSignature = localRevisionSignature,
      memberStateSignature = memberStateSignature,
      transportSignature = table.concat({
        localRevisionSignature,
        memberStateSignature,
        string.upper(mode),
        forceFullSnapshot == true and "1" or "0",
        BuildNormalizedRepairListSignature(requestedDomains),
        BuildNormalizedRepairListSignature(requestedSubdomains),
      }, "\31"),
    }
  end

  local function EvaluateRecentMemberRepairRequest(activeSession, profileName, sessionId, memberKey, requestedDomains, requestedSubdomains, opts)
    opts = type(opts) == "table" and opts or {}
    local requestState = BuildRecentMemberRepairRequestState(
      activeSession,
      profileName,
      sessionId,
      memberKey,
      requestedDomains,
      requestedSubdomains,
      opts
    )
    if type(requestState) ~= "table" then
      return false, nil, nil, nil
    end
    local recentState = GetRecentMemberRepairRequestState(sessionId, memberKey)
    if type(recentState) == "table"
      and requestState.localRevisionSignature ~= ""
      and requestState.localRevisionSignature == TrimText(recentState.localRevisionSignature)
      and requestState.memberStateSignature == TrimText(recentState.memberStateSignature)
    then
      if requestState.transportSignature ~= ""
        and requestState.transportSignature == TrimText(recentState.transportSignature)
      then
        return true, requestState, recentState, "exact"
      end
      if GetRepairRequestModeRank(recentState.mode) >= GetRepairRequestModeRank(requestState.mode)
        and DoesRecentMemberRepairStateCoverScope(
          recentState,
          requestState.domains,
          requestState.subdomains,
          requestState.forceFullSnapshot == true
        )
      then
        return true, requestState, recentState, "covered"
      end
    end
    return false, requestState, recentState, nil
  end

  FindActiveSyncCandidate = function(memberKey)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if resolvedMemberKey == "" or type(profileSyncMetaOps.getActiveSyncCandidates) ~= "function" then
      return nil
    end
    for _, candidate in ipairs(profileSyncMetaOps.getActiveSyncCandidates() or {}) do
      if NormalizeCharacterKey(type(candidate) == "table" and candidate.memberKey or "") == resolvedMemberKey then
        return candidate
      end
    end
    return nil
  end

  GetActiveSyncCandidateContext = function(memberKey)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    local matchedCandidate = nil
    local localRevisionSignature = ""
    if type(profileSyncMetaOps.getActiveSyncCandidates) ~= "function" then
      return nil, ""
    end
    for _, candidate in ipairs(profileSyncMetaOps.getActiveSyncCandidates() or {}) do
      if localRevisionSignature == "" then
        localRevisionSignature = TrimText(type(candidate) == "table" and candidate.localRevisionSignature or "")
      end
      if matchedCandidate == nil
        and resolvedMemberKey ~= ""
        and NormalizeCharacterKey(type(candidate) == "table" and candidate.memberKey or "") == resolvedMemberKey
      then
        matchedCandidate = candidate
      end
      if matchedCandidate ~= nil and localRevisionSignature ~= "" then
        break
      end
    end
    return matchedCandidate, localRevisionSignature
  end

  BuildActiveSyncCandidateSnapshot = function()
    local snapshot = {
      list = {},
      lookup = {},
      localRevisionSignature = "",
    }
    if type(profileSyncMetaOps.getActiveSyncCandidates) ~= "function" then
      return snapshot
    end
    for _, candidate in ipairs(profileSyncMetaOps.getActiveSyncCandidates() or {}) do
      snapshot.list[#snapshot.list + 1] = candidate
      local candidateMemberKey = NormalizeCharacterKey(type(candidate) == "table" and candidate.memberKey or "")
      if candidateMemberKey ~= "" then
        snapshot.lookup[string.lower(candidateMemberKey)] = candidate
      end
      if snapshot.localRevisionSignature == "" then
        snapshot.localRevisionSignature = TrimText(type(candidate) == "table" and candidate.localRevisionSignature or "")
      end
    end
    return snapshot
  end

  local function GetActiveSyncCandidateContextFromSnapshot(memberKey, snapshot)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    snapshot = type(snapshot) == "table" and snapshot or nil
    if snapshot == nil then
      return GetActiveSyncCandidateContext(resolvedMemberKey)
    end
    local matchedCandidate = type(snapshot.lookup) == "table"
      and snapshot.lookup[string.lower(resolvedMemberKey)]
      or nil
    if matchedCandidate == nil and type(snapshot.list) == "table" then
      for _, candidate in ipairs(snapshot.list) do
        if NormalizeCharacterKey(type(candidate) == "table" and candidate.memberKey or "") == resolvedMemberKey then
          matchedCandidate = candidate
          break
        end
      end
    end
    return matchedCandidate, TrimText(snapshot.localRevisionSignature)
  end

  local function BuildActiveSyncCandidateStateEntries(snapshot, rosterLookup)
    snapshot = type(snapshot) == "table" and snapshot or BuildActiveSyncCandidateSnapshot()
    local candidateSyncStateByMemberKey = {}
    local candidateEntries = {}
    for _, candidate in ipairs(type(snapshot.list) == "table" and snapshot.list or {}) do
      local candidateKey = NormalizeCharacterKey(type(candidate) == "table" and candidate.memberKey or "")
      if candidateKey ~= "" then
        candidateSyncStateByMemberKey[candidateKey] = INTERNAL_API.LIDCOUNCIL_GetPreciseSyncCandidateState(candidate, rosterLookup)
        candidateEntries[#candidateEntries + 1] = candidateKey
          .. "\30"
          .. FirstNonEmptyText(candidateSyncStateByMemberKey[candidateKey], "")
      end
    end
    return candidateEntries, candidateSyncStateByMemberKey
  end

  profileSyncMetaOps.resolveHostRepairScopeForMember = function(memberKey, domains, subdomains, opts)
    opts = type(opts) == "table" and opts or {}
    local requestedDomains = CloneCheckpointDomainList(domains)
    local requestedSubdomains = CloneCheckpointSubdomainList(subdomains)
    local detail = {
      requestedDomains = CloneCheckpointDomainList(requestedDomains),
      requestedSubdomains = CloneCheckpointSubdomainList(requestedSubdomains),
      effectiveDomains = CloneCheckpointDomainList(requestedDomains),
      effectiveSubdomains = CloneCheckpointSubdomainList(requestedSubdomains),
      prunedDomains = {},
      prunedSubdomains = {},
      scopeTightened = false,
      skippedNoOp = false,
      skipReason = "",
    }
    if opts.skipScopePrune == true or (#requestedDomains == 0 and #requestedSubdomains == 0) then
      return requestedDomains, requestedSubdomains, detail
    end

    local candidate = type(opts.syncCandidate) == "table" and opts.syncCandidate or FindActiveSyncCandidate(memberKey)
    if type(candidate) ~= "table" then
      detail.skipReason = "missing_candidate"
      return requestedDomains, requestedSubdomains, detail
    end

    local comparison = string.lower(TrimText(candidate.comparison))
    if comparison == "different_lineage" or comparison == "unknown" or TrimText(candidate.profileId) == "" then
      detail.skipReason = comparison ~= "" and comparison or "unknown"
      return requestedDomains, requestedSubdomains, detail
    end

    local hostRepairDomains = CloneCheckpointDomainList(
      type(candidate.hostRepairDomains) == "table" and candidate.hostRepairDomains
        or type(candidate.effectiveHostRepairDomains) == "table" and candidate.effectiveHostRepairDomains
        or {}
    )
    local effectiveHostRepairDomains = CloneCheckpointDomainList(
      type(candidate.effectiveHostRepairDomains) == "table" and candidate.effectiveHostRepairDomains
        or type(candidate.hostRepairDomains) == "table" and candidate.hostRepairDomains
        or {}
    )
    local preciseScopeDomains = CloneCheckpointDomainList(type(candidate.preciseScopeDomains) == "table" and candidate.preciseScopeDomains or {})
    local preciseByDomain = type(candidate.preciseDifferentSubdomainsByDomain) == "table"
      and candidate.preciseDifferentSubdomainsByDomain
      or {}

    local effectiveDomains = {}
    local effectiveSubdomains = {}
    for _, requestedSubdomain in ipairs(requestedSubdomains) do
      local resolvedSubdomain = TrimText(requestedSubdomain)
      local parentDomain = type(profileSyncMetaOps.getSubdomainParentDomain) == "function"
        and string.lower(TrimText(profileSyncMetaOps.getSubdomainParentDomain(resolvedSubdomain)))
        or ""
      if parentDomain == "" then
        effectiveSubdomains[#effectiveSubdomains + 1] = resolvedSubdomain
      elseif not HasComparedDomain(hostRepairDomains, parentDomain) then
        detail.prunedSubdomains[#detail.prunedSubdomains + 1] = resolvedSubdomain
        detail.scopeTightened = true
      elseif HasComparedDomain(preciseScopeDomains, parentDomain) then
        local keepSubdomain = false
        for _, preciseSubdomain in ipairs(
          profileSyncMetaOps.preferSpecificLootRepairSubdomains(preciseByDomain[parentDomain] or {})
        ) do
          if string.lower(TrimText(preciseSubdomain)) == string.lower(resolvedSubdomain) then
            keepSubdomain = true
            break
          end
        end
        if keepSubdomain then
          effectiveSubdomains[#effectiveSubdomains + 1] = resolvedSubdomain
        else
          detail.prunedSubdomains[#detail.prunedSubdomains + 1] = resolvedSubdomain
          detail.scopeTightened = true
        end
      else
        effectiveSubdomains[#effectiveSubdomains + 1] = resolvedSubdomain
      end
    end

    for _, requestedDomain in ipairs(requestedDomains) do
      local resolvedDomain = string.lower(TrimText(requestedDomain))
      if resolvedDomain ~= "" then
        if not HasComparedDomain(hostRepairDomains, resolvedDomain) then
          detail.prunedDomains[#detail.prunedDomains + 1] = resolvedDomain
          detail.scopeTightened = true
        elseif HasComparedDomain(preciseScopeDomains, resolvedDomain) then
          local preciseSubdomains = profileSyncMetaOps.preferSpecificLootRepairSubdomains(
            preciseByDomain[resolvedDomain] or {}
          )
          if #preciseSubdomains > 0 then
            effectiveSubdomains = MergeCheckpointSubdomainLists(effectiveSubdomains, preciseSubdomains)
          else
            detail.prunedDomains[#detail.prunedDomains + 1] = resolvedDomain
          end
          detail.scopeTightened = true
        elseif HasComparedDomain(effectiveHostRepairDomains, resolvedDomain) then
          effectiveDomains[#effectiveDomains + 1] = resolvedDomain
        else
          detail.prunedDomains[#detail.prunedDomains + 1] = resolvedDomain
          detail.scopeTightened = true
        end
      end
    end

    detail.effectiveDomains = CloneCheckpointDomainList(effectiveDomains)
    detail.effectiveSubdomains = CloneCheckpointSubdomainList(effectiveSubdomains)
    if not detail.scopeTightened then
      detail.scopeTightened = not AreCheckpointScopeListsEqual(detail.requestedDomains, detail.effectiveDomains)
        or not AreCheckpointScopeListsEqual(detail.requestedSubdomains, detail.effectiveSubdomains)
    end
    if #detail.effectiveDomains == 0 and #detail.effectiveSubdomains == 0 then
      detail.skippedNoOp = true
      detail.skipReason = comparison == "same" and "aligned" or "scope_aligned"
    end

    return detail.effectiveDomains, detail.effectiveSubdomains, detail
  end

  local function BuildHostRepairDomainsForMember(memberKey, candidateOverride)
    local candidate = type(candidateOverride) == "table" and candidateOverride or FindActiveSyncCandidate(memberKey)
    local comparison = string.lower(TrimText(type(candidate) == "table" and candidate.comparison or ""))
    local candidateProfileId = TrimText(type(candidate) == "table" and candidate.profileId or "")
    if type(candidate) ~= "table" or comparison == "unknown" or candidateProfileId == "" then
      local activeSession, activeProfileName = GetActiveLootSession()
      local resolvedProfileName = TrimText(activeProfileName)
      local resolvedMemberKey = NormalizeCharacterKey(memberKey)
      local compareSummaries = type(deps.CompareProfileRevisionSummaries) == "function" and deps.CompareProfileRevisionSummaries or nil
      if type(activeSession) ~= "table"
        or TrimText(activeSession.id) == ""
        or resolvedProfileName == ""
        or resolvedMemberKey == ""
        or type(compareSummaries) ~= "function"
      then
        return nil, nil, true, "full"
      end

      local member = type(activeSession.members) == "table" and activeSession.members[resolvedMemberKey] or nil
      if type(member) ~= "table" and type(activeSession.members) == "table" then
        for storedMemberKey, storedMember in pairs(activeSession.members) do
          if AreCharacterKeysSame(storedMemberKey, resolvedMemberKey) and type(storedMember) == "table" then
            member = storedMember
            break
          end
        end
      end
      if type(member) ~= "table" then
        return nil, nil, true, "full"
      end

      local localProfileId = TrimText(select(1, deps.GetLootProfileId(resolvedProfileName)) or "")
      local remoteProfileId = TrimText(member.sharedProfileId)
      if localProfileId == "" or remoteProfileId == "" then
        return nil, nil, true, "full"
      end
      if string.lower(localProfileId) ~= string.lower(remoteProfileId) then
        return nil, nil, true, "full"
      end

      local localRevisionSummary = deps.NormalizeRevisionSummary(
        GetLootProfileRevisionSummary(resolvedProfileName),
        resolvedProfileName,
        localProfileId
      )
      local localLiveLootChecksum = profileSyncMetaOps.buildSessionLiveLootChecksum(
        resolvedProfileName,
        activeSession
      )
      local localArchiveLootChecksum = profileSyncMetaOps.buildSessionArchiveLootChecksum(
        resolvedProfileName,
        activeSession
      )
      localRevisionSummary.liveLootChecksum = localLiveLootChecksum
      localRevisionSummary.archiveLootChecksum = localArchiveLootChecksum

      local remoteRevisionSummary = deps.NormalizeRevisionSummary({
        profileName = resolvedProfileName,
        profileId = remoteProfileId,
        settings = tonumber(member.settingsRevision) or 0,
        permissions = tonumber(member.permissionsRevision) or 0,
        operational = tonumber(member.operationalRevision) or 0,
        loot = tonumber(member.lootRevision) or tonumber(member.operationalRevision) or 0,
        session = tonumber(member.sessionRevision) or tonumber(member.operationalRevision) or 0,
        settingsChecksum = TrimText(member.settingsChecksum),
        permissionsChecksum = TrimText(member.permissionsChecksum),
        operationalChecksum = TrimText(member.operationalChecksum),
        lootChecksum = TrimText(member.lootChecksum),
        sessionChecksum = TrimText(member.sessionChecksum),
        liveLootChecksum = TrimText(member.liveLootChecksum),
        archiveLootChecksum = TrimText(member.archiveLootChecksum),
        updatedAt = tonumber(member.profileUpdatedAt) or 0,
      }, resolvedProfileName, remoteProfileId)

      local remoteNewerDomains, localNewerDomains = compareSummaries(localRevisionSummary, remoteRevisionSummary)
      if localLiveLootChecksum ~= "" and TrimText(remoteRevisionSummary.liveLootChecksum) ~= ""
        and string.lower(localLiveLootChecksum) == string.lower(TrimText(remoteRevisionSummary.liveLootChecksum))
      then
        local remoteArchiveLootChecksum = TrimText(remoteRevisionSummary.archiveLootChecksum)
        local archiveOnlyLootDifference = localArchiveLootChecksum ~= ""
          and remoteArchiveLootChecksum ~= ""
          and string.lower(localArchiveLootChecksum) ~= string.lower(remoteArchiveLootChecksum)
        local filteredRemote = {}
        for _, domain in ipairs(remoteNewerDomains) do
          if string.lower(TrimText(domain)) ~= "loot" or not archiveOnlyLootDifference then
            filteredRemote[#filteredRemote + 1] = domain
          end
        end
        remoteNewerDomains = filteredRemote
        local filteredLocal = {}
        for _, domain in ipairs(localNewerDomains) do
          if string.lower(TrimText(domain)) ~= "loot" or not archiveOnlyLootDifference then
            filteredLocal[#filteredLocal + 1] = domain
          end
        end
        localNewerDomains = filteredLocal
      end

      local domains = {}
      for _, domain in ipairs(type(localNewerDomains) == "table" and localNewerDomains or {}) do
        if not HasComparedDomain(remoteNewerDomains, domain) then
          domains[#domains + 1] = string.lower(TrimText(domain))
        end
      end
      if #domains == 0 then
        return {}, {}, false, (#remoteNewerDomains > 0 and "member_newer" or "same")
      end

      local repairDomains, repairSubdomains = profileSyncMetaOps.buildAutomaticHostRepairScope(
        resolvedMemberKey,
        domains,
        activeSession.id,
        candidate
      )
      if #repairDomains == 0 and #repairSubdomains == 0 then
        repairDomains = CloneCheckpointDomainList(domains)
      end
      return repairDomains, repairSubdomains, false, #repairSubdomains > 0 and "inferred_precise" or "inferred_targeted"
    end
    if comparison == "same" then
      return {}, {}, false, "same"
    end
    if comparison == "different_lineage" then
      return nil, nil, true, "full"
    end
    local domains = {}
    for _, domain in ipairs(type(candidate.localNewerDomains) == "table" and candidate.localNewerDomains or {}) do
      if not HasComparedDomain(candidate.remoteNewerDomains, domain) then
        domains[#domains + 1] = string.lower(TrimText(domain))
      end
    end
    if #domains == 0 then
      return {}, {}, false, comparison == "remote_newer" and "member_newer" or "same"
    end
    local subdomains = {}
    if candidate.precisePushReady then
      for _, domain in ipairs(domains) do
        for _, subdomain in ipairs(
          profileSyncMetaOps.preferSpecificLootRepairSubdomains(
            type(candidate.preciseDifferentSubdomainsByDomain) == "table"
              and (candidate.preciseDifferentSubdomainsByDomain[domain] or {})
              or {}
          )
        ) do
          subdomains[#subdomains + 1] = subdomain
        end
      end
    end
    return domains, subdomains, false, #subdomains > 0 and "precise" or "targeted"
  end

  local function BuildMemberRepairRequestDomains(memberKey, previewOnly)
    local candidate = FindActiveSyncCandidate(memberKey)
    if type(candidate) ~= "table" then
      return nil, nil, "none"
    end
    local comparison = string.lower(TrimText(candidate.effectiveComparison ~= "" and candidate.effectiveComparison or candidate.comparison))
    if comparison == "different_lineage" or comparison == "unknown" or TrimText(candidate.profileId) == "" then
      return nil, nil, "full"
    end
    if previewOnly then
      local domains = MergeComparedDomains(
        type(candidate.effectiveRemoteNewerDomains) == "table" and candidate.effectiveRemoteNewerDomains or candidate.remoteNewerDomains,
        type(candidate.effectiveLocalNewerDomains) == "table" and candidate.effectiveLocalNewerDomains or candidate.localNewerDomains
      )
      local subdomains = {}
      if candidate.precisePreviewReady then
        for _, subdomain in ipairs(
          profileSyncMetaOps.preferSpecificLootRepairSubdomains(
            type(candidate.precisePreviewSubdomains) == "table" and candidate.precisePreviewSubdomains or {}
          )
        ) do
          subdomains[#subdomains + 1] = subdomain
        end
      end
      return #domains > 0 and domains or nil, #subdomains > 0 and subdomains or nil, #subdomains > 0 and "precise" or "targeted"
    end
    local domains = {}
    local remoteDomains = type(candidate.effectiveRemoteNewerDomains) == "table" and candidate.effectiveRemoteNewerDomains or candidate.remoteNewerDomains or {}
    local localDomains = type(candidate.effectiveLocalNewerDomains) == "table" and candidate.effectiveLocalNewerDomains or candidate.localNewerDomains or {}
    for _, domain in ipairs(remoteDomains) do
      if not HasComparedDomain(localDomains, domain) then
        domains[#domains + 1] = string.lower(TrimText(domain))
      end
    end
    local subdomains = {}
    if candidate.precisePullReady then
      for _, domain in ipairs(domains) do
        for _, subdomain in ipairs(
          profileSyncMetaOps.preferSpecificLootRepairSubdomains(
            type(candidate.preciseDifferentSubdomainsByDomain) == "table"
              and (candidate.preciseDifferentSubdomainsByDomain[domain] or {})
              or {}
          )
        ) do
          subdomains[#subdomains + 1] = subdomain
        end
      end
    end
    return #domains > 0 and domains or nil, #subdomains > 0 and subdomains or nil, #subdomains > 0 and "precise" or "targeted"
  end

  local function BuildDetailedComparisonRequestDomains(memberKey, opts)
    opts = type(opts) == "table" and opts or {}
    local candidate = FindActiveSyncCandidate(memberKey)
    if type(candidate) ~= "table" then
      return nil
    end
    local comparison = string.lower(TrimText(candidate.effectiveComparison ~= "" and candidate.effectiveComparison or candidate.comparison))
    if comparison == "same" or comparison == "different_lineage" or comparison == "unknown" or TrimText(candidate.profileId) == "" then
      return nil
    end
    if opts.preferHostRepair == true then
      local preferredDomains = CloneCheckpointDomainList(
        type(candidate.effectiveHostRepairDomains) == "table" and candidate.effectiveHostRepairDomains
          or type(candidate.hostRepairDomains) == "table" and candidate.hostRepairDomains
          or {}
      )
      local pendingJoinState = type(opts.pendingJoinState) == "table" and opts.pendingJoinState or nil
      if type(pendingJoinState) == "table" and pendingJoinState.kind == "join_manifest" then
        local pendingDomains = CloneCheckpointDomainList(type(pendingJoinState.domains) == "table" and pendingJoinState.domains or {})
        for _, subdomain in ipairs(type(pendingJoinState.subdomains) == "table" and pendingJoinState.subdomains or {}) do
          local parentDomain = type(profileSyncMetaOps.getSubdomainParentDomain) == "function"
            and string.lower(TrimText(profileSyncMetaOps.getSubdomainParentDomain(subdomain)))
            or ""
          if parentDomain ~= "" and not HasComparedDomain(pendingDomains, parentDomain) then
            pendingDomains[#pendingDomains + 1] = parentDomain
          end
        end
        if #pendingDomains > 0 then
          local narrowedDomains = {}
          for _, domain in ipairs(pendingDomains) do
            if #preferredDomains == 0 or HasComparedDomain(preferredDomains, domain) then
              narrowedDomains[#narrowedDomains + 1] = string.lower(TrimText(domain))
            end
          end
          if #narrowedDomains > 0 then
            preferredDomains = narrowedDomains
          end
        end
      end
      if #preferredDomains > 0 then
        return preferredDomains
      end
    end
    local domains = MergeComparedDomains(
      candidate.effectiveRemoteNewerDomains or candidate.remoteNewerDomains,
      candidate.effectiveLocalNewerDomains or candidate.localNewerDomains
    )
    return #domains > 0 and domains or nil
  end

  profileSyncMetaOps.resolveAutoDetailedComparisonScope = function(sessionId, memberKey)
    local resolvedSessionId = TrimText(sessionId)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    local candidate = FindActiveSyncCandidate(resolvedMemberKey)
    if resolvedSessionId == "" or resolvedMemberKey == "" or type(candidate) ~= "table" then
      return nil, nil, {}, {}
    end
    local pendingJoinState = type(profileSyncMetaOps.getPendingJoinManifestRepair) == "function"
      and profileSyncMetaOps.getPendingJoinManifestRepair(resolvedSessionId, resolvedMemberKey)
      or nil
    local requestDomains = CloneCheckpointDomainList(BuildDetailedComparisonRequestDomains(resolvedMemberKey, {
      preferHostRepair = pendingJoinState ~= nil,
      pendingJoinState = pendingJoinState,
    }))
    local initialRequestDomains = CloneCheckpointDomainList(requestDomains)
    if type(pendingJoinState) == "table" and #requestDomains > 0 then
      local narrowedDomains = {}
      local alreadyRequestedDomains = CloneCheckpointDomainList(pendingJoinState.requestedComparisonDomains)
      for _, domain in ipairs(requestDomains) do
        if not HasComparedDomain(alreadyRequestedDomains, domain) then
          narrowedDomains[#narrowedDomains + 1] = domain
        end
      end
      requestDomains = narrowedDomains
    else
      pendingJoinState = nil
    end
    if #requestDomains > 0 then
      local pendingBurstState = sessionRuntime.pendingAutoDetailedComparisonTimers[
        "auto_detail_timer|" .. string.lower(resolvedSessionId) .. "|" .. string.lower(resolvedMemberKey)
      ]
      if type(pendingBurstState) == "table" then
        local narrowedDomains = {}
        local queuedDomains = CloneCheckpointDomainList(pendingBurstState.requestDomains)
        for _, domain in ipairs(requestDomains) do
          if not HasComparedDomain(queuedDomains, domain) then
            narrowedDomains[#narrowedDomains + 1] = domain
          end
        end
        requestDomains = narrowedDomains
      end
    end
    return candidate, pendingJoinState, requestDomains, initialRequestDomains
  end

  local function HasLoadedDetailedComparisonDomains(candidate, domains)
    candidate = type(candidate) == "table" and candidate or {}
    if candidate.preciseDetailLoaded ~= true then
      return false
    end
    for _, domain in ipairs(type(domains) == "table" and domains or {}) do
      if not HasComparedDomain(candidate.preciseScopeDomains, domain) then
        return false
      end
    end
    return true
  end

  profileSyncMetaOps.pruneLoadedDetailedComparisonDomains = function(candidate, domains)
    local filteredDomains = {}
    local prunedLoaded = false
    candidate = type(candidate) == "table" and candidate or {}
    for _, domain in ipairs(type(domains) == "table" and domains or {}) do
      local resolvedDomain = string.lower(TrimText(domain))
      if resolvedDomain ~= "" then
        if candidate.preciseDetailLoaded == true and HasComparedDomain(candidate.preciseScopeDomains, resolvedDomain) then
          prunedLoaded = true
        else
          filteredDomains[#filteredDomains + 1] = resolvedDomain
        end
      end
    end
    return filteredDomains, prunedLoaded
  end

  local function BuildDetailedComparisonRequestStamp(sessionId, memberKey, domains)
    return string.lower(TrimText(sessionId)) .. "|"
      .. string.lower(NormalizeCharacterKey(memberKey)) .. "|"
      .. table.concat(MergeComparedDomains(domains), ",")
  end

  local function ResolveDetailedComparisonRequestContext(sessionId, memberKey, options)
    options = type(options) == "table" and options or {}
    local explicitDomains = CloneCheckpointDomainList(type(options.requestDomains) == "table" and options.requestDomains or {})
    local candidate = nil
    local pendingJoinState = nil
    local requestDomains = {}
    local initialRequestDomains = {}
    local prunedLoadedDomains = false

    if options.auto == true then
      candidate, pendingJoinState, requestDomains, initialRequestDomains =
        profileSyncMetaOps.resolveAutoDetailedComparisonScope(sessionId, memberKey)
      if #explicitDomains > 0 then
        initialRequestDomains = CloneCheckpointDomainList(MergeComparedDomains(initialRequestDomains, explicitDomains))
        requestDomains = CloneCheckpointDomainList(MergeComparedDomains(requestDomains, explicitDomains))
        if type(pendingJoinState) == "table" and pendingJoinState.kind == "join_manifest" then
          local narrowedDomains = {}
          local alreadyRequestedDomains = CloneCheckpointDomainList(pendingJoinState.requestedComparisonDomains)
          for _, domain in ipairs(requestDomains) do
            if not HasComparedDomain(alreadyRequestedDomains, domain) then
              narrowedDomains[#narrowedDomains + 1] = domain
            end
          end
          requestDomains = narrowedDomains
        end
      end
      if type(profileSyncMetaOps.pruneLoadedDetailedComparisonDomains) == "function" then
        requestDomains, prunedLoadedDomains = profileSyncMetaOps.pruneLoadedDetailedComparisonDomains(candidate, requestDomains)
      end
    else
      requestDomains = #explicitDomains > 0
        and CloneCheckpointDomainList(explicitDomains)
        or CloneCheckpointDomainList(BuildDetailedComparisonRequestDomains(memberKey))
      initialRequestDomains = CloneCheckpointDomainList(requestDomains)
    end

    return candidate, pendingJoinState, requestDomains, initialRequestDomains, prunedLoadedDomains
  end

  local function SendDetailedComparisonRequests(targets, options)
    options = type(options) == "table" and options or {}
    local activeSession, profileName = GetActiveLootSession()
    if not activeSession or not profileName then
      return 0, 0, 0, 0
    end

    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if not AreCharacterKeysSame(activeSession.host or "", selfKey) then
      return 0, 0, 0, 0
    end

    local requestedCount = 0
    local skippedAligned = 0
    local skippedLoaded = 0
    local skippedPending = 0
    local now = GetProfileCheckpointSyncTime()
    PruneAgedSessionRuntimeTracking(now)
    for _, memberKey in ipairs(type(targets) == "table" and targets or {}) do
      local resolvedMemberKey = NormalizeCharacterKey(memberKey)
      local explicitRequestDomains = type(options.requestDomainsByMember) == "table"
        and options.requestDomainsByMember[string.lower(resolvedMemberKey)]
        or nil
      local candidate = FindActiveSyncCandidate(memberKey)
      local pendingJoinState = nil
      local requestDomains = {}
      local initialRequestDomains = {}
      local prunedLoadedDomains = false
      candidate, pendingJoinState, requestDomains, initialRequestDomains, prunedLoadedDomains =
        ResolveDetailedComparisonRequestContext(activeSession.id, memberKey, {
          auto = options.auto == true,
          requestDomains = explicitRequestDomains,
        })
      if #requestDomains == 0 then
        if prunedLoadedDomains then
          skippedLoaded = skippedLoaded + 1
        elseif options.auto == true
          and type(pendingJoinState) == "table"
          and pendingJoinState.kind == "join_manifest"
          and #initialRequestDomains > 0
        then
          skippedPending = skippedPending + 1
        else
          skippedAligned = skippedAligned + 1
        end
      elseif options.force ~= true and HasLoadedDetailedComparisonDomains(candidate, requestDomains) then
        skippedLoaded = skippedLoaded + 1
      else
        local requestStamp = BuildDetailedComparisonRequestStamp(activeSession.id, memberKey, requestDomains)
        local lastRequestedAt = tonumber(sessionRuntime.recentAutoSubcheckRequestTimes[requestStamp]) or 0
        local allowRetry = options.force == true or (now - lastRequestedAt) >= sessionConfig.profileSyncAutoSubcheckDedupeSeconds
        if allowRetry then
          local sentCount = type(profileSyncMetaOps.sendSubchecksumRequests) == "function"
            and profileSyncMetaOps.sendSubchecksumRequests(memberKey, requestDomains, {
              force = options.force == true,
              auto = options.auto == true,
            })
            or 0
          if sentCount > 0 then
            sessionRuntime.recentAutoSubcheckRequestTimes[requestStamp] = now
            if type(pendingJoinState) == "table" and pendingJoinState.kind == "join_manifest" then
              pendingJoinState.requestedComparisonDomains = CloneCheckpointDomainList(
                MergeComparedDomains(pendingJoinState.requestedComparisonDomains, requestDomains)
              )
              pendingJoinState.updatedAt = GetProfileCheckpointSyncTime()
            end
            requestedCount = requestedCount + 1
          end
        else
          if options.auto == true
            and type(pendingJoinState) == "table"
            and pendingJoinState.kind == "join_manifest"
          then
            skippedPending = skippedPending + 1
          else
            skippedLoaded = skippedLoaded + 1
          end
        end
      end
    end
    return requestedCount, skippedAligned, skippedLoaded, skippedPending
  end

  profileSyncMetaOps.resolveMemberBackgroundSyncBurstDelay = function(pendingTimerCount, overrides)
    overrides = type(overrides) == "table" and overrides or {}
    local baseDelay = math.max(0, tonumber(overrides.baseDelaySeconds)
      or tonumber(sessionConfig.memberBackgroundSyncBurstDelaySeconds) or 0.35)
    local staggerDelay = math.max(0, tonumber(overrides.staggerSeconds)
      or tonumber(sessionConfig.memberBackgroundSyncBurstStaggerSeconds) or 0.25)
    local maxStagger = math.max(0, tonumber(overrides.maxStaggerSeconds)
      or tonumber(sessionConfig.memberBackgroundSyncBurstMaxStaggerSeconds) or 5.0)
    return baseDelay + math.min(maxStagger, math.max(0, tonumber(pendingTimerCount) or 0) * staggerDelay)
  end
  INTERNAL_API.LIDCOUNCIL_ResolveMemberBackgroundSyncBurstDelay_Impl =
    profileSyncMetaOps.resolveMemberBackgroundSyncBurstDelay

  profileSyncMetaOps.queueMemberBackgroundSyncBurst = function(activeSession, profileName, sessionId, memberKey, opts)
    opts = type(opts) == "table" and opts or {}
    activeSession = type(activeSession) == "table" and activeSession or nil
    local resolvedProfileName = TrimText(profileName)
    local resolvedSessionId = FirstNonEmptyText(sessionId, type(activeSession) == "table" and activeSession.id or "")
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if type(activeSession) ~= "table"
      or resolvedProfileName == ""
      or resolvedSessionId == ""
      or resolvedMemberKey == ""
    then
      return false
    end

    local now = GetProfileCheckpointSyncTime()
    PruneAgedSessionRuntimeTracking(now)
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if selfKey == ""
      or not AreCharacterKeysSame(activeSession.host or "", selfKey)
      or TrimText(activeSession.id) ~= resolvedSessionId
    then
      return false
    end

    local requestDomains = CloneCheckpointDomainList(type(opts.requestDomains) == "table" and opts.requestDomains or {})
    local prewarmDomains = CloneCheckpointDomainList(type(opts.prewarmDomains) == "table" and opts.prewarmDomains or {})
    local prewarmSubdomains = CloneCheckpointSubdomainList(type(opts.prewarmSubdomains) == "table" and opts.prewarmSubdomains or {})
    local queuePrewarm = opts.queuePrewarm == true
    if #requestDomains == 0 and not queuePrewarm then
      return false
    end

    local pendingKey = "auto_detail_timer|" .. string.lower(resolvedSessionId) .. "|" .. string.lower(resolvedMemberKey)
    local pendingState = sessionRuntime.pendingAutoDetailedComparisonTimers[pendingKey]
    if type(pendingState) == "table" then
      local pendingQueuedAt = math.max(0, tonumber(pendingState.updatedAt or pendingState.queuedAt) or 0)
      if pendingQueuedAt <= 0
        or (now - pendingQueuedAt) >= sessionConfig.autoDetailedComparisonTimerRetentionSeconds
      then
        sessionRuntime.pendingAutoDetailedComparisonTimers[pendingKey] = nil
        pendingState = nil
      end
    end
    if type(pendingState) == "table" then
      pendingState.profileName = resolvedProfileName
      pendingState.sessionId = resolvedSessionId
      pendingState.memberKey = resolvedMemberKey
      pendingState.updatedAt = now
      if #requestDomains > 0 then
        pendingState.requestDomains = CloneCheckpointDomainList(
          MergeComparedDomains(pendingState.requestDomains, requestDomains)
        )
      end
      if queuePrewarm then
        pendingState.prewarmDomains = CloneCheckpointDomainList(
          MergeComparedDomains(pendingState.prewarmDomains, prewarmDomains)
        )
        pendingState.prewarmSubdomains = CloneCheckpointSubdomainList(
          MergeCheckpointSubdomainLists(pendingState.prewarmSubdomains, prewarmSubdomains)
        )
        pendingState.prewarmForce = pendingState.prewarmForce == true or opts.prewarmForce == true
        if TrimText(pendingState.prewarmReason) == "" then
          pendingState.prewarmReason = TrimText(opts.prewarmReason)
        end
      end
      if type(RecordProfileSyncDecision) == "function" then
        RecordProfileSyncDecision("queue_background_member_sync", {
          action = "coalesced_pending",
          sessionId = resolvedSessionId,
          profileName = resolvedProfileName,
          reason = FirstNonEmptyText(opts.prewarmReason, opts.reason),
          target = resolvedMemberKey,
          targetCount = 1,
          queuedCount = (#requestDomains > 0 and 1 or 0) + (queuePrewarm and 1 or 0),
          requestedDomains = CloneCheckpointDomainList(MergeComparedDomains(requestDomains, prewarmDomains)),
          requestedSubdomains = CloneCheckpointSubdomainList(prewarmSubdomains),
        })
      end
      return true
    end

    local pendingTimerCount = 0
    for _, queuedTimer in pairs(sessionRuntime.pendingAutoDetailedComparisonTimers) do
      if type(queuedTimer) == "table" and TrimText(queuedTimer.sessionId) == resolvedSessionId then
        pendingTimerCount = pendingTimerCount + 1
      end
    end
    local scheduledDelaySeconds = type(profileSyncMetaOps.resolveMemberBackgroundSyncBurstDelay) == "function"
      and profileSyncMetaOps.resolveMemberBackgroundSyncBurstDelay(pendingTimerCount)
      or sessionConfig.memberBackgroundSyncBurstDelaySeconds
    local token = string.format("ADCR-%d-%d", tonumber(time and time() or 0) or 0, math.random(1000, 9999))
    sessionRuntime.pendingAutoDetailedComparisonTimers[pendingKey] = {
      token = token,
      sessionId = resolvedSessionId,
      profileName = resolvedProfileName,
      memberKey = resolvedMemberKey,
      requestDomains = CloneCheckpointDomainList(requestDomains),
      prewarmDomains = CloneCheckpointDomainList(prewarmDomains),
      prewarmSubdomains = CloneCheckpointSubdomainList(prewarmSubdomains),
      prewarmForce = opts.prewarmForce == true,
      prewarmReason = TrimText(opts.prewarmReason),
      reason = TrimText(opts.reason),
      scheduledDelaySeconds = scheduledDelaySeconds,
      queuedAt = now,
      updatedAt = now,
    }
    local function RunAutoRequest()
      local currentPending = sessionRuntime.pendingAutoDetailedComparisonTimers[pendingKey]
      if type(currentPending) ~= "table" or currentPending.token ~= token then
        return
      end
      sessionRuntime.pendingAutoDetailedComparisonTimers[pendingKey] = nil
      local currentSession, currentProfileName = GetActiveLootSession()
      local currentSelfKey = NormalizeCharacterKey(GetCharacterKey() or "")
      if not currentSession
        or not currentProfileName
        or not AreCharacterKeysSame(currentSession.host or "", currentSelfKey)
        or not DoesActiveSessionMatch(currentSession, currentProfileName, currentPending.sessionId, currentPending.profileName)
      then
        return
      end
      if (#(currentPending.prewarmDomains or {}) > 0
          or #(currentPending.prewarmSubdomains or {}) > 0
          or currentPending.prewarmForce == true)
      then
        PrewarmMemberPreciseLiveSyncState(
          currentSession,
          currentPending.profileName,
          currentPending.sessionId,
          currentPending.memberKey,
          {
            mode = "BACKGROUND",
            reason = FirstNonEmptyText(currentPending.prewarmReason, "profile_state"),
            force = currentPending.prewarmForce == true,
            domains = CloneCheckpointDomainList(currentPending.prewarmDomains),
            subdomains = CloneCheckpointSubdomainList(currentPending.prewarmSubdomains),
          }
        )
      end
      if #(currentPending.requestDomains or {}) > 0 then
        SendDetailedComparisonRequests({ currentPending.memberKey }, {
          auto = true,
          requestDomainsByMember = {
            [string.lower(currentPending.memberKey)] = CloneCheckpointDomainList(currentPending.requestDomains),
          },
        })
      end
    end
    if type(Compat) == "table" and type(Compat.After) == "function" then
      Compat.After(scheduledDelaySeconds, RunAutoRequest)
    else
      RunAutoRequest()
    end
    if type(RecordProfileSyncDecision) == "function" then
      RecordProfileSyncDecision("queue_background_member_sync", {
        action = "queued",
        sessionId = resolvedSessionId,
        profileName = resolvedProfileName,
        reason = FirstNonEmptyText(opts.prewarmReason, opts.reason),
        target = resolvedMemberKey,
        targetCount = 1,
        queuedCount = (#requestDomains > 0 and 1 or 0) + (queuePrewarm and 1 or 0),
        requestedDomains = CloneCheckpointDomainList(MergeComparedDomains(requestDomains, prewarmDomains)),
        requestedSubdomains = CloneCheckpointSubdomainList(prewarmSubdomains),
        scheduledDelaySeconds = scheduledDelaySeconds,
      })
    end
    return true
  end

  local function QueueAutoDetailedComparison(memberKey, reason)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if resolvedMemberKey == "" then
      return
    end
    PruneAgedSessionRuntimeTracking(GetProfileCheckpointSyncTime())
    local activeSession, profileName = GetActiveLootSession()
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if not activeSession
      or not profileName
      or not AreCharacterKeysSame(activeSession.host or "", selfKey)
    then
      return
    end
    local candidate, _, requestDomains = ResolveDetailedComparisonRequestContext(activeSession.id, resolvedMemberKey, {
      auto = true,
    })
    if #requestDomains == 0 or HasLoadedDetailedComparisonDomains(candidate, requestDomains) then
      return
    end
    if type(profileSyncMetaOps.queueMemberBackgroundSyncBurst) == "function" then
      profileSyncMetaOps.queueMemberBackgroundSyncBurst(activeSession, profileName, activeSession.id, resolvedMemberKey, {
        requestDomains = requestDomains,
        reason = TrimText(reason),
      })
    end
  end

  local function QueuePostBootstrapLiveRevalidation(profileName, sessionId, memberKey)
    local resolvedProfileName = TrimText(profileName)
    local resolvedSessionId = TrimText(sessionId)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if resolvedProfileName == "" or resolvedSessionId == "" or resolvedMemberKey == "" then
      return false
    end
    local now = GetProfileCheckpointSyncTime()
    PruneAgedSessionRuntimeTracking(now)
    local pendingKey = "post_bootstrap_revalidation|" .. string.lower(resolvedSessionId) .. "|" .. string.lower(resolvedMemberKey)
    local pendingState = sessionRuntime.pendingPostBootstrapRevalidationTimers[pendingKey]
    if type(pendingState) == "table" then
      local pendingQueuedAt = math.max(0, tonumber(pendingState.updatedAt or pendingState.queuedAt) or 0)
      if pendingQueuedAt <= 0
        or (now - pendingQueuedAt) >= sessionConfig.autoDetailedComparisonTimerRetentionSeconds
      then
        sessionRuntime.pendingPostBootstrapRevalidationTimers[pendingKey] = nil
        pendingState = nil
      end
    end
    if type(pendingState) == "table"
      and TrimText(pendingState.profileName) == resolvedProfileName
      and TrimText(pendingState.sessionId) == resolvedSessionId
      and NormalizeCharacterKey(pendingState.memberKey) == resolvedMemberKey
      and TrimText(pendingState.token) ~= ""
    then
      pendingState.updatedAt = now
      return true
    end

    local token = string.format("PBR-%d-%d", tonumber(time and time() or 0) or 0, math.random(1000, 9999))
    sessionRuntime.pendingPostBootstrapRevalidationTimers[pendingKey] = {
      token = token,
      queuedAt = now,
      updatedAt = now,
      profileName = resolvedProfileName,
      sessionId = resolvedSessionId,
      memberKey = resolvedMemberKey,
    }

    local function RunPostBootstrapRevalidation()
      local currentPending = sessionRuntime.pendingPostBootstrapRevalidationTimers[pendingKey]
      if type(currentPending) ~= "table" or TrimText(currentPending.token) ~= token then
        return
      end
      sessionRuntime.pendingPostBootstrapRevalidationTimers[pendingKey] = nil

      local activeSession, activeProfileName = GetActiveLootSession()
      local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
      if not activeSession
        or not DoesActiveSessionMatch(activeSession, activeProfileName, resolvedSessionId, resolvedProfileName)
        or not AreCharacterKeysSame(activeSession.host or "", selfKey)
        or not IsJoinedSessionCharacter(activeSession, resolvedMemberKey)
      then
        return
      end

      if type(profileSyncMetaOps.queueMemberBackgroundSyncBurst) == "function" then
        profileSyncMetaOps.queueMemberBackgroundSyncBurst(activeSession, resolvedProfileName, resolvedSessionId, resolvedMemberKey, {
          queuePrewarm = true,
          prewarmReason = "post_bootstrap_prewarm",
          prewarmForce = true,
        })
      else
        PrewarmMemberPreciseLiveSyncState(activeSession, resolvedProfileName, resolvedSessionId, resolvedMemberKey, {
          mode = "BACKGROUND",
          reason = "post_bootstrap_prewarm",
          force = true,
        })
      end

      local candidate = FindActiveSyncCandidate(resolvedMemberKey)
      if type(candidate) ~= "table" then
        return
      end

      local comparison = string.lower(TrimText(candidate.effectiveComparison ~= "" and candidate.effectiveComparison or candidate.comparison))
      if comparison == "same" or comparison == "different_lineage" or comparison == "unknown" then
        return
      end

      local requestSubdomains = {}
      local requestDomains = CloneCheckpointDomainList(
        type(candidate.effectiveHostRepairDomains) == "table" and candidate.effectiveHostRepairDomains
          or type(candidate.hostRepairDomains) == "table" and candidate.hostRepairDomains
          or {}
      )
      if candidate.precisePushReady then
        for _, domain in ipairs(requestDomains) do
          for _, subdomain in ipairs(profileSyncMetaOps.preferSpecificLootRepairSubdomains(
            type(candidate.preciseDifferentSubdomainsByDomain) == "table"
              and (candidate.preciseDifferentSubdomainsByDomain[domain] or {})
              or {}
          )) do
            requestSubdomains[#requestSubdomains + 1] = subdomain
          end
        end
      end
      if #requestDomains == 0 and #requestSubdomains == 0 then
        return
      end

      QueueAutoDetailedComparison(resolvedMemberKey, "post_bootstrap_state")
      ScheduleDeferredJoinManifestRepair(
        resolvedProfileName,
        resolvedSessionId,
        resolvedMemberKey,
        requestDomains,
        requestSubdomains
      )
    end

    if type(Compat) == "table" and type(Compat.After) == "function" then
      Compat.After(sessionConfig.memberBackgroundSyncBurstDelaySeconds, RunPostBootstrapRevalidation)
    else
      RunPostBootstrapRevalidation()
    end
    return true
  end

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

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

  local function BuildProfileDeltaId()
    return string.format("PD-%d-%d", tonumber(time and time() or 0) or 0, math.random(1000, 9999))
  end

  local function MarkProfileDeltaSeen(changeId, sessionId)
    local resolvedId = TrimText(changeId)
    if resolvedId ~= "" then
      sessionRuntime.appliedProfileDeltaIds[resolvedId] = {
        sessionId = TrimText(sessionId),
        seenAt = GetProfileCheckpointSyncTime(),
      }
    end
  end

  local function HasProfileDeltaSeen(changeId)
    local resolvedId = TrimText(changeId)
    if resolvedId == "" then
      return false
    end
    local seenState = sessionRuntime.appliedProfileDeltaIds[resolvedId]
    if type(seenState) ~= "table" then
      sessionRuntime.appliedProfileDeltaIds[resolvedId] = nil
      return false
    end
    local now = GetProfileCheckpointSyncTime()
    local seenAt = math.max(0, tonumber(seenState.seenAt) or 0)
    if seenAt <= 0 or (now - seenAt) >= sessionConfig.profileDeltaSeenRetentionSeconds then
      sessionRuntime.appliedProfileDeltaIds[resolvedId] = nil
      return false
    end
    PruneAgedSessionRuntimeTracking(now)
    return true
  end

  local function GetProfileDeltaRuntimeKey(sessionId, profileId, profileName)
    local resolvedSessionId = TrimText(sessionId)
    local resolvedProfileId = TrimText(profileId)
    local resolvedProfileName = TrimText(profileName)
    return resolvedSessionId .. ":" .. (resolvedProfileId ~= "" and resolvedProfileId or resolvedProfileName)
  end

  local function NextHostProfileDeltaSequence(activeSession)
    if type(activeSession) ~= "table" then
      return 0
    end
    activeSession.profileDeltaSequence = math.max(0, tonumber(activeSession.profileDeltaSequence) or 0) + 1
    return activeSession.profileDeltaSequence
  end

  local function RememberProfileDeltaSequence(delta)
    if type(delta) ~= "table" or tonumber(delta.sequence) == nil or tonumber(delta.sequence) <= 0 then
      return
    end
    local runtimeKey = GetProfileDeltaRuntimeKey(delta.sessionId, delta.profileId, delta.profileName)
    local currentSequence = tonumber(delta.sequence) or 0
    local lastState = sessionRuntime.profileDeltaLastSequence[runtimeKey]
    local lastSequence = type(lastState) == "table"
      and (tonumber(lastState.sequence) or 0)
      or (tonumber(lastState) or 0)
    sessionRuntime.profileDeltaLastSequence[runtimeKey] = {
      sequence = math.max(lastSequence, currentSequence),
      updatedAt = GetProfileCheckpointSyncTime(),
    }
  end

  local function IsProfileDeltaSequenceGap(delta)
    if type(delta) ~= "table" or tonumber(delta.sequence) == nil or tonumber(delta.sequence) <= 0 then
      return false
    end
    local runtimeKey = GetProfileDeltaRuntimeKey(delta.sessionId, delta.profileId, delta.profileName)
    local sequenceState = sessionRuntime.profileDeltaLastSequence[runtimeKey]
    local now = GetProfileCheckpointSyncTime()
    if type(sequenceState) == "table" then
      local updatedAt = math.max(0, tonumber(sequenceState.updatedAt) or 0)
      if updatedAt <= 0 or (now - updatedAt) >= sessionConfig.profileDeltaSequenceRetentionSeconds then
        sessionRuntime.profileDeltaLastSequence[runtimeKey] = nil
        return false
      end
    end
    local lastSequence = type(sequenceState) == "table"
      and (tonumber(sequenceState.sequence) or 0)
      or (tonumber(sequenceState) or 0)
    return lastSequence > 0 and tonumber(delta.sequence) > (lastSequence + 1)
  end

  local function IsProfileDeltaSequenceStale(delta)
    if type(delta) ~= "table" or tonumber(delta.sequence) == nil or tonumber(delta.sequence) <= 0 then
      return false
    end
    local runtimeKey = GetProfileDeltaRuntimeKey(delta.sessionId, delta.profileId, delta.profileName)
    local sequenceState = sessionRuntime.profileDeltaLastSequence[runtimeKey]
    local now = GetProfileCheckpointSyncTime()
    if type(sequenceState) == "table" then
      local updatedAt = math.max(0, tonumber(sequenceState.updatedAt) or 0)
      if updatedAt <= 0 or (now - updatedAt) >= sessionConfig.profileDeltaSequenceRetentionSeconds then
        sessionRuntime.profileDeltaLastSequence[runtimeKey] = nil
        return false
      end
    end
    local lastSequence = type(sequenceState) == "table"
      and (tonumber(sequenceState.sequence) or 0)
      or (tonumber(sequenceState) or 0)
    return lastSequence > 0 and tonumber(delta.sequence) <= lastSequence
  end

  local function SendProfileDelta(kind, distribution, target, activeSession, profileName, delta, revisionSummary)
    if type(SendComm) ~= "function" or type(activeSession) ~= "table" or type(delta) ~= "table" then
      return false
    end
    revisionSummary = type(revisionSummary) == "table" and revisionSummary or GetLootProfileRevisionSummary(profileName)
    if TrimText(kind) == "PDELTA" and (tonumber(delta.sequence) or 0) <= 0 then
      delta.sequence = NextHostProfileDeltaSequence(activeSession)
    end
    local args = type(delta.args) == "table" and delta.args or {}
    local deltaArgs = {
      TrimText(activeSession.id),
      TrimText(profileName),
      TrimText(delta.profileId),
      TrimText(delta.changeId),
      NormalizeCharacterKey(delta.actor),
      TrimText(delta.domain),
      TrimText(delta.action),
      tostring(tonumber(revisionSummary.settings) or 0),
      tostring(tonumber(revisionSummary.permissions) or 0),
      tostring(tonumber(revisionSummary.operational) or 0),
      tostring(tonumber(revisionSummary.updatedAt) or 0),
      tostring(tonumber(delta.sequence) or 0),
      TrimText(revisionSummary.settingsChecksum),
      TrimText(revisionSummary.permissionsChecksum),
      TrimText(revisionSummary.operationalChecksum),
    }
    for index = 1, #args do
      deltaArgs[#deltaArgs + 1] = args[index]
    end
    if type(profileSyncMetaOps.validateCommPayload) == "function" then
      local payloadSafe, payloadReason, payloadBytes = profileSyncMetaOps.validateCommPayload(kind, unpack(deltaArgs))
      if payloadSafe and TrimText(kind) == "PDELTA"
        and payloadBytes > sessionConfig.profileDeltaPayloadTargetBytes
      then
        payloadSafe = false
        payloadReason = "profile_delta_snapshot_fallback_required"
      end
      if not payloadSafe then
        -- Revision numbers and the delta body are authoritative.  Checksum fields
        -- are diagnostic only, so omit them before falling back to a larger repair.
        deltaArgs[13] = ""
        deltaArgs[14] = ""
        deltaArgs[15] = ""
        payloadSafe, payloadReason, payloadBytes = profileSyncMetaOps.validateCommPayload(kind, unpack(deltaArgs))
        if payloadSafe and TrimText(kind) == "PDELTA"
          and payloadBytes > sessionConfig.profileDeltaPayloadTargetBytes
        then
          payloadSafe = false
          payloadReason = "profile_delta_snapshot_fallback_required"
        end
      end
      if not payloadSafe then
        local isProfileDelta = TrimText(kind) == "PDELTA"
        local requiresSnapshotFallback = isProfileDelta and (
          TrimText(payloadReason) == "profile_delta_snapshot_fallback_required"
          or TrimText(payloadReason) == "comm_payload_exceeds_safe_limit"
        )
        if not requiresSnapshotFallback and type(profileSyncMetaOps.recordOutboundPayloadReject) == "function" then
          profileSyncMetaOps.recordOutboundPayloadReject(kind, payloadReason, payloadBytes, {
            sessionId = activeSession.id,
            target = target,
          })
        end
        if type(RecordProfileSyncDecision) == "function" then
          RecordProfileSyncDecision("send_profile_delta", {
            action = requiresSnapshotFallback and "snapshot_fallback_required" or "failed",
            opcode = TrimText(kind),
            sessionId = TrimText(activeSession.id),
            profileName = TrimText(profileName),
            target = NormalizeCharacterKey(target),
            domain = TrimText(delta.domain),
            deltaAction = TrimText(delta.action),
            reason = TrimText(payloadReason),
            error = requiresSnapshotFallback
              and "Profile delta will use the chunked snapshot fallback."
              or "Profile delta exceeds the safe addon-message limit.",
          })
        end
        if requiresSnapshotFallback then
          return false, "Profile delta requires snapshot fallback."
        end
        return false, "Profile delta exceeds the safe addon-message limit."
      end
    end
    return SendComm(kind, distribution, target, unpack(deltaArgs))
  end

  profileSyncMetaOps.buildProfileDeltaDeliveryPolicy = function(sent, sendError)
    local deltaSent = sent == true
    return {
      deltaSent = deltaSent,
      trackAcks = deltaSent,
      forceSnapshotFallback = not deltaSent,
      -- A member's advertised profile proof must describe data that member has
      -- actually applied. The host may apply a requested edit immediately,
      -- but it must not promote the requesting member to the combined host
      -- revision until PDELTA_ACK (or a snapshot receipt) arrives.
      advanceMemberProof = false,
      error = TrimText(sendError),
    }
  end

  profileSyncMetaOps.isProfileDeltaSnapshotFallbackReason = function(reason)
    local resolved = string.lower(TrimText(reason))
    return resolved == "delta_fallback"
      or resolved == "delta_payload_fallback"
      or resolved == "profile_delta_snapshot_fallback"
  end

  INTERNAL_API.LIDCOUNCIL_BuildProfileDeltaDeliveryPolicy_Impl = profileSyncMetaOps.buildProfileDeltaDeliveryPolicy
  INTERNAL_API.LIDCOUNCIL_IsProfileDeltaSnapshotFallbackReason_Impl = profileSyncMetaOps.isProfileDeltaSnapshotFallbackReason

  INTERNAL_API.LIDCOUNCIL_RunProfileDeltaDeliveryPolicyValidation_Impl = function()
    local checks = {}
    local passed = 0
    local function AddCheck(name, condition)
      local checkPassed = condition == true
      checks[#checks + 1] = {
        name = name,
        passed = checkPassed,
      }
      if checkPassed then
        passed = passed + 1
      end
    end

    local delivered = profileSyncMetaOps.buildProfileDeltaDeliveryPolicy(true, nil)
    AddCheck("delivered profile delta waits for an acknowledgement before member proof advances",
      delivered.trackAcks == true and delivered.advanceMemberProof == false)
    AddCheck("delivered profile delta does not queue a redundant snapshot fallback",
      delivered.forceSnapshotFallback == false)

    local oversized = profileSyncMetaOps.buildProfileDeltaDeliveryPolicy(false, "Profile delta requires snapshot fallback.")
    AddCheck("oversized profile delta forces the chunked snapshot fallback",
      oversized.forceSnapshotFallback == true and oversized.trackAcks == false)
    AddCheck("snapshot fallback cannot optimistically promote the requesting member proof",
      oversized.advanceMemberProof == false)
    AddCheck("profile delta fallback reason bypasses aligned-candidate pruning",
      profileSyncMetaOps.isProfileDeltaSnapshotFallbackReason("delta_payload_fallback") == true
        and profileSyncMetaOps.isProfileDeltaSnapshotFallbackReason("manual_refresh") == false)

    local fixtureMemberRevision = 7
    local combinedHostRevision = 9
    if delivered.advanceMemberProof then
      fixtureMemberRevision = combinedHostRevision
    end
    AddCheck("member proof remains at its last confirmed revision before ACK",
      fixtureMemberRevision == 7)
    fixtureMemberRevision = combinedHostRevision -- simulated PDELTA_ACK application
    AddCheck("member proof advances when the applied acknowledgement arrives",
      fixtureMemberRevision == 9)

    return passed == #checks, {
      total = #checks,
      passed = passed,
      failed = #checks - passed,
      checks = checks,
    }
  end

  local function SendProfileDeltaAck(activeSession, profileName, delta, revisionSummary, ackPhase)
    if type(activeSession) ~= "table" or type(delta) ~= "table" or type(SendComm) ~= "function" then
      return false
    end
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    local hostKey = NormalizeCharacterKey(activeSession.host or "")
    if selfKey == "" or hostKey == "" or AreCharacterKeysSame(selfKey, hostKey) then
      return false
    end
    revisionSummary = type(revisionSummary) == "table" and revisionSummary or GetLootProfileRevisionSummary(profileName)
    local resolvedAckPhase = type(INTERNAL_API.LIDCOUNCIL_NormalizeCombatSyncAckPhase_Impl) == "function"
      and INTERNAL_API.LIDCOUNCIL_NormalizeCombatSyncAckPhase_Impl(ackPhase)
      or (TrimText(ackPhase) == "" and "APPLIED" or string.upper(TrimText(ackPhase)))
    if resolvedAckPhase == "" then
      return false, "Invalid profile delta acknowledgement phase."
    end
    local ackArgs = {
      TrimText(activeSession.id),
      TrimText(profileName),
      TrimText(delta.changeId),
      selfKey,
      tostring(tonumber(delta.sequence) or 0),
      tostring(tonumber(revisionSummary.settings) or 0),
      tostring(tonumber(revisionSummary.permissions) or 0),
      tostring(tonumber(revisionSummary.operational) or 0),
      tostring(tonumber(revisionSummary.updatedAt) or 0),
      TrimText(revisionSummary.settingsChecksum),
      TrimText(revisionSummary.permissionsChecksum),
      TrimText(revisionSummary.operationalChecksum),
      tostring(tonumber(revisionSummary.loot) or tonumber(revisionSummary.operational) or 0),
      tostring(tonumber(revisionSummary.session) or tonumber(revisionSummary.operational) or 0),
      TrimText(revisionSummary.lootChecksum),
      TrimText(revisionSummary.sessionChecksum),
      resolvedAckPhase
    }
    if type(profileSyncMetaOps.validateCommPayload) == "function" then
      local payloadSafe, payloadReason, payloadBytes = profileSyncMetaOps.validateCommPayload("PDELTA_ACK", unpack(ackArgs))
      if not payloadSafe then
        -- The receiver falls back to operational checksums for these optional fields.
        ackArgs[15] = ""
        ackArgs[16] = ""
        payloadSafe, payloadReason, payloadBytes = profileSyncMetaOps.validateCommPayload("PDELTA_ACK", unpack(ackArgs))
      end
      if not payloadSafe then
        -- Revisions and ACK phase are authoritative; checksum strings are diagnostics.
        ackArgs[10] = ""
        ackArgs[11] = ""
        ackArgs[12] = ""
        payloadSafe, payloadReason, payloadBytes = profileSyncMetaOps.validateCommPayload("PDELTA_ACK", unpack(ackArgs))
      end
      if not payloadSafe then
        if type(profileSyncMetaOps.recordOutboundPayloadReject) == "function" then
          profileSyncMetaOps.recordOutboundPayloadReject("PDELTA_ACK", payloadReason, payloadBytes, {
            sessionId = activeSession.id,
            target = hostKey,
          })
        end
        if type(RecordProfileSyncDecision) == "function" then
          RecordProfileSyncDecision("send_profile_delta_ack", {
            action = "failed",
            sessionId = TrimText(activeSession.id),
            profileName = TrimText(profileName),
            target = hostKey,
            changeId = TrimText(delta.changeId),
            reason = TrimText(payloadReason),
            error = "Profile delta acknowledgement exceeds the safe addon-message limit.",
          })
        end
        return false, "Profile delta acknowledgement exceeds the safe addon-message limit."
      end
    end
    return SendComm("PDELTA_ACK", "WHISPER", hostKey, unpack(ackArgs))
  end

  profileSyncMetaOps.buildCombatProfileBarrierKey = function(delta, sender)
    delta = type(delta) == "table" and delta or {}
    return table.concat({
      string.lower(TrimText(delta.sessionId)),
      string.lower(TrimText(delta.profileId) ~= "" and TrimText(delta.profileId) or TrimText(delta.profileName)),
      string.lower(profileSyncMetaOps.normalizeSenderKey(sender)),
    }, "\31")
  end

  profileSyncMetaOps.stageInboundProfileDeltaIfCombat = function(opcode, fields, sender, delta, activeSession, localProfileName)
    local resolvedOpcode = string.upper(TrimText(opcode))
    local decision = type(INTERNAL_API.LIDCOUNCIL_ResolveCombatSyncDecision_Impl) == "function"
      and INTERNAL_API.LIDCOUNCIL_ResolveCombatSyncDecision_Impl(resolvedOpcode)
      or nil
    if type(decision) ~= "table" or decision.stageData ~= true then
      return false
    end

    local queueEntry = type(INTERNAL_API.LIDCOUNCIL_QueueCombatSyncInboxEntry_Impl) == "function"
      and INTERNAL_API.LIDCOUNCIL_QueueCombatSyncInboxEntry_Impl
      or nil
    if type(queueEntry) ~= "function" then
      profileSyncMetaOps.recordInboundPayloadReject(
        resolvedOpcode,
        sender,
        fields,
        "combat_inbox_unavailable",
        type(delta) == "table" and delta.sessionId or nil
      )
      return true
    end

    local barrierKey = profileSyncMetaOps.buildCombatProfileBarrierKey(delta, sender)
    local queued, queueReason = queueEntry({
      opcode = resolvedOpcode,
      sessionId = TrimText(type(delta) == "table" and delta.sessionId or ""),
      profileName = TrimText(type(delta) == "table" and delta.profileName or ""),
      profileId = TrimText(type(delta) == "table" and delta.profileId or ""),
      sender = profileSyncMetaOps.normalizeSenderKey(sender),
      changeId = TrimText(type(delta) == "table" and delta.changeId or ""),
      sequence = math.max(0, tonumber(type(delta) == "table" and delta.sequence or 0) or 0),
      domain = TrimText(type(delta) == "table" and delta.domain or ""),
      action = TrimText(type(delta) == "table" and delta.action or ""),
      orderingKey = resolvedOpcode == "PDELTA" and (barrierKey .. "\31pdelta") or "",
      barrierKey = barrierKey,
      payload = {
        fields = fields,
        sender = sender,
      },
    })
    if queued ~= true then
      profileSyncMetaOps.recordInboundPayloadReject(
        resolvedOpcode,
        sender,
        fields,
        "combat_inbox_" .. TrimText(queueReason),
        type(delta) == "table" and delta.sessionId or nil
      )
      return true
    end

    if resolvedOpcode == "PDELTA" then
      SendProfileDeltaAck(
        activeSession,
        localProfileName,
        delta,
        GetLootProfileRevisionSummary(localProfileName),
        "QUEUED"
      )
    end
    return true
  end

  profileSyncMetaOps.applyCombatStagedProfileDelta = function(entry)
    local opcode = string.upper(TrimText(type(entry) == "table" and entry.opcode or ""))
    local payload = type(entry) == "table" and type(entry.payload) == "table" and entry.payload or nil
    local fields = type(payload) == "table" and type(payload.fields) == "table" and payload.fields or nil
    if type(fields) ~= "table" then
      return true, "invalid_staged_delta_discarded"
    end

    local activeSession, activeProfileName = GetActiveLootSession()
    if not DoesActiveSessionMatch(
      activeSession,
      activeProfileName,
      type(entry) == "table" and entry.sessionId or "",
      type(entry) == "table" and entry.profileName or ""
    ) then
      return true, "stale_session_discarded"
    end
    if opcode == "PDELTA" then
      INTERNAL_API.LIDCOUNCIL_HandleProfileDelta_Impl(fields, payload.sender)
      return true, "profile_delta_dispatched"
    end
    if opcode == "PDELTA_REQ" then
      INTERNAL_API.LIDCOUNCIL_HandleProfileDeltaRequest_Impl(fields, payload.sender)
      return true, "profile_delta_request_dispatched"
    end
    return true, "unsupported_staged_delta_discarded"
  end

  profileSyncMetaOps.validatePendingProfileDeltaResponse = function(pending, payload)
    if type(pending) ~= "table" or type(payload) ~= "table" then
      return false, "unknown_profile_delta_response"
    end
    if TrimText(pending.sessionId) ~= TrimText(payload.sessionId)
      or string.lower(TrimText(pending.profileName)) ~= string.lower(TrimText(payload.profileName))
    then
      return false, "profile_delta_response_session_mismatch"
    end
    local pendingDelta = type(pending.delta) == "table" and pending.delta or {}
    if TrimText(pendingDelta.changeId) ~= TrimText(payload.changeId) then
      return false, "profile_delta_response_change_mismatch"
    end
    if math.max(0, tonumber(pendingDelta.sequence) or 0) ~= math.max(0, tonumber(payload.sequence) or 0) then
      return false, "profile_delta_response_sequence_mismatch"
    end
    if type(pending.missing) ~= "table" or pending.missing[NormalizeCharacterKey(payload.memberKey)] ~= true then
      return false, "profile_delta_response_member_not_pending"
    end
    return true
  end

  profileSyncMetaOps.allowSupersededProfileDeltaRecoveryRequest = function(activeSession, payload)
    if type(activeSession) ~= "table" or type(payload) ~= "table" then
      return false, "invalid_profile_delta_recovery_request"
    end
    local memberKey = NormalizeCharacterKey(payload.memberKey)
    if memberKey == "" or not IsJoinedSessionCharacter(activeSession, memberKey) then
      return false, "profile_delta_recovery_member_not_joined"
    end
    local requestedSequence = math.max(0, tonumber(payload.sequence) or 0)
    local hostSequence = math.max(0, tonumber(activeSession.profileDeltaSequence) or 0)
    if requestedSequence <= 0 then
      return false, "profile_delta_recovery_sequence_missing"
    end
    if hostSequence > 0 and requestedSequence > hostSequence then
      return false, "profile_delta_recovery_sequence_future"
    end

    local requestKey = table.concat({
      string.lower(TrimText(payload.sessionId)),
      string.lower(TrimText(payload.profileName)),
      string.lower(memberKey),
    }, "\31")
    local now = GetProfileCheckpointSyncTime()
    local previous = sessionRuntime.recentProfileDeltaRecoveryRequests[requestKey]
    local previousAt = math.max(0, tonumber(type(previous) == "table" and previous.requestedAt or 0) or 0)
    local previousSequence = math.max(0, tonumber(type(previous) == "table" and previous.sequence or 0) or 0)
    if previousAt > 0
      and (now - previousAt) < sessionConfig.profileDeltaRecoveryRequestDedupeSeconds
      and requestedSequence <= previousSequence
    then
      return true, "coalesced_superseded_recovery"
    end
    sessionRuntime.recentProfileDeltaRecoveryRequests[requestKey] = {
      sequence = requestedSequence,
      requestedAt = now,
    }
    return true, "superseded_profile_delta_recovery"
  end

  profileSyncMetaOps.buildProfileDeltaRecoverySourceKey = function(sessionId, profileName, sequence)
    return table.concat({
      string.lower(TrimText(sessionId)),
      string.lower(TrimText(profileName)),
      tostring(math.max(0, tonumber(sequence) or 0)),
    }, "\31")
  end

  profileSyncMetaOps.rememberProfileDeltaRecoverySource = function(pending)
    local delta = type(pending) == "table" and type(pending.delta) == "table" and pending.delta or nil
    local sequence = math.max(0, tonumber(type(delta) == "table" and delta.sequence or 0) or 0)
    if type(delta) ~= "table" or sequence <= 0 then
      return
    end
    local sourceKey = profileSyncMetaOps.buildProfileDeltaRecoverySourceKey(
      pending.sessionId,
      pending.profileName,
      sequence
    )
    sessionRuntime.recentProfileDeltaRecoverySources[sourceKey] = {
      rememberedAt = GetProfileCheckpointSyncTime(),
      delta = {
        sessionId = TrimText(pending.sessionId),
        profileName = TrimText(pending.profileName),
        profileId = TrimText(pending.profileId) ~= "" and TrimText(pending.profileId) or TrimText(delta.profileId),
        changeId = TrimText(delta.changeId),
        actor = NormalizeCharacterKey(delta.actor),
        domain = TrimText(delta.domain),
        action = TrimText(delta.action),
        sequence = sequence,
      },
    }

    local retainedCount = 0
    local oldestKey = nil
    local oldestAt = nil
    for key, sourceState in pairs(sessionRuntime.recentProfileDeltaRecoverySources) do
      retainedCount = retainedCount + 1
      local rememberedAt = math.max(0, tonumber(type(sourceState) == "table" and sourceState.rememberedAt or 0) or 0)
      if oldestAt == nil or rememberedAt < oldestAt then
        oldestAt = rememberedAt
        oldestKey = key
      end
    end
    if retainedCount > sessionConfig.maxRecentProfileDeltaRecoverySources and oldestKey ~= nil then
      sessionRuntime.recentProfileDeltaRecoverySources[oldestKey] = nil
    end
  end

  profileSyncMetaOps.getProfileDeltaRecoverySource = function(payload)
    if type(payload) ~= "table" then
      return nil
    end
    local sourceKey = profileSyncMetaOps.buildProfileDeltaRecoverySourceKey(
      payload.sessionId,
      payload.profileName,
      payload.sequence
    )
    local sourceState = sessionRuntime.recentProfileDeltaRecoverySources[sourceKey]
    local rememberedAt = math.max(0, tonumber(type(sourceState) == "table" and sourceState.rememberedAt or 0) or 0)
    if rememberedAt <= 0
      or (GetProfileCheckpointSyncTime() - rememberedAt) >= sessionConfig.profileDeltaRecoverySourceRetentionSeconds
    then
      sessionRuntime.recentProfileDeltaRecoverySources[sourceKey] = nil
      return nil
    end
    return type(sourceState.delta) == "table" and sourceState.delta or nil
  end

  profileSyncMetaOps.getProfileDeltaAckStatus = function()
    local pendingCount = 0
    local pendingMemberCount = 0
    local queuedMemberCount = 0
    for _, pendingAck in pairs(sessionRuntime.pendingProfileDeltaAcks) do
      if type(pendingAck) == "table" then
        pendingCount = pendingCount + 1
        for memberKey in pairs(type(pendingAck.missing) == "table" and pendingAck.missing or {}) do
          if type(pendingAck.queued) ~= "table" or pendingAck.queued[memberKey] == nil then
            pendingMemberCount = pendingMemberCount + 1
          end
        end
        for _ in pairs(type(pendingAck.queued) == "table" and pendingAck.queued or {}) do
          queuedMemberCount = queuedMemberCount + 1
        end
      end
    end
    return {
      pending = pendingCount,
      pendingMembers = pendingMemberCount,
      queuedMembers = queuedMemberCount,
      supersededTotal = math.max(0, tonumber(sessionRuntime.profileDeltaAckSupersededTotal) or 0),
    }
  end

  local function RequestProfileDeltaRecovery(activeSession, profileName, delta, reason)
    if type(activeSession) ~= "table" or type(delta) ~= "table" or type(SendComm) ~= "function" then
      return false
    end
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    local hostKey = NormalizeCharacterKey(activeSession.host or "")
    if selfKey == "" or hostKey == "" or AreCharacterKeysSame(selfKey, hostKey) then
      return false
    end
    local nackArgs = {
      TrimText(activeSession.id),
      TrimText(profileName),
      TrimText(delta.changeId),
      selfKey,
      tostring(tonumber(delta.sequence) or 0),
      TrimText(reason)
    }
    if type(profileSyncMetaOps.validateCommPayload) == "function" then
      local payloadSafe, payloadReason, payloadBytes = profileSyncMetaOps.validateCommPayload("PDELTA_NACK", unpack(nackArgs))
      if not payloadSafe then
        nackArgs[6] = "payload_limit"
        payloadSafe, payloadReason, payloadBytes = profileSyncMetaOps.validateCommPayload("PDELTA_NACK", unpack(nackArgs))
      end
      if not payloadSafe then
        if type(profileSyncMetaOps.recordOutboundPayloadReject) == "function" then
          profileSyncMetaOps.recordOutboundPayloadReject("PDELTA_NACK", payloadReason, payloadBytes, {
            sessionId = activeSession.id,
            target = hostKey,
          })
        end
        return false, "Profile delta recovery notice exceeds the safe addon-message limit."
      end
    end
    return SendComm("PDELTA_NACK", "WHISPER", hostKey, unpack(nackArgs))
  end

  local function TrackProfileDeltaAcks(activeSession, profileName, delta, revisionSummary)
    if type(activeSession) ~= "table" or type(delta) ~= "table" or TrimText(delta.changeId) == "" then
      return
    end
    local distribution = deps.GetGroupDistribution()
    if not distribution or type(Compat) ~= "table" or type(Compat.After) ~= "function" then
      return
    end

    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    local missing = {}
    for memberKey, member in pairs(activeSession.members or {}) do
      local resolvedKey = NormalizeCharacterKey(memberKey)
      if resolvedKey ~= "" and not AreCharacterKeysSame(resolvedKey, selfKey)
          and type(member) == "table" and string.upper(TrimText(member.status or "JOINED")) == "JOINED" then
        missing[resolvedKey] = true
      end
    end
    if not next(missing) then
      return
    end

    local now = GetProfileCheckpointSyncTime()
    PruneAgedSessionRuntimeTracking(now)
    local supersededCount = 0
    for pendingChangeId, pendingAck in pairs(sessionRuntime.pendingProfileDeltaAcks) do
      local pendingDelta = type(pendingAck) == "table" and type(pendingAck.delta) == "table" and pendingAck.delta or {}
      local pendingSequence = math.max(0, tonumber(pendingDelta.sequence) or 0)
      if pendingChangeId ~= delta.changeId
        and TrimText(type(pendingAck) == "table" and pendingAck.sessionId or "") == TrimText(activeSession.id)
        and string.lower(TrimText(type(pendingAck) == "table" and pendingAck.profileName or "")) == string.lower(TrimText(profileName))
        and pendingSequence > 0
        and pendingSequence < math.max(0, tonumber(delta.sequence) or 0)
      then
        profileSyncMetaOps.rememberProfileDeltaRecoverySource(pendingAck)
        sessionRuntime.pendingProfileDeltaAcks[pendingChangeId] = nil
        supersededCount = supersededCount + 1
      end
    end
    if supersededCount > 0 then
      sessionRuntime.profileDeltaAckSupersededTotal = math.max(0, tonumber(sessionRuntime.profileDeltaAckSupersededTotal) or 0) + supersededCount
    end
    sessionRuntime.pendingProfileDeltaAcks[delta.changeId] = {
      sessionId = TrimText(activeSession.id),
      profileName = TrimText(profileName),
      profileId = TrimText(delta.profileId),
      delta = delta,
      sequence = math.max(0, tonumber(delta.sequence) or 0),
      revisionSummary = revisionSummary,
      missing = missing,
      queued = {},
      attempts = 0,
      queuedAt = now,
      updatedAt = now,
    }

    local function CheckPendingAcks()
      local pending = sessionRuntime.pendingProfileDeltaAcks[delta.changeId]
      if type(pending) ~= "table" then
        return
      end
      local currentTime = GetProfileCheckpointSyncTime()
      local updatedAt = math.max(0, tonumber(pending.updatedAt or pending.queuedAt) or 0)
      if (updatedAt <= 0 or (currentTime - updatedAt) >= sessionConfig.pendingProfileDeltaAckRetentionSeconds)
        and not next(pending.queued or {})
      then
        sessionRuntime.pendingProfileDeltaAcks[delta.changeId] = nil
        return
      end
      if not next(pending.missing or {}) then
        sessionRuntime.pendingProfileDeltaAcks[delta.changeId] = nil
        return
      end

      local currentSession, currentProfileName = GetActiveLootSession()
      if not DoesActiveSessionMatch(currentSession, currentProfileName, pending.sessionId, pending.profileName) then
        sessionRuntime.pendingProfileDeltaAcks[delta.changeId] = nil
        return
      end

      local retryTargets = {}
      for memberKey in pairs(pending.missing) do
        if type(pending.queued) ~= "table" or pending.queued[memberKey] == nil then
          retryTargets[memberKey] = true
        end
      end
      if not next(retryTargets) then
        Compat.After(sessionConfig.profileDeltaAckTimeoutSeconds, CheckPendingAcks)
        return
      end

      pending.attempts = math.max(0, tonumber(pending.attempts) or 0) + 1
      pending.updatedAt = currentTime
      if pending.attempts <= sessionConfig.profileDeltaMaxRetries then
        for memberKey in pairs(retryTargets) do
          SendProfileDelta("PDELTA", "WHISPER", memberKey, currentSession, pending.profileName, pending.delta, pending.revisionSummary)
        end
        Compat.After(sessionConfig.profileDeltaAckTimeoutSeconds, CheckPendingAcks)
        return
      end

      local syncCandidateSnapshot = BuildActiveSyncCandidateSnapshot()
      for memberKey in pairs(retryTargets) do
        QueueTargetedDeltaRecoveryForMember(
          currentSession,
          pending.profileName,
          pending.sessionId,
          memberKey,
          pending.delta,
          {
            mode = "LIVE",
            reason = "delta_ack_timeout",
            syncCandidateSnapshot = syncCandidateSnapshot,
          }
        )
        pending.missing[memberKey] = nil
      end
      if next(pending.missing or {}) then
        Compat.After(sessionConfig.profileDeltaAckTimeoutSeconds, CheckPendingAcks)
      else
        sessionRuntime.pendingProfileDeltaAcks[delta.changeId] = nil
      end
    end

    Compat.After(sessionConfig.profileDeltaAckTimeoutSeconds, CheckPendingAcks)
  end

  local function BuildProfileDeltaRevisionSummary(delta)
    delta = type(delta) == "table" and delta or {}
    return deps.NormalizeRevisionSummary({
      profileName = delta.profileName,
      profileId = delta.profileId,
      settings = delta.settingsRevision,
      permissions = delta.permissionsRevision,
      operational = delta.operationalRevision,
      loot = delta.lootRevision,
      session = delta.sessionRevision,
      settingsChecksum = delta.settingsChecksum,
      permissionsChecksum = delta.permissionsChecksum,
      operationalChecksum = delta.operationalChecksum,
      lootChecksum = delta.lootChecksum,
      sessionChecksum = delta.sessionChecksum,
      updatedAt = delta.profileUpdatedAt,
    }, delta.profileName, delta.profileId)
  end

  local function NormalizeProfileDeltaDomain(domain)
    local resolved = string.lower(TrimText(domain))
    if resolved == "settings" then
      return "settings"
    elseif resolved == "permissions" then
      return "permissions"
    elseif resolved == "loot" then
      return "loot"
    elseif resolved == "session" then
      return "session"
    end
    return "operational"
  end

  local function BuildProfileDeltaRecoveryScope(sessionId, memberKey, delta, candidateOverride)
    local requestedDomain = TrimText(type(delta) == "table" and delta.domain or "")
    if requestedDomain == "" then
      return {}, {}, "full"
    end

    local candidate = type(candidateOverride) == "table" and candidateOverride or FindActiveSyncCandidate(memberKey)
    local comparison = string.lower(TrimText(
      type(candidate) == "table"
        and (candidate.effectiveComparison ~= "" and candidate.effectiveComparison or candidate.comparison)
        or ""
    ))
    if comparison == "same" then
      return {}, {}, "aligned"
    elseif comparison == "different_lineage" or comparison == "unknown" then
      return {}, {}, "full"
    end

    local normalizedDomain = NormalizeProfileDeltaDomain(requestedDomain)
    local recoveryDomains, recoverySubdomains = profileSyncMetaOps.buildAutomaticHostRepairScope(
      memberKey,
      { normalizedDomain },
      sessionId,
      candidate
    )
    if #recoveryDomains == 0 and #recoverySubdomains == 0 then
      recoveryDomains = { normalizedDomain }
    end
    return recoveryDomains, recoverySubdomains, #recoverySubdomains > 0 and "precise" or "targeted"
  end

  QueueTargetedDeltaRecoveryForMember = function(activeSession, profileName, sessionId, memberKey, delta, opts)
    opts = type(opts) == "table" and opts or {}
    local resolvedProfileName = TrimText(profileName)
    local resolvedSessionId = TrimText(sessionId)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    local mode = TrimText(opts.mode) ~= "" and TrimText(opts.mode) or "LIVE"
    local reason = TrimText(opts.reason) ~= "" and TrimText(opts.reason) or "delta_recovery"
    local syncCandidate = type(opts.syncCandidate) == "table" and opts.syncCandidate
      or select(1, GetActiveSyncCandidateContextFromSnapshot(
        resolvedMemberKey,
        type(opts.syncCandidateSnapshot) == "table" and opts.syncCandidateSnapshot or nil
      ))
    local recoveryDomains, recoverySubdomains, recoveryKind = BuildProfileDeltaRecoveryScope(
      resolvedSessionId,
      resolvedMemberKey,
      delta,
      syncCandidate
    )
    local requestedScope = ClassifyRequestedRepairScope(
      recoveryDomains,
      recoverySubdomains,
      recoveryKind == "full" and "full" or "same"
    )

    if #recoveryDomains == 0 and #recoverySubdomains == 0 and recoveryKind ~= "full" then
      if type(RecordProfileSyncDecision) == "function" then
        RecordProfileSyncDecision("queue_delta_recovery", {
          action = recoveryKind == "aligned" and "skipped_aligned" or "skipped",
          sessionId = resolvedSessionId,
          profileName = resolvedProfileName,
          mode = mode,
          reason = reason,
          target = resolvedMemberKey,
          targetCount = resolvedMemberKey ~= "" and 1 or 0,
          requestedDomains = {},
          requestedSubdomains = {},
          requestedScope = requestedScope,
          scopeEscalated = false,
          fullSnapshotFallback = false,
          scopeEscalationKinds = {},
        })
      end
      return true, 0, nil, recoveryKind
    end

    local targetedReason = (#recoverySubdomains > 0 and #recoveryDomains == 0)
      and (reason .. "_precise")
      or (#recoverySubdomains > 0 and (reason .. "_targeted") or reason)
    local queuedRepair, queuedCount, repairError, repairDetail = QueueLiveFirstRepairTransfersForMember(
      activeSession,
      resolvedProfileName,
      resolvedSessionId,
      resolvedMemberKey,
      {
        mode = mode,
        reason = targetedReason,
        domains = recoveryDomains,
        subdomains = recoverySubdomains,
        syncCandidate = syncCandidate,
      }
    )
    local queuedRepairCount = math.max(0, tonumber(queuedCount) or 0)
    if type(repairDetail) == "table" then
      repairDetail.requestedScope = TrimText(repairDetail.requestedScope) ~= ""
        and TrimText(repairDetail.requestedScope)
        or requestedScope
    end
    if queuedRepair and queuedRepairCount <= 0 and type(repairDetail) == "table" and repairDetail.coalescedExistingRepair == true then
      if type(RecordProfileSyncDecision) == "function" then
        RecordProfileSyncDecision("queue_delta_recovery", {
          action = "coalesced_existing_repair",
          sessionId = resolvedSessionId,
          profileName = resolvedProfileName,
          mode = mode,
          reason = reason,
          target = resolvedMemberKey,
          targetCount = resolvedMemberKey ~= "" and 1 or 0,
          queuedCount = 0,
          requestedDomains = CloneCheckpointDomainList(recoveryDomains),
          requestedSubdomains = CloneCheckpointSubdomainList(recoverySubdomains),
          requestedScope = TrimText(type(repairDetail) == "table" and repairDetail.requestedScope or requestedScope),
          coalescedReason = TrimText(type(repairDetail) == "table" and repairDetail.coalescedRepairReason or ""),
        })
      end
      return true, 0, nil, "coalesced", repairDetail
    end
    if queuedRepair and queuedRepairCount <= 0 and type(repairDetail) == "table" and repairDetail.skippedNoOp == true then
      if type(RecordProfileSyncDecision) == "function" then
        RecordProfileSyncDecision("queue_delta_recovery", {
          action = "skipped_noop",
          sessionId = resolvedSessionId,
          profileName = resolvedProfileName,
          mode = mode,
          reason = reason,
          target = resolvedMemberKey,
          targetCount = resolvedMemberKey ~= "" and 1 or 0,
          queuedCount = 0,
          requestedDomains = CloneCheckpointDomainList(recoveryDomains),
          requestedSubdomains = CloneCheckpointSubdomainList(recoverySubdomains),
          requestedScope = TrimText(type(repairDetail) == "table" and repairDetail.requestedScope or requestedScope),
          effectiveDomains = CloneCheckpointDomainList(type(repairDetail) == "table" and repairDetail.effectiveDomains or {}),
          effectiveSubdomains = CloneCheckpointSubdomainList(type(repairDetail) == "table" and repairDetail.effectiveSubdomains or {}),
          scopeEscalated = type(repairDetail) == "table" and repairDetail.scopeEscalated == true,
          fullSnapshotFallback = type(repairDetail) == "table" and repairDetail.fullSnapshotFallback == true,
          scopeEscalationKinds = CloneDecisionTextList(type(repairDetail) == "table" and repairDetail.scopeEscalationKinds or {}),
          fallbackReason = TrimText(type(repairDetail) == "table" and repairDetail.skipReason or ""),
          fallbackReasons = TrimText(type(repairDetail) == "table" and repairDetail.skipReason or "") ~= ""
            and { TrimText(repairDetail.skipReason) }
            or {},
        })
      end
      return true, 0, nil, "aligned", repairDetail
    end
    if queuedRepair then
      if type(RecordProfileSyncDecision) == "function" then
        RecordProfileSyncDecision("queue_delta_recovery", {
          action = queuedRepairCount > 0
            and "queued_targeted"
            or (type(repairDetail) == "table" and repairDetail.deferredPatchState == true and "deferred_patch_state" or "completed"),
          sessionId = resolvedSessionId,
          profileName = resolvedProfileName,
          mode = mode,
          reason = reason,
          target = resolvedMemberKey,
          targetCount = resolvedMemberKey ~= "" and 1 or 0,
          queuedCount = queuedRepairCount,
          requestedDomains = CloneCheckpointDomainList(recoveryDomains),
          requestedSubdomains = CloneCheckpointSubdomainList(recoverySubdomains),
          requestedScope = TrimText(type(repairDetail) == "table" and repairDetail.requestedScope or requestedScope),
          transferKinds = CloneDecisionTextList(type(repairDetail) == "table" and repairDetail.transferKinds or {}),
          patchSubdomains = CloneCheckpointSubdomainList(type(repairDetail) == "table" and repairDetail.patchTransferSubdomains or {}),
          snapshotFallbackSubdomains = CloneCheckpointSubdomainList(type(repairDetail) == "table" and repairDetail.snapshotFallbackSubdomains or {}),
          scopeEscalated = type(repairDetail) == "table" and repairDetail.scopeEscalated == true,
          fullSnapshotFallback = type(repairDetail) == "table" and repairDetail.fullSnapshotFallback == true,
          scopeEscalationKinds = CloneDecisionTextList(type(repairDetail) == "table" and repairDetail.scopeEscalationKinds or {}),
          fallbackReason = type(repairDetail) == "table" and type(repairDetail.fallbackReasons) == "table" and repairDetail.fallbackReasons[1] or "",
          fallbackReasons = CloneDecisionTextList(type(repairDetail) == "table" and repairDetail.fallbackReasons or {}),
        })
      end
      return true, queuedRepairCount, nil, recoveryKind, repairDetail
    end

    local fallbackReasons = recoveryKind == "full"
      and { "delta_full_recovery_required" }
      or { "delta_targeted_recovery_failed" }
    local fallbackDetail = {
      transferKind = "",
      transferKinds = {},
      requestedScope = requestedScope,
      patchTransfers = 0,
      patchSubdomains = 0,
      snapshotTransfers = 0,
      deferredPatchState = false,
      scopeEscalated = false,
      fullSnapshotFallback = false,
      scopeEscalationKinds = {},
      fallback = true,
      fallbackReason = fallbackReasons[1],
      fallbackReasons = CloneDecisionTextList(fallbackReasons),
    }

    if recoveryKind ~= "full" and (#recoveryDomains > 0 or #recoverySubdomains > 0) then
      local preparedScopedSnapshot, scopedPrepareError = PrepareProfileSnapshotTransfer(resolvedProfileName, {
        domains = #recoveryDomains > 0 and recoveryDomains or nil,
        subdomains = #recoverySubdomains > 0 and recoverySubdomains or nil,
      })
      if type(preparedScopedSnapshot) == "table" then
        fallbackDetail.transferKinds = profileSyncMetaOps.buildPreparedTransferKindList({ preparedScopedSnapshot })
        fallbackDetail.transferKind = fallbackDetail.transferKinds[1] or ""
        fallbackDetail.requestedScope = TrimText(preparedScopedSnapshot.requestedScope) ~= ""
          and TrimText(preparedScopedSnapshot.requestedScope)
          or requestedScope
        fallbackDetail.snapshotTransfers = 1
        fallbackDetail.scopeEscalated = preparedScopedSnapshot.scopeEscalated == true
        fallbackDetail.fullSnapshotFallback = preparedScopedSnapshot.fullSnapshotFallback == true
        fallbackDetail.scopeEscalationKinds = TrimText(preparedScopedSnapshot.fallbackEscalation) ~= ""
          and { TrimText(preparedScopedSnapshot.fallbackEscalation) }
          or {}
        fallbackDetail.fallbackReasons = MergeDecisionTextLists(
          fallbackDetail.fallbackReasons,
          CloneDecisionTextList(type(preparedScopedSnapshot) == "table" and preparedScopedSnapshot.fallbackReasons or {})
        )
        local coalesceScopedSnapshot, scopedSnapshotRequestState, _, scopedSnapshotCoalescedReason =
          EvaluateRecentMemberRepairRequest(
            activeSession,
            resolvedProfileName,
            resolvedSessionId,
            resolvedMemberKey,
            recoveryDomains,
            recoverySubdomains,
            {
              mode = mode,
              forceFullSnapshot = preparedScopedSnapshot.fullSnapshotFallback == true,
              syncCandidate = syncCandidate,
            }
          )
        if coalesceScopedSnapshot then
          fallbackDetail.coalescedExistingRepair = true
          fallbackDetail.coalescedRepairReason = TrimText(scopedSnapshotCoalescedReason)
          if type(RecordProfileSyncDecision) == "function" then
            RecordProfileSyncDecision("queue_delta_recovery", {
              action = "coalesced_scoped_snapshot_fallback",
              sessionId = resolvedSessionId,
              profileName = resolvedProfileName,
              mode = mode,
              reason = reason,
              target = resolvedMemberKey,
              targetCount = resolvedMemberKey ~= "" and 1 or 0,
              queuedCount = 0,
              requestedDomains = CloneCheckpointDomainList(recoveryDomains),
              requestedSubdomains = CloneCheckpointSubdomainList(recoverySubdomains),
              requestedScope = TrimText(fallbackDetail.requestedScope),
              coalescedReason = TrimText(scopedSnapshotCoalescedReason),
              fallback = true,
              fallbackReason = fallbackDetail.fallbackReason,
              fallbackReasons = CloneDecisionTextList(fallbackDetail.fallbackReasons),
            })
          end
          return true, 0, nil, "coalesced", fallbackDetail
        end
        local queuedScopedSnapshot, queuedScopedCountOrError = QueueProfileSnapshotForMember(
          resolvedProfileName,
          resolvedSessionId,
          resolvedMemberKey,
          {
            mode = mode,
            reason = targetedReason .. "_scoped_snapshot_fallback",
            domains = #recoveryDomains > 0 and recoveryDomains or nil,
            subdomains = #recoverySubdomains > 0 and recoverySubdomains or nil,
            preparedSnapshot = preparedScopedSnapshot,
          }
        )
        if queuedScopedSnapshot then
          RememberRecentMemberRepairRequestState(resolvedSessionId, resolvedMemberKey, scopedSnapshotRequestState)
        end
        if type(RecordProfileSyncDecision) == "function" then
          RecordProfileSyncDecision("queue_delta_recovery", {
            action = queuedScopedSnapshot and "queued_scoped_snapshot_fallback" or "scoped_snapshot_fallback_failed",
            sessionId = resolvedSessionId,
            profileName = resolvedProfileName,
            mode = mode,
            reason = reason,
            target = resolvedMemberKey,
            targetCount = resolvedMemberKey ~= "" and 1 or 0,
            queuedCount = queuedScopedSnapshot and math.max(0, tonumber(queuedScopedCountOrError) or 1) or 0,
            requestedDomains = CloneCheckpointDomainList(recoveryDomains),
            requestedSubdomains = CloneCheckpointSubdomainList(recoverySubdomains),
            requestedScope = TrimText(fallbackDetail.requestedScope),
            transferKind = fallbackDetail.transferKind,
            transferKinds = CloneDecisionTextList(fallbackDetail.transferKinds),
            scopeEscalated = fallbackDetail.scopeEscalated == true,
            fullSnapshotFallback = fallbackDetail.fullSnapshotFallback == true,
            scopeEscalationKinds = CloneDecisionTextList(fallbackDetail.scopeEscalationKinds),
            fallback = true,
            fallbackReason = fallbackDetail.fallbackReason,
            fallbackReasons = CloneDecisionTextList(fallbackDetail.fallbackReasons),
            error = queuedScopedSnapshot and nil or (queuedScopedCountOrError or repairError),
          })
        end
        if queuedScopedSnapshot then
          return true, math.max(0, tonumber(queuedScopedCountOrError) or 1), nil, "scoped_snapshot", fallbackDetail
        end
        AppendDecisionReason(fallbackReasons, "delta_scoped_snapshot_fallback_failed")
        repairError = queuedScopedCountOrError or repairError
      else
        AppendDecisionReason(fallbackReasons, "delta_scoped_snapshot_fallback_failed")
        repairError = scopedPrepareError or repairError
      end
      fallbackDetail.fallbackReason = fallbackReasons[#fallbackReasons] or fallbackReasons[1]
      fallbackDetail.fallbackReasons = CloneDecisionTextList(fallbackReasons)
    end

    local coalesceFullSnapshot, fullSnapshotRequestState, _, fullSnapshotCoalescedReason =
      EvaluateRecentMemberRepairRequest(
        activeSession,
        resolvedProfileName,
        resolvedSessionId,
        resolvedMemberKey,
        {},
        {},
        {
          mode = mode,
          forceFullSnapshot = true,
          syncCandidate = syncCandidate,
        }
      )
    if coalesceFullSnapshot then
      fallbackDetail.transferKind = "FULL"
      fallbackDetail.transferKinds = { "FULL" }
      fallbackDetail.requestedScope = requestedScope
      fallbackDetail.scopeEscalationKinds = BuildFullSnapshotFallbackEscalationKinds(requestedScope)
      fallbackDetail.scopeEscalated = #fallbackDetail.scopeEscalationKinds > 0
      fallbackDetail.fullSnapshotFallback = fallbackDetail.scopeEscalated
      fallbackDetail.coalescedExistingRepair = true
      fallbackDetail.coalescedRepairReason = TrimText(fullSnapshotCoalescedReason)
      if type(RecordProfileSyncDecision) == "function" then
        RecordProfileSyncDecision("queue_delta_recovery", {
          action = "coalesced_full_snapshot_fallback",
          sessionId = resolvedSessionId,
          profileName = resolvedProfileName,
          mode = mode,
          reason = reason,
          target = resolvedMemberKey,
          targetCount = resolvedMemberKey ~= "" and 1 or 0,
          queuedCount = 0,
          requestedDomains = CloneCheckpointDomainList(recoveryDomains),
          requestedSubdomains = CloneCheckpointSubdomainList(recoverySubdomains),
          requestedScope = TrimText(fallbackDetail.requestedScope),
          transferKind = "FULL",
          transferKinds = { "FULL" },
          scopeEscalated = fallbackDetail.scopeEscalated == true,
          fullSnapshotFallback = fallbackDetail.fullSnapshotFallback == true,
          scopeEscalationKinds = CloneDecisionTextList(fallbackDetail.scopeEscalationKinds),
          fallback = true,
          fallbackReason = fallbackDetail.fallbackReason,
          fallbackReasons = CloneDecisionTextList(fallbackDetail.fallbackReasons),
          coalescedReason = TrimText(fullSnapshotCoalescedReason),
        })
      end
      return true, 0, nil, "coalesced", fallbackDetail
    end
    local queuedSnapshot, queueSnapshotResult = QueueProfileSnapshotForMember(
      resolvedProfileName,
      resolvedSessionId,
      resolvedMemberKey,
      {
        mode = mode,
        reason = reason,
      }
    )
    if queuedSnapshot then
      RememberRecentMemberRepairRequestState(resolvedSessionId, resolvedMemberKey, fullSnapshotRequestState)
    end
    fallbackDetail.transferKind = "FULL"
    fallbackDetail.transferKinds = { "FULL" }
    fallbackDetail.snapshotTransfers = 1
    fallbackDetail.requestedScope = requestedScope
    fallbackDetail.scopeEscalationKinds = BuildFullSnapshotFallbackEscalationKinds(requestedScope)
    fallbackDetail.scopeEscalated = #fallbackDetail.scopeEscalationKinds > 0
    fallbackDetail.fullSnapshotFallback = fallbackDetail.scopeEscalated
    if type(RecordProfileSyncDecision) == "function" then
      RecordProfileSyncDecision("queue_delta_recovery", {
        action = queuedSnapshot and "queued_full_snapshot_fallback" or "full_snapshot_fallback_failed",
        sessionId = resolvedSessionId,
        profileName = resolvedProfileName,
        mode = mode,
        reason = reason,
        target = resolvedMemberKey,
        targetCount = resolvedMemberKey ~= "" and 1 or 0,
        queuedCount = queuedSnapshot and math.max(0, tonumber(queueSnapshotResult) or 1) or 0,
        requestedDomains = CloneCheckpointDomainList(recoveryDomains),
        requestedSubdomains = CloneCheckpointSubdomainList(recoverySubdomains),
        requestedScope = TrimText(fallbackDetail.requestedScope),
        transferKind = fallbackDetail.transferKind,
        transferKinds = CloneDecisionTextList(fallbackDetail.transferKinds),
        scopeEscalated = fallbackDetail.scopeEscalated == true,
        fullSnapshotFallback = fallbackDetail.fullSnapshotFallback == true,
        scopeEscalationKinds = CloneDecisionTextList(fallbackDetail.scopeEscalationKinds),
        fallback = true,
        fallbackReason = fallbackDetail.fallbackReason,
        fallbackReasons = CloneDecisionTextList(fallbackDetail.fallbackReasons),
        error = queuedSnapshot and nil or (queueSnapshotResult or repairError),
      })
    end
    return queuedSnapshot, queuedSnapshot and queueSnapshotResult or 0, queueSnapshotResult or repairError, "full", fallbackDetail
  end

  local function IsLocalProfileAlignedWithDelta(profileName, delta)
    local localSummary = deps.NormalizeRevisionSummary(
      GetLootProfileRevisionSummary(profileName),
      profileName,
      TrimText(type(delta) == "table" and delta.profileId or "")
    )
    local remoteSummary = BuildProfileDeltaRevisionSummary(delta)
    local domain = NormalizeProfileDeltaDomain(type(delta) == "table" and delta.domain or "")
    local checksumKey = domain .. "Checksum"
    local localRevision = math.max(0, tonumber(localSummary[domain]) or 0)
    local remoteRevision = math.max(0, tonumber(remoteSummary[domain]) or 0)
    if localRevision ~= remoteRevision then
      return false, { domain }, { domain }
    end
    local localChecksum = TrimText(localSummary[checksumKey])
    local remoteChecksum = TrimText(remoteSummary[checksumKey])
    if localChecksum ~= "" and remoteChecksum ~= "" and localChecksum ~= remoteChecksum then
      return false, { domain }, { domain }
    end
    return true, {}, {}
  end

  local function RefreshActiveSessionProfileCache(activeSession, profileName)
    if type(activeSession) ~= "table" or TrimText(profileName) == "" then
      return
    end
    local sourceProfile = type(deps.GetLootProfile) == "function" and select(1, deps.GetLootProfile(profileName)) or nil
    if type(sourceProfile) == "table" and type(deps.NormalizeLootRollOptions) == "function" then
      activeSession.rollOptions = deps.NormalizeLootRollOptions(sourceProfile.settings and sourceProfile.settings.rollOptions)
    end
    if type(activeSession.members) == "table" then
      for memberKey, member in pairs(activeSession.members) do
        if type(member) == "table" then
          member.profileMaster = deps.GetLootProfileMaster(profileName)
          member.role = deps.GetLootProfileRole(profileName, memberKey)
        end
      end
    end
  end

  AreCharacterKeysSame = function(left, right)
    local leftKey = NormalizeCharacterKey(left)
    local rightKey = NormalizeCharacterKey(right)
    if leftKey == "" or rightKey == "" then
      return false
    end
    if string.lower(leftKey) == string.lower(rightKey) then
      return true
    end

    local leftName, leftRealm = leftKey:match("^([^%-]+)%-(.+)$")
    local rightName, rightRealm = rightKey:match("^([^%-]+)%-(.+)$")
    leftName = string.lower(TrimText(leftName or leftKey))
    rightName = string.lower(TrimText(rightName or rightKey))
    leftRealm = string.lower(TrimText(leftRealm or ""))
    rightRealm = string.lower(TrimText(rightRealm or ""))
    if leftName == "" or rightName == "" or leftName ~= rightName then
      return false
    end
    return leftRealm == "" or rightRealm == "" or leftRealm == rightRealm
  end

  NormalizeSenderKey = function(sender)
    if type(deps.NormalizeSenderKey) == "function" then
      return deps.NormalizeSenderKey(sender)
    end
    return NormalizeCharacterKey(sender)
  end

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

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

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

  local function BuildPendingJoinRequest(invite)
    invite = type(invite) == "table" and invite or {}
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "Unknown")
    local inviteProfileId = TrimText(invite.profileId)
    local existingSharedProfileName = TrimText(inviteProfileId ~= "" and deps.FindLootProfileNameById(inviteProfileId) or "")
    local localRevisionSummary = existingSharedProfileName ~= ""
      and deps.NormalizeRevisionSummary(GetLootProfileRevisionSummary(existingSharedProfileName), existingSharedProfileName, inviteProfileId)
      or deps.BuildEmptyRevisionSummary(invite.profileName, inviteProfileId)
    local joinedAt = tonumber(time and time() or 0) or 0
    local runtimeNow = GetProfileCheckpointSyncTime()
    return {
      invite = invite,
      selfKey = selfKey,
      joinedAt = joinedAt,
      queuedAt = runtimeNow,
      updatedAt = runtimeNow,
      payloadDetails = deps.GetMemberPayloadDetails(nil, true),
      localRevisionSummary = localRevisionSummary,
      existingSharedProfileName = existingSharedProfileName,
      attempts = 0,
      queueAttempts = 0,
      confirmed = false,
      state = "PENDING",
      retryTimerToken = 0,
      retryTimerArmed = false,
      retryTimerDueAt = 0,
      retryBlockedSince = 0,
      retryBlockedSeconds = 0,
      lastQueuedAt = 0,
      lastSentAt = 0,
      hardDeadlineAt = runtimeNow + sessionConfig.joinAckHardTimeoutSeconds,
      timedOutAt = 0,
      acceptLateAckUntil = 0,
    }
  end

  function sessionLifecycleOps.getPendingJoinRetryOptions()
    return {
      maxAttempts = sessionConfig.joinAckMaxAttempts,
      retryDelaysSeconds = sessionConfig.joinAckRetryDelaysSeconds,
      finalWaitSeconds = sessionConfig.joinAckFinalWaitSeconds,
      fallbackDelaySeconds = sessionConfig.joinAckFallbackDelaySeconds,
      queuePollSeconds = sessionConfig.joinAckQueuePollSeconds,
      blockedPollSeconds = sessionConfig.joinAckBlockedPollSeconds,
    }
  end

  function sessionLifecycleOps.getJoinOutboundQueueStatus()
    if type(deps.GetCommOutboundQueueStatus) ~= "function" then
      return {}
    end
    local ok, status = pcall(deps.GetCommOutboundQueueStatus)
    return ok and type(status) == "table" and status or {}
  end

  function sessionLifecycleOps.markPendingJoinTimedOut(sessionId, reason)
    local resolvedSessionId = TrimText(sessionId)
    local request = sessionRuntime.pendingJoinRequests[resolvedSessionId]
    if type(request) ~= "table" or request.confirmed or request.state == "TIMED_OUT" then
      return false
    end
    local runtimeNow = GetProfileCheckpointSyncTime()
    request.state = "TIMED_OUT"
    request.timeoutReason = TrimText(reason)
    request.timedOutAt = runtimeNow
    request.updatedAt = runtimeNow
    request.acceptLateAckUntil = runtimeNow + sessionConfig.joinAckLateGraceSeconds
    INTERNAL_API.LIDCOUNCIL_InvalidateJoinAckRetryTimer_Impl(request)
    local invite = type(request.invite) == "table" and request.invite or {}
    Print(sessionLifecycleOps.buildFlowNoticeText("join_request_timeout", {
      profileName = invite.profileName,
    }))
    sessionUiOps.refreshAutoPassSection()
    return true
  end

  function sessionLifecycleOps.schedulePendingJoinRetryCheck(sessionId, delaySeconds, replaceExisting)
    local resolvedSessionId = TrimText(sessionId)
    local request = sessionRuntime.pendingJoinRequests[resolvedSessionId]
    if type(request) ~= "table" or request.confirmed or request.state == "TIMED_OUT" then
      return false, "No active join request."
    end
    if type(Compat) ~= "table" or type(Compat.After) ~= "function" then
      return false, "Timer API unavailable."
    end
    local armed, token = INTERNAL_API.LIDCOUNCIL_ArmJoinAckRetryTimer_Impl(
      request,
      GetProfileCheckpointSyncTime(),
      math.max(0, tonumber(delaySeconds) or 0),
      replaceExisting == true
    )
    if not armed then
      return false, "Join retry timer already armed."
    end
    local scheduled, scheduleError = Compat.After(math.max(0, tonumber(delaySeconds) or 0), function()
      local pending = sessionRuntime.pendingJoinRequests[resolvedSessionId]
      if type(pending) == "table"
        and INTERNAL_API.LIDCOUNCIL_ConsumeJoinAckRetryTimer_Impl(pending, token)
      then
        sessionLifecycleOps.processPendingJoinRetry(resolvedSessionId)
      end
    end)
    if scheduled == false then
      local pending = sessionRuntime.pendingJoinRequests[resolvedSessionId]
      if type(pending) == "table" then
        INTERNAL_API.LIDCOUNCIL_ConsumeJoinAckRetryTimer_Impl(pending, token)
      end
      return false, scheduleError or "Unable to schedule join retry timer."
    end
    return true
  end

  function sessionLifecycleOps.processPendingJoinRetry(sessionId)
    local resolvedSessionId = TrimText(sessionId)
    local request = sessionRuntime.pendingJoinRequests[resolvedSessionId]
    if type(request) ~= "table" or request.confirmed then
      return false, "No pending join request."
    end
    local runtimeNow = GetProfileCheckpointSyncTime()
    local queueStatus = sessionLifecycleOps.getJoinOutboundQueueStatus()
    local blocked = queueStatus.chatLockdownActive == true
      or math.max(0, tonumber(queueStatus.globalThrottleCooldownRemaining) or 0) > 0
    INTERNAL_API.LIDCOUNCIL_UpdateJoinAckBlockedDeadline_Impl(request, runtimeNow, blocked)
    local decision = INTERNAL_API.LIDCOUNCIL_ResolvePendingJoinRetryAction_Impl(
      request,
      queueStatus,
      runtimeNow,
      sessionLifecycleOps.getPendingJoinRetryOptions()
    )
    if decision.action == "wait_blocked" or decision.action == "wait_queued" then
      return sessionLifecycleOps.schedulePendingJoinRetryCheck(
        resolvedSessionId,
        decision.delaySeconds,
        false
      )
    end
    if decision.action == "timeout" then
      return sessionLifecycleOps.markPendingJoinTimedOut(resolvedSessionId, decision.reason)
    end
    if decision.action == "queue_retry" then
      return SendJoinRequest(resolvedSessionId, math.max(0, tonumber(request.attempts) or 0) > 0)
    end
    return false, decision.action or "Join retry stopped."
  end

  function sessionLifecycleOps.handleOutboundJoinSent(metadata, sentAt)
    metadata = type(metadata) == "table" and metadata or {}
    local sessionId = TrimText(metadata.sessionId)
    local memberKey = NormalizeCharacterKey(metadata.memberKey)
    local request = sessionRuntime.pendingJoinRequests[sessionId]
    if type(request) ~= "table"
      or request.confirmed
      or request.state == "TIMED_OUT"
      or sessionId == ""
      or memberKey == ""
      or memberKey ~= NormalizeCharacterKey(request.selfKey)
    then
      return false
    end
    local runtimeNow = GetProfileCheckpointSyncTime()
    local previousAttempts = math.max(0, tonumber(request.attempts) or 0)
    request.attempts = previousAttempts + 1
    if previousAttempts == 0 then
      -- The acknowledgement budget begins when WoW actually accepts the first
      -- JOIN, not while that packet is still waiting in the outbound queue.
      request.hardDeadlineAt = runtimeNow + sessionConfig.joinAckHardTimeoutSeconds
    end
    request.lastSentAt = runtimeNow
    request.updatedAt = runtimeNow
    request.state = "WAITING_ACK"
    local retryDelay = INTERNAL_API.LIDCOUNCIL_ResolveJoinAckRetryDelay_Impl(
      request.attempts,
      sessionLifecycleOps.getPendingJoinRetryOptions()
    )
    sessionLifecycleOps.schedulePendingJoinRetryCheck(sessionId, retryDelay, true)
    local invite = type(request.invite) == "table" and request.invite or {}
    if request.attempts > 1 then
      Print(sessionLifecycleOps.buildFlowNoticeText("join_request_retried", {
        profileName = invite.profileName,
        attempts = request.attempts,
        maxAttempts = sessionConfig.joinAckMaxAttempts,
      }))
    else
      Print(sessionLifecycleOps.buildFlowNoticeText("join_request_sent", {
        profileName = invite.profileName,
      }))
    end
    return true
  end

  INTERNAL_API.LIDCOUNCIL_HandleOutboundJoinSent_Impl = sessionLifecycleOps.handleOutboundJoinSent

  SendJoinRequest = function(sessionId, isRetry)
    PruneAgedSessionRuntimeTracking(GetProfileCheckpointSyncTime())
    local request = sessionRuntime.pendingJoinRequests[TrimText(sessionId)]
    if type(request) ~= "table" or request.confirmed then
      return false, "No pending join request."
    end
    local invite = type(request.invite) == "table" and request.invite or {}
    if TrimText(invite.sessionId) == "" or TrimText(invite.profileName) == "" or NormalizeCharacterKey(invite.host) == "" then
      return false, "Pending invite is incomplete."
    end

    local runtimeNow = GetProfileCheckpointSyncTime()
    request.queueAttempts = math.max(0, tonumber(request.queueAttempts) or 0) + 1
    request.lastQueuedAt = runtimeNow
    request.updatedAt = runtimeNow
    request.state = "QUEUED"
    local payloadDetails = type(request.payloadDetails) == "table" and request.payloadDetails or deps.GetMemberPayloadDetails(nil, true)
    request.payloadDetails = payloadDetails
    local localRevisionSummary = type(request.localRevisionSummary) == "table" and request.localRevisionSummary or deps.BuildEmptyRevisionSummary(invite.profileName, invite.profileId)
    local localLiveLootChecksum = request.existingSharedProfileName ~= ""
      and profileSyncMetaOps.buildSessionLiveLootChecksum(request.existingSharedProfileName, nil)
      or ""
    local successfulAttemptsBeforeQueue = math.max(0, tonumber(request.attempts) or 0)
    local function TrySendJoin(args)
      return SendComm("JOIN", "WHISPER", invite.host, unpack(args))
    end
    local joinSent, joinError = TrySendJoin({
      invite.sessionId,
      invite.profileName,
      request.selfKey,
      request.joinedAt,
      payloadDetails.addonVersion,
      payloadDetails.clientVersion,
      payloadDetails.className,
      payloadDetails.classFile,
      payloadDetails.specName,
      payloadDetails.specIcon,
      payloadDetails.localAutoPassEnabled and "1" or "0",
      invite.profileId,
      tostring(localRevisionSummary.settings or 0),
      tostring(localRevisionSummary.permissions or 0),
      tostring(localRevisionSummary.operational or 0),
      tostring(localRevisionSummary.updatedAt or 0),
      request.existingSharedProfileName ~= "" and "1" or "0",
      GetCommProtocolMarker(),
      TrimText(localRevisionSummary.settingsChecksum),
      TrimText(localRevisionSummary.permissionsChecksum),
      TrimText(localRevisionSummary.operationalChecksum),
      tostring(localRevisionSummary.loot or localRevisionSummary.operational or 0),
      tostring(localRevisionSummary.session or localRevisionSummary.operational or 0),
      TrimText(localRevisionSummary.lootChecksum),
      TrimText(localRevisionSummary.sessionChecksum),
      localLiveLootChecksum
    })
    if not joinSent and string.find(tostring(joinError or ""), "Payload exceeds safe addon message length", 1, true) then
      joinSent, joinError = TrySendJoin({
        invite.sessionId,
        invite.profileName,
        request.selfKey,
        request.joinedAt,
        payloadDetails.addonVersion,
        payloadDetails.clientVersion,
        payloadDetails.className,
        payloadDetails.classFile,
        payloadDetails.specName,
        payloadDetails.specIcon,
        payloadDetails.localAutoPassEnabled and "1" or "0",
        invite.profileId,
        tostring(localRevisionSummary.settings or 0),
        tostring(localRevisionSummary.permissions or 0),
        tostring(localRevisionSummary.operational or 0),
        tostring(localRevisionSummary.updatedAt or 0),
        request.existingSharedProfileName ~= "" and "1" or "0",
        GetCommProtocolMarker()
      })
    end

    if joinSent then
      if math.max(0, tonumber(request.attempts) or 0) <= successfulAttemptsBeforeQueue then
        sessionLifecycleOps.schedulePendingJoinRetryCheck(
          sessionId,
          sessionConfig.joinAckQueuePollSeconds,
          true
        )
      end
    else
      request.state = "QUEUE_FAILED"
      request.lastError = tostring(joinError or "")
      Print(sessionLifecycleOps.buildFlowNoticeText("join_request_failed", {
        error = joinError,
      }))
      sessionLifecycleOps.schedulePendingJoinRetryCheck(
        sessionId,
        sessionConfig.joinAckFallbackDelaySeconds,
        true
      )
    end

    return joinSent, joinError
  end

  INTERNAL_API.LIDCOUNCIL_EnsureSessionPopup_Impl = function()
    if type(StaticPopupDialogs) ~= "table" or StaticPopupDialogs.LIDCOUNCIL_SESSION_INVITE then
      return
    end

    StaticPopupDialogs.LIDCOUNCIL_SESSION_INVITE = {
      text = "%s invited you to a LidCouncil session.",
      button1 = YES,
      button2 = NO,
      timeout = 0,
      whileDead = 1,
      hideOnEscape = 1,
      preferredIndex = 3,
      OnAccept = function(self, data)
        local invite = data or self.data
        if not invite then
          return
        end
        local inviteProtocolVersion = math.max(1, tonumber(invite.protocolVersion) or 1)
        if inviteProtocolVersion ~= COMM_PROTOCOL_VERSION then
          local selfKey = NormalizeCharacterKey(GetCharacterKey() or "Unknown")
          SendComm("DECLINE", "WHISPER", invite.host, invite.sessionId, invite.profileName, selfKey)
          Print(sessionLifecycleOps.buildFlowNoticeText("invite_incompatible_build", {
            profileName = invite.profileName,
          }))
          sessionRuntime.pendingInvites[invite.sessionId] = nil
          return
        end
        SetLocalAutoPassEnabled(true)
        sessionRuntime.pendingJoinRequests[invite.sessionId] = BuildPendingJoinRequest(invite)
        SendJoinRequest(invite.sessionId, false)
        sessionUiOps.refreshAutoPassSection()
      end,
      OnCancel = function(self, data)
        local invite = data or self.data
        if not invite then
          return
        end
        local selfKey = NormalizeCharacterKey(GetCharacterKey() or "Unknown")
        SendComm("DECLINE", "WHISPER", invite.host, invite.sessionId, invite.profileName, selfKey)
        sessionRuntime.pendingInvites[invite.sessionId] = nil
        sessionRuntime.pendingJoinRequests[invite.sessionId] = nil
      end,
    }
  end

  local function ShowSessionInvite(invite)
    INTERNAL_API.LIDCOUNCIL_EnsureSessionPopup_Impl()
    if type(StaticPopupDialogs) ~= "table" or type(StaticPopupDialogs.LIDCOUNCIL_SESSION_INVITE) ~= "table" then
      return false, "popup_definition_unavailable"
    end
    if type(StaticPopup_Show) ~= "function" then
      return false, "popup_api_unavailable"
    end
    local dialog = StaticPopup_Show("LIDCOUNCIL_SESSION_INVITE", tostring(invite.host), tostring(invite.profileName), invite)
    if not dialog then
      return false, "popup_display_failed"
    end
    dialog.data = invite
    if dialog.text and dialog.text.SetText then
      dialog.text:SetText(sessionLifecycleOps.buildInvitePopupText({
        host = invite.host,
        profileName = invite.profileName,
        status = invite.status,
      }))
    end
    return true
  end

  local BuildMemberBroadcastPayloadState
  local BuildMemberBroadcastPayloadSignature
  profileSyncMetaOps.buildMemberBroadcastPayloadBundle = function(profileName, sessionId, memberKey, memberData, opts)
    opts = type(opts) == "table" and opts or {}
    local payloadState = type(opts.payloadState) == "table"
      and opts.payloadState
      or BuildMemberBroadcastPayloadState(profileName, sessionId, memberKey, memberData)
    local payloadSignature = TrimText(opts.payloadSignature)
    if payloadSignature == "" then
      payloadSignature = BuildMemberBroadcastPayloadSignature(payloadState)
    end
    local visibleStateSignature = TrimText(opts.visibleStateSignature)
    return {
      payloadState = payloadState,
      payloadSignature = payloadSignature,
      visibleStateSignature = visibleStateSignature,
    }
  end

  local function BroadcastMember(profileName, sessionId, memberKey, memberData, channel, target, opts)
    local details = type(memberData) == "table" and memberData or {}
    local broadcastOptions = type(opts) == "table" and opts or {}
    local resolvedProfileName = TrimText(profileName)
    local runtimeNow = GetProfileCheckpointSyncTime()
    PruneAgedSessionRuntimeTracking(runtimeNow)
    local distribution = channel or deps.GetGroupDistribution()
    if not distribution then
      return false
    end
    local resolvedDistribution = string.upper(TrimText(distribution))
    local resolvedTarget = NormalizeCharacterKey(target)
    local resolvedSessionId = TrimText(sessionId)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    local broadcastKey = string.lower(resolvedSessionId) .. "|" .. string.lower(resolvedMemberKey)
    local memberStatus = string.upper(TrimText(details.status or "JOINED"))
    local allowIdenticalRepeat = broadcastOptions.allowIdenticalRepeat == true
    local payloadBundle = type(broadcastOptions.payloadBundle) == "table"
      and broadcastOptions.payloadBundle
      or (type(profileSyncMetaOps.buildMemberBroadcastPayloadBundle) == "function"
        and profileSyncMetaOps.buildMemberBroadcastPayloadBundle(profileName, sessionId, memberKey, details, broadcastOptions)
        or nil)
    local payloadSignature = type(payloadBundle) == "table"
      and TrimText(payloadBundle.payloadSignature)
      or ""
    if payloadSignature == "" then
      payloadSignature = TrimText(broadcastOptions.payloadSignature)
    end
    local lastBroadcastStateKey = nil
    local recentBroadcastState = nil
    if resolvedSessionId ~= ""
      and resolvedMemberKey ~= ""
      and resolvedTarget == ""
      and resolvedDistribution ~= ""
      and resolvedDistribution ~= "WHISPER"
    then
      lastBroadcastStateKey = string.lower(resolvedSessionId)
        .. "|broadcast|"
        .. string.lower(resolvedDistribution)
        .. "|"
        .. string.lower(resolvedMemberKey)
      recentBroadcastState = sessionRuntime.recentMemberSnapshotWhispers[lastBroadcastStateKey]
    end
    local canCoalesceGroupBroadcast = resolvedSessionId ~= ""
      and resolvedMemberKey ~= ""
      and resolvedTarget == ""
      and resolvedDistribution ~= ""
      and resolvedDistribution ~= "WHISPER"
      and broadcastOptions.skipCoalesce ~= true
      and broadcastOptions.forceImmediate ~= true
      and memberStatus == "JOINED"
    if canCoalesceGroupBroadcast then
      if type(recentBroadcastState) == "table"
        and INTERNAL_API.LIDCOUNCIL_ShouldSuppressStableMemberPublication_Impl(
          recentBroadcastState.signature,
          payloadSignature,
          allowIdenticalRepeat
        )
      then
        return true
      end
      local pending = sessionRuntime.pendingSessionMemberBroadcasts[broadcastKey]
      if type(pending) == "table" then
        local pendingUpdatedAt = math.max(0, tonumber(pending.updatedAt or pending.queuedAt) or 0)
        if pendingUpdatedAt <= 0
          or (runtimeNow - pendingUpdatedAt) >= sessionConfig.pendingSessionMemberBroadcastRetentionSeconds
        then
          sessionRuntime.pendingSessionMemberBroadcasts[broadcastKey] = nil
          pending = nil
        end
      end
      if type(pending) == "table" then
        if type(pending.payloadBundle) == "table"
          and TrimText(pending.payloadBundle.payloadSignature) ~= ""
          and TrimText(pending.payloadBundle.payloadSignature) == payloadSignature
        then
          pending.suppressCheckpoint = pending.suppressCheckpoint == true and broadcastOptions.suppressCheckpoint == true
          pending.updatedAt = runtimeNow
          return true
        end
        pending.profileName = profileName
        pending.sessionId = sessionId
        pending.memberKey = memberKey
        pending.memberData = memberData
        pending.channel = channel
        pending.target = target
        pending.suppressCheckpoint = pending.suppressCheckpoint == true and broadcastOptions.suppressCheckpoint == true
        pending.payloadBundle = payloadBundle
        pending.updatedAt = runtimeNow
        return true
      end
      local token = string.format("MBR-%d-%d", tonumber(time and time() or 0) or 0, math.random(1000, 9999))
      sessionRuntime.pendingSessionMemberBroadcasts[broadcastKey] = {
        token = token,
        profileName = profileName,
        sessionId = sessionId,
        memberKey = memberKey,
        memberData = memberData,
        channel = channel,
        target = target,
        suppressCheckpoint = broadcastOptions.suppressCheckpoint == true,
        payloadBundle = payloadBundle,
        queuedAt = runtimeNow,
        updatedAt = runtimeNow,
      }
      local function FlushPendingBroadcast()
        local currentPending = sessionRuntime.pendingSessionMemberBroadcasts[broadcastKey]
        if type(currentPending) ~= "table" or currentPending.token ~= token then
          return
        end
        sessionRuntime.pendingSessionMemberBroadcasts[broadcastKey] = nil
        BroadcastMember(
          currentPending.profileName,
          currentPending.sessionId,
          currentPending.memberKey,
          currentPending.memberData,
          currentPending.channel,
          currentPending.target,
          {
            payloadBundle = currentPending.payloadBundle,
            suppressCheckpoint = currentPending.suppressCheckpoint,
            skipCoalesce = true,
          }
        )
      end
      if type(Compat) == "table" and type(Compat.After) == "function" then
        Compat.After(sessionConfig.memberBroadcastCoalesceDelaySeconds, FlushPendingBroadcast)
      else
        FlushPendingBroadcast()
      end
      return true
    end
    if resolvedTarget == "" and resolvedDistribution ~= "" and resolvedDistribution ~= "WHISPER" then
      sessionRuntime.pendingSessionMemberBroadcasts[broadcastKey] = nil
    end
    local activeSession, activeProfileName = GetActiveLootSession()
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    local payloadState = type(payloadBundle) == "table"
      and type(payloadBundle.payloadState) == "table"
      and payloadBundle.payloadState
      or (type(broadcastOptions.payloadState) == "table"
        and broadcastOptions.payloadState
        or BuildMemberBroadcastPayloadState(profileName, sessionId, memberKey, details))
    if payloadSignature == "" then
      payloadSignature = BuildMemberBroadcastPayloadSignature(payloadState)
    end
    local visibleStateSignature = type(payloadBundle) == "table"
      and TrimText(payloadBundle.visibleStateSignature)
      or ""
    if visibleStateSignature == "" then
      visibleStateSignature = BuildSessionVisibleMemberStateSignature(payloadState)
    end
    if resolvedTarget ~= "" and not allowIdenticalRepeat then
      local targetWhisperStateKey = BuildTargetMemberSnapshotWhisperStateKey(
        resolvedSessionId,
        resolvedTarget,
        resolvedMemberKey
      )
      local recentTargetState = targetWhisperStateKey ~= "" and sessionRuntime.recentMemberSnapshotWhispers[targetWhisperStateKey] or nil
      local recentTargetSentAt = math.max(0, tonumber(type(recentTargetState) == "table" and recentTargetState.sentAt or 0) or 0)
      if targetWhisperStateKey ~= ""
        and type(recentTargetState) == "table"
        and (recentTargetSentAt <= 0 or (runtimeNow - recentTargetSentAt) >= sessionConfig.memberSnapshotWhisperRetentionSeconds)
      then
        sessionRuntime.recentMemberSnapshotWhispers[targetWhisperStateKey] = nil
        recentTargetState = nil
      end
      if type(recentTargetState) == "table"
        and INTERNAL_API.LIDCOUNCIL_ShouldSuppressStableMemberPublication_Impl(
          recentTargetState.signature,
          visibleStateSignature,
          allowIdenticalRepeat
        )
        and (runtimeNow - math.max(0, tonumber(recentTargetState.sentAt) or 0)) < sessionConfig.memberSnapshotWhisperDedupeSeconds
      then
        return true
      end
    end
    if type(recentBroadcastState) == "table"
      and INTERNAL_API.LIDCOUNCIL_ShouldSuppressStableMemberPublication_Impl(
        recentBroadcastState.signature,
        payloadSignature,
        allowIdenticalRepeat
      )
    then
      return true
    end
    local payloadStatus = FirstNonEmptyText(payloadState.status, "JOINED")
    local payloadJoinedAt = tonumber(payloadState.joinedAt) or (time and time() or 0)
    local payloadLeftAt = tonumber(payloadState.leftAt) or nil
    local settingsRevision = math.max(0, tonumber(payloadState.settingsRevision) or 0)
    local permissionsRevision = math.max(0, tonumber(payloadState.permissionsRevision) or 0)
    local operationalRevision = math.max(0, tonumber(payloadState.operationalRevision) or 0)
    local lootRevision = math.max(0, tonumber(payloadState.lootRevision) or operationalRevision)
    local sessionRevision = math.max(0, tonumber(payloadState.sessionRevision) or operationalRevision)
    local profileUpdatedAt = math.max(0, tonumber(payloadState.profileUpdatedAt) or 0)
    local settingsChecksum = TrimText(payloadState.settingsChecksum)
    local permissionsChecksum = TrimText(payloadState.permissionsChecksum)
    local operationalChecksum = TrimText(payloadState.operationalChecksum)
    local lootChecksum = TrimText(payloadState.lootChecksum)
    local sessionChecksum = TrimText(payloadState.sessionChecksum)
    local liveLootChecksum = TrimText(payloadState.liveLootChecksum)
    local archiveLootChecksum = TrimText(payloadState.archiveLootChecksum)
    local payloadLastSyncAt = tonumber(payloadState.lastSyncAt)
    local payloadLastDeltaRecoveryAt = math.max(0, tonumber(payloadState.lastDeltaRecoveryAt) or 0)
    local payloadLastDeltaRecoveryState = TrimText(payloadState.lastDeltaRecoveryState)
    local payloadLastDeltaRecoveryKind = TrimText(payloadState.lastDeltaRecoveryKind)
    local payloadLastDeltaRecoveryRequestedScope = TrimText(payloadState.lastDeltaRecoveryRequestedScope)
    local payloadLastDeltaRecoveryScopeEscalated = payloadState.lastDeltaRecoveryScopeEscalated == true
    local payloadLastDeltaRecoveryFullSnapshotFallback = payloadState.lastDeltaRecoveryFullSnapshotFallback == true
    local payloadLastDeltaRecoveryScopeEscalationKinds = TrimText(payloadState.lastDeltaRecoveryScopeEscalationKinds)
    local payloadLastDeltaRecoverySummary = TrimText(payloadState.lastDeltaRecoverySummary)
    local memberArgs = {
      sessionId,
      profileName,
      memberKey,
      payloadStatus,
      payloadJoinedAt,
      TrimText(payloadState.addonVersion),
      TrimText(payloadState.clientVersion),
      TrimText(payloadState.className),
      TrimText(payloadState.classFile),
      TrimText(payloadState.specName),
      TrimText(payloadState.specIcon),
      payloadState.localAutoPassEnabled and "1" or "0",
      TrimText(payloadState.profileMaster),
      TrimText(payloadState.role),
      FirstNonEmptyText(payloadState.sharedProfileId, payloadState.profileId),
      tostring(settingsRevision),
      tostring(permissionsRevision),
      tostring(operationalRevision),
      tostring(profileUpdatedAt),
      settingsChecksum,
      permissionsChecksum,
      operationalChecksum,
      tostring(tonumber(payloadLeftAt) or ""),
      tostring(lootRevision),
      tostring(sessionRevision),
      lootChecksum,
      sessionChecksum,
      liveLootChecksum,
      archiveLootChecksum,
      tostring(tonumber(payloadLastSyncAt) or ""),
      payloadLastDeltaRecoveryState,
      payloadLastDeltaRecoveryKind,
      payloadLastDeltaRecoveryRequestedScope,
      payloadLastDeltaRecoveryScopeEscalated and "1" or "0",
      payloadLastDeltaRecoveryFullSnapshotFallback and "1" or "0",
      payloadLastDeltaRecoveryScopeEscalationKinds,
      tostring(payloadLastDeltaRecoveryAt > 0 and payloadLastDeltaRecoveryAt or ""),
      payloadLastDeltaRecoverySummary,
      TrimText(payloadState.lootListArchiveChecksum),
      TrimText(payloadState.itemHistoryArchiveChecksum),
      TrimText(payloadState.sessionHistoryArchiveChecksum),
      TrimText(payloadState.funAwardsArchiveChecksum),
      TrimText(payloadState.hostSyncStatusMatrix),
      tostring(math.max(0, math.floor(tonumber(payloadState.hostSyncStatusGeneration) or 0)))
    }
    if type(profileSyncMetaOps.validateCommPayload) == "function" then
      local payloadSafe, payloadReason, payloadBytes = profileSyncMetaOps.validateCommPayload("MEMBER", unpack(memberArgs))
      if not payloadSafe then
        -- Recovery diagnostics are verbose and are not part of readiness.
        for index = 30, 38 do
          memberArgs[index] = ""
        end
        payloadSafe, payloadReason, payloadBytes = profileSyncMetaOps.validateCommPayload("MEMBER", unpack(memberArgs))
      end
      if not payloadSafe then
        -- Preserve the compact host status matrix and archive receipts before
        -- aggregate advisories.
        memberArgs[26] = ""
        memberArgs[27] = ""
        memberArgs[28] = ""
        memberArgs[29] = ""
        payloadSafe, payloadReason, payloadBytes = profileSyncMetaOps.validateCommPayload("MEMBER", unpack(memberArgs))
      end
      if not payloadSafe then
        for index = 39, 42 do
          memberArgs[index] = ""
        end
        payloadSafe, payloadReason, payloadBytes = profileSyncMetaOps.validateCommPayload("MEMBER", unpack(memberArgs))
      end
      if not payloadSafe then
        -- A long profile/session identity can still make the three checksum
        -- fields exceed WoW's limit. Revisions remain intact; the receiver
        -- treats omitted checksums as unchanged until the next profile state.
        memberArgs[20] = ""
        memberArgs[21] = ""
        memberArgs[22] = ""
        payloadSafe, payloadReason, payloadBytes = profileSyncMetaOps.validateCommPayload("MEMBER", unpack(memberArgs))
      end
      if not payloadSafe then
        -- Last-resort roster update: preserve identity, role, Auto-Pass,
        -- profile ID, revisions, and class file while omitting display-only
        -- strings that the receiver retains from an earlier member state.
        memberArgs[6] = ""
        memberArgs[7] = ""
        memberArgs[8] = ""
        memberArgs[10] = ""
        memberArgs[11] = ""
        memberArgs[13] = ""
        payloadSafe, payloadReason, payloadBytes = profileSyncMetaOps.validateCommPayload("MEMBER", unpack(memberArgs))
      end
      if not payloadSafe then
        if type(profileSyncMetaOps.recordOutboundPayloadReject) == "function" then
          profileSyncMetaOps.recordOutboundPayloadReject("MEMBER", payloadReason, payloadBytes, {
            sessionId = resolvedSessionId,
            target = resolvedTarget,
          })
        end
        if type(RecordProfileSyncDecision) == "function" then
          RecordProfileSyncDecision("broadcast_session_member", {
            action = "failed",
            sessionId = resolvedSessionId,
            profileName = resolvedProfileName,
            target = resolvedTarget,
            memberKey = resolvedMemberKey,
            reason = TrimText(payloadReason),
            error = "Member state exceeds the safe addon-message limit.",
          })
        end
        return false
      end
    end
    local sent = SendComm("MEMBER", distribution, target, unpack(memberArgs))
    if sent then
      local sentAt = GetProfileCheckpointSyncTime()
      if lastBroadcastStateKey ~= nil then
        sessionRuntime.recentMemberSnapshotWhispers[lastBroadcastStateKey] = {
          signature = payloadSignature,
          sentAt = sentAt,
        }
      end
      if resolvedSessionId ~= "" and resolvedMemberKey ~= "" and resolvedTarget ~= "" then
        local targetWhisperStateKey = BuildTargetMemberSnapshotWhisperStateKey(
          resolvedSessionId,
          resolvedTarget,
          resolvedMemberKey
        )
        if targetWhisperStateKey ~= "" then
          sessionRuntime.recentMemberSnapshotWhispers[targetWhisperStateKey] = {
            signature = visibleStateSignature,
            sentAt = sentAt,
          }
        end
      end
      if type(activeSession) == "table"
          and TrimText(activeSession.id) == TrimText(sessionId)
          and DoesActiveSessionMatch(activeSession, activeProfileName, sessionId, profileName)
          and AreCharacterKeysSame(activeSession.host or "", selfKey) then
        if broadcastOptions.suppressCheckpoint ~= true then
          QueueSessionRecordCheckpoint(profileName, sessionId, "session_member_checkpoint", memberKey, {
            prebuiltCheckpointState = type(profileSyncMetaOps.buildSessionMemberCheckpointState) == "function"
              and profileSyncMetaOps.buildSessionMemberCheckpointState(profileName, sessionId, memberKey, details)
              or nil,
          })
        end
      end
    end
    return sent
  end

  profileSyncMetaOps.publishJoinManifestValidationState = function(sessionId, memberKey, opts)
    local resolvedSessionId = TrimText(sessionId)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    local activeSession, activeProfileName = GetActiveLootSession()
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if resolvedSessionId == "" or resolvedMemberKey == ""
      or type(activeSession) ~= "table"
      or TrimText(activeSession.id) ~= resolvedSessionId
      or not AreCharacterKeysSame(activeSession.host or "", selfKey)
    then
      return false
    end
    local member = select(1, FindSessionMember(activeSession, resolvedMemberKey))
    if type(member) ~= "table" or tostring(member.status or "JOINED") ~= "JOINED" then
      return false
    end
    return BroadcastMember(
      activeProfileName,
      resolvedSessionId,
      resolvedMemberKey,
      member,
      nil,
      nil,
      INTERNAL_API.LIDCOUNCIL_BuildReadinessPublicationOptions_Impl(opts)
    ) == true
  end

  BuildMemberBroadcastPayloadState = function(profileName, sessionId, memberKey, memberData)
    local details = type(memberData) == "table" and memberData or {}
    local activeSession, activeProfileName = GetActiveLootSession()
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    local resolvedProfileName = TrimText(profileName)
    local resolvedSessionId = TrimText(sessionId)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    local isActiveHostPublisher = type(activeSession) == "table"
      and resolvedSessionId ~= ""
      and resolvedProfileName ~= ""
      and TrimText(activeSession.id) == resolvedSessionId
      and DoesActiveSessionMatch(activeSession, activeProfileName, resolvedSessionId, resolvedProfileName)
      and AreCharacterKeysSame(activeSession.host or "", selfKey)
    local isHostSelfRow = isActiveHostPublisher
      and AreCharacterKeysSame(resolvedMemberKey, selfKey)
    local payloadDetails = deps.GetMemberPayloadDetails(details, isHostSelfRow)
    local profileMaster = FirstNonEmptyText(details.profileMaster, deps.GetLootProfileMaster(resolvedProfileName))
    local memberRole = FirstNonEmptyText(details.role, deps.GetLootProfileRole(resolvedProfileName, resolvedMemberKey))
    local profileId = isHostSelfRow
      and TrimText(select(1, deps.GetLootProfileId(resolvedProfileName)) or "")
      or FirstNonEmptyText(details.sharedProfileId, details.profileId, select(1, deps.GetLootProfileId(resolvedProfileName)))
    local revisionSummary = type(details.revisionSummary) == "table" and details.revisionSummary or GetLootProfileRevisionSummary(resolvedProfileName)
    local operationalRevision = isHostSelfRow
      and (tonumber(revisionSummary and revisionSummary.operational) or 0)
      or (tonumber(details.operationalRevision) or tonumber(revisionSummary and revisionSummary.operational) or 0)
    local operationalChecksum = isHostSelfRow
      and TrimText(revisionSummary and revisionSummary.operationalChecksum)
      or FirstNonEmptyText(details.operationalChecksum, revisionSummary and revisionSummary.operationalChecksum)
    local archiveScopeChecksums = isHostSelfRow
      and profileSyncMetaOps.buildSessionArchiveScopeChecksums(resolvedProfileName, activeSession)
      or {}
    local payloadState = {
      status = details.status or "JOINED",
      joinedAt = tonumber(details.joinedAt) or (time and time() or 0),
      leftAt = tonumber(details.leftAt) or nil,
      addonVersion = payloadDetails.addonVersion,
      clientVersion = payloadDetails.clientVersion,
      className = payloadDetails.className,
      classFile = payloadDetails.classFile,
      specName = payloadDetails.specName,
      specIcon = payloadDetails.specIcon,
      localAutoPassEnabled = payloadDetails.localAutoPassEnabled and true or false,
      profileMaster = profileMaster,
      role = memberRole,
      sharedProfileId = profileId,
      settingsRevision = isHostSelfRow
        and (tonumber(revisionSummary and revisionSummary.settings) or 0)
        or (tonumber(details.settingsRevision) or tonumber(revisionSummary and revisionSummary.settings) or 0),
      permissionsRevision = isHostSelfRow
        and (tonumber(revisionSummary and revisionSummary.permissions) or 0)
        or (tonumber(details.permissionsRevision) or tonumber(revisionSummary and revisionSummary.permissions) or 0),
      operationalRevision = operationalRevision,
      lootRevision = isHostSelfRow
        and (tonumber(revisionSummary and revisionSummary.loot) or operationalRevision)
        or (tonumber(details.lootRevision) or tonumber(revisionSummary and revisionSummary.loot) or operationalRevision),
      sessionRevision = isHostSelfRow
        and (tonumber(revisionSummary and revisionSummary.session) or operationalRevision)
        or (tonumber(details.sessionRevision) or tonumber(revisionSummary and revisionSummary.session) or operationalRevision),
      profileUpdatedAt = isHostSelfRow
        and (tonumber(revisionSummary and revisionSummary.updatedAt) or 0)
        or (tonumber(details.profileUpdatedAt) or tonumber(revisionSummary and revisionSummary.updatedAt) or 0),
      settingsChecksum = isHostSelfRow
        and TrimText(revisionSummary and revisionSummary.settingsChecksum)
        or FirstNonEmptyText(details.settingsChecksum, revisionSummary and revisionSummary.settingsChecksum),
      permissionsChecksum = isHostSelfRow
        and TrimText(revisionSummary and revisionSummary.permissionsChecksum)
        or FirstNonEmptyText(details.permissionsChecksum, revisionSummary and revisionSummary.permissionsChecksum),
      operationalChecksum = operationalChecksum,
      lootChecksum = isHostSelfRow
        and FirstNonEmptyText(revisionSummary and revisionSummary.lootChecksum, operationalChecksum)
        or FirstNonEmptyText(details.lootChecksum, revisionSummary and revisionSummary.lootChecksum, operationalChecksum),
      sessionChecksum = isHostSelfRow
        and FirstNonEmptyText(revisionSummary and revisionSummary.sessionChecksum, operationalChecksum)
        or FirstNonEmptyText(details.sessionChecksum, revisionSummary and revisionSummary.sessionChecksum, operationalChecksum),
      liveLootChecksum = isHostSelfRow
        and profileSyncMetaOps.buildSessionLiveLootChecksum(resolvedProfileName, activeSession)
        or FirstNonEmptyText(details.liveLootChecksum),
      archiveLootChecksum = isHostSelfRow
        and profileSyncMetaOps.buildSessionArchiveLootChecksum(resolvedProfileName, activeSession)
        or FirstNonEmptyText(details.archiveLootChecksum),
      lootListArchiveChecksum = isHostSelfRow
        and TrimText(archiveScopeChecksums.lootList)
        or FirstNonEmptyText(details.lootListArchiveChecksum),
      itemHistoryArchiveChecksum = isHostSelfRow
        and TrimText(archiveScopeChecksums.itemHistory)
        or FirstNonEmptyText(details.itemHistoryArchiveChecksum),
      sessionHistoryArchiveChecksum = isHostSelfRow
        and TrimText(archiveScopeChecksums.sessionHistory)
        or FirstNonEmptyText(details.sessionHistoryArchiveChecksum),
      funAwardsArchiveChecksum = isHostSelfRow
        and TrimText(archiveScopeChecksums.funAwards)
        or FirstNonEmptyText(details.funAwardsArchiveChecksum),
      lastSyncAt = tonumber(details.lastSyncAt) or nil,
      lastDeltaRecoveryAt = math.max(0, tonumber(details.lastDeltaRecoveryAt) or 0),
      lastDeltaRecoveryState = TrimText(details.lastDeltaRecoveryState),
      lastDeltaRecoveryKind = TrimText(details.lastDeltaRecoveryKind),
      lastDeltaRecoveryRequestedScope = TrimText(details.lastDeltaRecoveryRequestedScope),
      lastDeltaRecoveryScopeEscalated = details.lastDeltaRecoveryScopeEscalated == true,
      lastDeltaRecoveryFullSnapshotFallback = details.lastDeltaRecoveryFullSnapshotFallback == true,
      lastDeltaRecoveryScopeEscalationKinds = TrimText(details.lastDeltaRecoveryScopeEscalationKinds),
      lastDeltaRecoverySummary = TrimText(details.lastDeltaRecoverySummary),
    }
    local hostStatusMatrix = isActiveHostPublisher
      and profileSyncMetaOps.buildHostMemberSyncStatusMatrix(
        activeSession,
        resolvedProfileName,
        resolvedMemberKey,
        payloadState
      )
      or nil
    payloadState.hostSyncStatusMatrix = profileSyncMetaOps.encodeHostMemberStatusMatrix(hostStatusMatrix)
    local storedMember = isActiveHostPublisher and select(1, FindSessionMember(activeSession, resolvedMemberKey)) or nil
    local statusTarget = type(storedMember) == "table" and storedMember or memberData
    if isActiveHostPublisher and type(statusTarget) == "table" and payloadState.hostSyncStatusMatrix ~= "" then
      local accepted, generation = profileSyncMetaOps.setHostMemberStatusMatrixValue(
        statusTarget,
        payloadState.hostSyncStatusMatrix,
        resolvedSessionId,
        nil,
        "host_publish",
        "accepted session proof"
      )
      if accepted == true then
        payloadState.hostSyncStatusGeneration = generation
        if type(memberData) == "table" and memberData ~= statusTarget then
          profileSyncMetaOps.setHostMemberStatusMatrixValue(
            memberData,
            payloadState.hostSyncStatusMatrix,
            resolvedSessionId,
            generation,
            "host_publish_alias",
            "accepted session proof"
          )
        end
      end
    end
    if payloadState.hostSyncStatusMatrix == "" and type(statusTarget) == "table" then
      local retainedMatrix = profileSyncMetaOps.getHostMemberStatusMatrixValue(statusTarget, resolvedSessionId)
      if type(profileSyncMetaOps.decodeHostMemberStatusMatrix(retainedMatrix)) == "table" then
        payloadState.hostSyncStatusMatrix = retainedMatrix
        payloadState.hostSyncStatusGeneration = profileSyncMetaOps.getHostMemberStatusMatrixGeneration(
          statusTarget,
          resolvedSessionId
        )
      end
    end
    return payloadState
  end

  BuildMemberBroadcastPayloadSignature = function(state)
    state = type(state) == "table" and state or {}
    return table.concat({
      TrimText(state.status or "JOINED"),
      tostring(math.max(0, tonumber(state.joinedAt) or 0)),
      tostring(math.max(0, tonumber(state.leftAt) or 0)),
      TrimText(state.addonVersion),
      TrimText(state.clientVersion),
      TrimText(state.className),
      TrimText(state.classFile),
      TrimText(state.specName),
      TrimText(state.specIcon),
      state.localAutoPassEnabled == true and "1" or "0",
      TrimText(state.profileMaster),
      TrimText(state.role),
      FirstNonEmptyText(state.sharedProfileId, state.profileId),
      tostring(math.max(0, tonumber(state.settingsRevision) or 0)),
      tostring(math.max(0, tonumber(state.permissionsRevision) or 0)),
      tostring(math.max(0, tonumber(state.operationalRevision) or 0)),
      tostring(math.max(0, tonumber(state.lootRevision) or 0)),
      tostring(math.max(0, tonumber(state.sessionRevision) or 0)),
      tostring(math.max(0, tonumber(state.profileUpdatedAt) or 0)),
      TrimText(state.settingsChecksum),
      TrimText(state.permissionsChecksum),
      TrimText(state.operationalChecksum),
      TrimText(state.lootChecksum),
      TrimText(state.sessionChecksum),
      TrimText(state.liveLootChecksum),
      TrimText(state.archiveLootChecksum),
      TrimText(state.lootListArchiveChecksum),
      TrimText(state.itemHistoryArchiveChecksum),
      TrimText(state.sessionHistoryArchiveChecksum),
      TrimText(state.funAwardsArchiveChecksum),
      TrimText(state.hostSyncStatusMatrix),
      tostring(math.max(0, tonumber(state.hostSyncStatusGeneration) or 0)),
    }, "\31")
  end

  BuildSessionVisibleMemberStateSignature = function(memberData)
    if type(memberData) ~= "table" then
      return ""
    end
    return table.concat({
      TrimText(memberData.status or "JOINED"),
      tostring(math.max(0, tonumber(memberData.joinedAt) or 0)),
      tostring(math.max(0, tonumber(memberData.leftAt) or 0)),
      TrimText(memberData.addonVersion),
      TrimText(memberData.clientVersion),
      TrimText(memberData.className),
      TrimText(memberData.classFile),
      TrimText(memberData.specName),
      TrimText(memberData.specIcon),
      memberData.localAutoPassEnabled == true and "1" or "0",
      TrimText(memberData.profileMaster),
      TrimText(memberData.role),
      FirstNonEmptyText(memberData.sharedProfileId, memberData.profileId),
      tostring(math.max(0, tonumber(memberData.settingsRevision) or 0)),
      tostring(math.max(0, tonumber(memberData.permissionsRevision) or 0)),
      tostring(math.max(0, tonumber(memberData.operationalRevision) or 0)),
      tostring(math.max(0, tonumber(memberData.lootRevision) or 0)),
      tostring(math.max(0, tonumber(memberData.sessionRevision) or 0)),
      tostring(math.max(0, tonumber(memberData.profileUpdatedAt) or 0)),
      TrimText(memberData.settingsChecksum),
      TrimText(memberData.permissionsChecksum),
      TrimText(memberData.operationalChecksum),
      TrimText(memberData.lootChecksum),
      TrimText(memberData.sessionChecksum),
      TrimText(memberData.liveLootChecksum),
      TrimText(memberData.archiveLootChecksum),
      TrimText(memberData.lootListArchiveChecksum),
      TrimText(memberData.itemHistoryArchiveChecksum),
      TrimText(memberData.sessionHistoryArchiveChecksum),
      TrimText(memberData.funAwardsArchiveChecksum),
      profileSyncMetaOps.getHostMemberStatusMatrixValue(memberData),
      TrimText(memberData.profileApplyAckPhase),
      TrimText(memberData.profileApplyPendingId),
      TrimText(memberData.profileApplyPendingKind),
    }, "\31")
  end

  local function IsSessionMemberVisibleForCurrentState(memberData)
    if type(memberData) ~= "table" then
      return false
    end
    return string.upper(TrimText(memberData.status or "JOINED")) ~= "REMOVED"
  end

  BuildTargetMemberSnapshotWhisperStateKey = function(sessionId, targetMemberKey, memberKey)
    local resolvedSessionId = TrimText(sessionId)
    local resolvedTargetMemberKey = NormalizeCharacterKey(targetMemberKey)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if resolvedSessionId == "" or resolvedTargetMemberKey == "" then
      return ""
    end
    local key = string.lower(resolvedSessionId) .. "|" .. string.lower(resolvedTargetMemberKey) .. "|"
    if resolvedMemberKey ~= "" then
      key = key .. string.lower(resolvedMemberKey)
    end
    return key
  end

  local function BuildRecentStatePacketSendKey(kind, sessionId, profileName, memberKey, distribution, target)
    local resolvedKind = string.upper(TrimText(kind))
    local resolvedSessionId = string.lower(TrimText(sessionId))
    local resolvedProfileName = string.lower(TrimText(profileName))
    local resolvedMemberKey = string.lower(NormalizeCharacterKey(memberKey))
    local resolvedDistribution = string.upper(TrimText(distribution))
    local resolvedTarget = string.lower(NormalizeCharacterKey(target))
    if resolvedKind == "" or resolvedSessionId == "" or resolvedProfileName == "" or resolvedMemberKey == "" then
      return ""
    end
    return table.concat({
      resolvedKind,
      resolvedSessionId,
      resolvedProfileName,
      resolvedMemberKey,
      resolvedDistribution,
      resolvedTarget,
    }, "|")
  end

  local function GetRecentStatePacketSendInfo(stateKey, now)
    local resolvedKey = TrimText(stateKey)
    if resolvedKey == "" then
      return nil
    end
    local currentTime = math.max(0, tonumber(now) or 0)
    if currentTime <= 0 then
      currentTime = GetProfileCheckpointSyncTime()
    end
    local stateInfo = sessionRuntime.recentStatePacketSends[resolvedKey]
    local sentAt = math.max(0, tonumber(type(stateInfo) == "table" and stateInfo.sentAt or 0) or 0)
    if type(stateInfo) == "table"
      and (sentAt <= 0 or (currentTime - sentAt) >= sessionConfig.statePacketSendRetentionSeconds)
    then
      sessionRuntime.recentStatePacketSends[resolvedKey] = nil
      return nil
    end
    return type(stateInfo) == "table" and stateInfo or nil
  end

  local function RememberRecentStatePacketSend(stateKey, signature, now)
    local resolvedKey = TrimText(stateKey)
    local resolvedSignature = TrimText(signature)
    if resolvedKey == "" or resolvedSignature == "" then
      return false
    end
    sessionRuntime.recentStatePacketSends[resolvedKey] = {
      signature = resolvedSignature,
      sentAt = math.max(0, tonumber(now) or GetProfileCheckpointSyncTime()),
    }
    return true
  end

  local function GetTargetedMemberSnapshotSendDecision(sessionId, targetMemberKey, memberKey, payloadState, opts)
    opts = type(opts) == "table" and opts or {}
    local resolvedSessionId = TrimText(sessionId)
    local resolvedTargetMemberKey = NormalizeCharacterKey(targetMemberKey)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    local signature = BuildSessionVisibleMemberStateSignature(payloadState)
    local now = tonumber(opts.now) or GetProfileCheckpointSyncTime()
    PruneAgedSessionRuntimeTracking(now)
    local dedupeKey = BuildTargetMemberSnapshotWhisperStateKey(
      resolvedSessionId,
      resolvedTargetMemberKey,
      resolvedMemberKey
    )
    local recentState = dedupeKey ~= "" and sessionRuntime.recentMemberSnapshotWhispers[dedupeKey] or nil
    local recentSentAt = math.max(0, tonumber(type(recentState) == "table" and recentState.sentAt or 0) or 0)
    if dedupeKey ~= ""
      and type(recentState) == "table"
      and (recentSentAt <= 0 or (now - recentSentAt) >= sessionConfig.memberSnapshotWhisperRetentionSeconds)
    then
      sessionRuntime.recentMemberSnapshotWhispers[dedupeKey] = nil
      recentState = nil
    end
    local shouldSend = true
    if opts.alwaysInclude ~= true then
      if opts.onlyChangedForTarget == true
        and type(recentState) == "table"
        and recentState.signature == signature
      then
        shouldSend = false
      else
        if type(recentState) == "table"
          and recentState.signature == signature
          and (now - (tonumber(recentState.sentAt) or 0)) < sessionConfig.memberSnapshotWhisperDedupeSeconds
        then
          shouldSend = false
        end
      end
    end
    return {
      shouldSend = shouldSend,
      signature = signature,
      dedupeKey = dedupeKey,
      recentState = recentState,
    }
  end

  local function DidTargetedHostMemberRefreshCoverRow(refreshDetail)
    return type(refreshDetail) == "table"
      and (refreshDetail.broadcastSent == true or refreshDetail.skippedForTarget == true)
      or false
  end

  local function GetSessionMemberDeltaRecoveryDisplayState(memberData)
    if type(memberData) ~= "table" then
      return ""
    end
    local deltaRecoveryState = string.lower(TrimText(memberData.lastDeltaRecoveryState))
    local deltaRecoveryAt = math.max(0, tonumber(memberData.lastDeltaRecoveryAt) or 0)
    local memberLastSyncAt = math.max(0, tonumber(memberData.lastSyncAt) or 0)
    if deltaRecoveryState ~= "" then
      if deltaRecoveryState == "deferred" and memberLastSyncAt > 0 and memberLastSyncAt >= deltaRecoveryAt then
        return "RECOVERED"
      end
      return string.upper(deltaRecoveryState)
    end
    if memberData.lastDeltaRecoveryFullSnapshotFallback == true then
      return "FULL_FALLBACK"
    end
    if memberData.lastDeltaRecoveryScopeEscalated == true then
      return "WIDENED"
    end
    if TrimText(memberData.lastDeltaRecoveryKind) == "aligned" then
      return "ALIGNED"
    end
    if deltaRecoveryAt > 0 then
      return "RECOVERED"
    end
    return ""
  end

  INTERNAL_API.LIDCOUNCIL_BuildMemberProfileStateSignature = function(state)
    state = type(state) == "table" and state or {}
    return table.concat({
      FirstNonEmptyText(state.sharedProfileId, state.profileId),
      tostring(math.max(0, tonumber(state.settingsRevision) or 0)),
      tostring(math.max(0, tonumber(state.permissionsRevision) or 0)),
      tostring(math.max(0, tonumber(state.operationalRevision) or 0)),
      tostring(math.max(0, tonumber(state.lootRevision) or 0)),
      tostring(math.max(0, tonumber(state.sessionRevision) or 0)),
      tostring(math.max(0, tonumber(state.profileUpdatedAt) or 0)),
      TrimText(state.settingsChecksum),
      TrimText(state.permissionsChecksum),
      TrimText(state.operationalChecksum),
      TrimText(state.lootChecksum),
      TrimText(state.sessionChecksum),
      TrimText(state.liveLootChecksum),
      TrimText(state.archiveLootChecksum),
      TrimText(state.lootListArchiveChecksum),
      TrimText(state.itemHistoryArchiveChecksum),
      TrimText(state.sessionHistoryArchiveChecksum),
      TrimText(state.funAwardsArchiveChecksum),
    }, "\31")
  end

  INTERNAL_API.LIDCOUNCIL_HasMemberSharedProfileState = function(state)
    state = type(state) == "table" and state or {}
    return TrimText(state.sharedProfileId) ~= ""
      or math.max(
        0,
        tonumber(state.settingsRevision) or 0,
        tonumber(state.permissionsRevision) or 0,
        tonumber(state.lootRevision) or 0,
        tonumber(state.sessionRevision) or 0
      ) > 0
  end

  INTERNAL_API.LIDCOUNCIL_BuildMemberProfileStateOrderingComparison = function(existingState, incomingState, opts)
    opts = type(opts) == "table" and opts or {}
    existingState = type(existingState) == "table" and existingState or {}
    incomingState = type(incomingState) == "table" and incomingState or {}
    local includeOperationalRevision = opts.includeOperationalRevision ~= false
    local existingProfileUpdatedAt = math.max(0, tonumber(existingState.profileUpdatedAt) or 0)
    local incomingProfileUpdatedAt = math.max(0, tonumber(incomingState.profileUpdatedAt) or 0)
    local existingSettingsRevision = math.max(0, tonumber(existingState.settingsRevision) or 0)
    local existingPermissionsRevision = math.max(0, tonumber(existingState.permissionsRevision) or 0)
    local existingOperationalRevision = math.max(0, tonumber(existingState.operationalRevision) or 0)
    local existingLootRevision = math.max(0, tonumber(existingState.lootRevision) or existingOperationalRevision)
    local existingSessionRevision = math.max(0, tonumber(existingState.sessionRevision) or existingOperationalRevision)
    local incomingSettingsRevision = math.max(0, tonumber(incomingState.settingsRevision) or 0)
    local incomingPermissionsRevision = math.max(0, tonumber(incomingState.permissionsRevision) or 0)
    local incomingOperationalRevision = math.max(0, tonumber(incomingState.operationalRevision) or 0)
    local incomingLootRevision = math.max(0, tonumber(incomingState.lootRevision) or incomingOperationalRevision)
    local incomingSessionRevision = math.max(0, tonumber(incomingState.sessionRevision) or incomingOperationalRevision)
    local incomingNoNewerRevisions =
      incomingSettingsRevision <= existingSettingsRevision
      and incomingPermissionsRevision <= existingPermissionsRevision
      and (not includeOperationalRevision or incomingOperationalRevision <= existingOperationalRevision)
      and incomingLootRevision <= existingLootRevision
      and incomingSessionRevision <= existingSessionRevision
    local incomingAnyOlderRevision =
      incomingSettingsRevision < existingSettingsRevision
      or incomingPermissionsRevision < existingPermissionsRevision
      or (includeOperationalRevision and incomingOperationalRevision < existingOperationalRevision)
      or incomingLootRevision < existingLootRevision
      or incomingSessionRevision < existingSessionRevision
    return {
      existingProfileUpdatedAt = existingProfileUpdatedAt,
      incomingProfileUpdatedAt = incomingProfileUpdatedAt,
      incomingNoNewerRevisions = incomingNoNewerRevisions,
      incomingAnyOlderRevision = incomingAnyOlderRevision,
    }
  end

  INTERNAL_API.LIDCOUNCIL_ShouldSkipIncomingProfileState = function(existingMember, incomingState)
    existingMember = type(existingMember) == "table" and existingMember or nil
    incomingState = type(incomingState) == "table" and incomingState or {}
    if type(existingMember) ~= "table" then
      return false
    end

    if INTERNAL_API.LIDCOUNCIL_BuildMemberProfileStateSignature(existingMember)
      == INTERNAL_API.LIDCOUNCIL_BuildMemberProfileStateSignature(incomingState)
      and tonumber(existingMember.lastSyncAt)
    then
      return true
    end

    local orderingComparison = INTERNAL_API.LIDCOUNCIL_BuildMemberProfileStateOrderingComparison(existingMember, incomingState)
    if TrimText(existingMember.sharedProfileId) ~= ""
      and TrimText(incomingState.sharedProfileId) == ""
      and orderingComparison.incomingProfileUpdatedAt <= orderingComparison.existingProfileUpdatedAt
      and orderingComparison.incomingNoNewerRevisions
    then
      return true
    end
    if orderingComparison.incomingProfileUpdatedAt <= orderingComparison.existingProfileUpdatedAt
      and orderingComparison.incomingNoNewerRevisions
      and (
        orderingComparison.incomingProfileUpdatedAt < orderingComparison.existingProfileUpdatedAt
        or orderingComparison.incomingAnyOlderRevision
      )
    then
      return true
    end
    return false
  end

  INTERNAL_API.LIDCOUNCIL_ShouldSkipIncomingSessionMemberState = function(existingMember, incomingState, opts)
    opts = type(opts) == "table" and opts or {}
    existingMember = type(existingMember) == "table" and existingMember or nil
    incomingState = type(incomingState) == "table" and incomingState or {}
    if type(existingMember) ~= "table" then
      return false
    end

    local previousVisibleState = FirstNonEmptyText(
      opts.previousVisibleState,
      BuildSessionVisibleMemberStateSignature(existingMember)
    )
    if previousVisibleState == BuildSessionVisibleMemberStateSignature(incomingState) then
      return true
    end

    local incomingJoinedAt = math.max(0, tonumber(incomingState.joinedAt) or 0)
    local existingJoinedAt = math.max(0, tonumber(existingMember.joinedAt) or 0)
    if incomingJoinedAt < existingJoinedAt then
      return true
    end
    if incomingJoinedAt ~= existingJoinedAt then
      return false
    end

    local existingStatus = string.upper(TrimText(existingMember.status or "JOINED"))
    local normalizedIncomingStatus = string.upper(TrimText(incomingState.status or "JOINED"))
    if existingStatus == "REMOVED" and normalizedIncomingStatus ~= "REMOVED" then
      return true
    end
    if existingStatus == "LEFT" and normalizedIncomingStatus == "JOINED" then
      return true
    end

    local incomingLeftAt = math.max(0, tonumber(incomingState.leftAt) or 0)
    local existingLeftAt = math.max(0, tonumber(existingMember.leftAt) or 0)
    if incomingLeftAt > 0 and existingLeftAt > 0 and incomingLeftAt < existingLeftAt then
      return true
    end
    if incomingLeftAt ~= existingLeftAt then
      return false
    end

    local orderingComparison = INTERNAL_API.LIDCOUNCIL_BuildMemberProfileStateOrderingComparison(
      existingMember,
      incomingState,
      { includeOperationalRevision = false }
    )
    if orderingComparison.incomingProfileUpdatedAt <= orderingComparison.existingProfileUpdatedAt
      and orderingComparison.incomingNoNewerRevisions
      and (
        orderingComparison.incomingProfileUpdatedAt < orderingComparison.existingProfileUpdatedAt
        or orderingComparison.incomingAnyOlderRevision
      )
    then
      return true
    end
    return false
  end

  profileSyncMetaOps.evaluateInboundStampedStateWrite = function(existingMember, incomingState, opts)
    opts = type(opts) == "table" and opts or {}
    existingMember = type(existingMember) == "table" and existingMember or nil
    incomingState = type(incomingState) == "table" and incomingState or {}
    if type(existingMember) ~= "table" then
      return {
        shouldSkip = false,
        shouldSkipBase = false,
        needsFreshSyncStamp = false,
        sameState = false,
      }
    end

    local stateKind = string.lower(TrimText(opts.stateKind))
    local sameState = false
    local shouldSkipBase = false
    if stateKind == "session_member" then
      local previousVisibleState = FirstNonEmptyText(
        opts.previousVisibleState,
        BuildSessionVisibleMemberStateSignature(existingMember)
      )
      sameState = previousVisibleState == BuildSessionVisibleMemberStateSignature(incomingState)
      shouldSkipBase = INTERNAL_API.LIDCOUNCIL_ShouldSkipIncomingSessionMemberState(existingMember, incomingState, {
        previousVisibleState = previousVisibleState,
      })
    else
      sameState = INTERNAL_API.LIDCOUNCIL_BuildMemberProfileStateSignature(existingMember)
        == INTERNAL_API.LIDCOUNCIL_BuildMemberProfileStateSignature(incomingState)
      shouldSkipBase = INTERNAL_API.LIDCOUNCIL_ShouldSkipIncomingProfileState(existingMember, incomingState)
    end
    local existingLastSyncAt = math.max(0, tonumber(existingMember.lastSyncAt) or 0)
    local existingRecoveryState = string.lower(TrimText(existingMember.lastDeltaRecoveryState))
    local existingRecoveryAt = math.max(0, tonumber(existingMember.lastDeltaRecoveryAt) or 0)
    local needsFreshSyncStamp = shouldSkipBase
      and sameState
      and (existingLastSyncAt <= 0 or (existingRecoveryState == "deferred" and existingLastSyncAt <= existingRecoveryAt))
      or false
    return {
      shouldSkip = shouldSkipBase and not needsFreshSyncStamp,
      shouldSkipBase = shouldSkipBase,
      needsFreshSyncStamp = needsFreshSyncStamp,
      sameState = sameState,
    }
  end

  local PruneStaleDeferredJoinMemberSnapshots

  profileSyncMetaOps.getDeferredJoinMemberSnapshotStore = function(activeSession, create)
    activeSession = type(activeSession) == "table" and activeSession or nil
    local sessionKey = string.lower(TrimText(type(activeSession) == "table" and activeSession.id or ""))
    if sessionKey == "" then
      return nil, ""
    end
    sessionRuntime.pendingDeferredMemberSnapshotsBySession = type(sessionRuntime.pendingDeferredMemberSnapshotsBySession) == "table"
      and sessionRuntime.pendingDeferredMemberSnapshotsBySession
      or {}
    local pendingDeferredSnapshots = sessionRuntime.pendingDeferredMemberSnapshotsBySession[sessionKey]
    if type(pendingDeferredSnapshots) ~= "table" and create == true then
      pendingDeferredSnapshots = {}
      sessionRuntime.pendingDeferredMemberSnapshotsBySession[sessionKey] = pendingDeferredSnapshots
    end
    return pendingDeferredSnapshots, sessionKey
  end

  INTERNAL_API.LIDCOUNCIL_ClearDeferredJoinMemberRows = function(activeSession, memberKey)
    activeSession = type(activeSession) == "table" and activeSession or nil
    local pendingDeferredSnapshots, sessionKey = profileSyncMetaOps.getDeferredJoinMemberSnapshotStore(activeSession, false)
    if type(pendingDeferredSnapshots) ~= "table" then
      return false
    end
    PruneStaleDeferredJoinMemberSnapshots(activeSession, GetProfileCheckpointSyncTime())
    pendingDeferredSnapshots = select(1, profileSyncMetaOps.getDeferredJoinMemberSnapshotStore(activeSession, false))
    if type(pendingDeferredSnapshots) ~= "table" then
      return false
    end
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if resolvedMemberKey == "" then
      sessionRuntime.pendingDeferredMemberSnapshotsBySession[sessionKey] = nil
      return true
    end
    if pendingDeferredSnapshots[resolvedMemberKey] == nil then
      return false
    end
    pendingDeferredSnapshots[resolvedMemberKey] = nil
    if not next(pendingDeferredSnapshots) then
      sessionRuntime.pendingDeferredMemberSnapshotsBySession[sessionKey] = nil
    end
    return true
  end

  local function NormalizeDeferredJoinMemberKeys(activeSession, memberKey, deferredMemberKeys, opts)
    opts = type(opts) == "table" and opts or {}
    activeSession = type(activeSession) == "table" and activeSession or nil
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    local requireMemberRows = opts.requireMemberRows == true
    local requireVisibleRows = opts.requireVisibleRows == true
    local normalizedDeferredMemberKeys = {}
    local includedDeferredMemberKeys = {}
    if type(deferredMemberKeys) ~= "table" then
      return normalizedDeferredMemberKeys
    end
    for _, deferredMemberKey in ipairs(deferredMemberKeys) do
      local resolvedDeferredMemberKey = NormalizeCharacterKey(deferredMemberKey)
      local existingMember = requireMemberRows and select(1, FindSessionMember(activeSession, resolvedDeferredMemberKey)) or true
      local visibleMember = existingMember
      if requireVisibleRows then
        visibleMember = type(existingMember) == "table" and IsSessionMemberVisibleForCurrentState(existingMember) and existingMember or nil
      end
      if resolvedDeferredMemberKey ~= ""
        and not AreCharacterKeysSame(resolvedDeferredMemberKey, resolvedMemberKey)
        and includedDeferredMemberKeys[resolvedDeferredMemberKey] ~= true
        and existingMember
        and (requireVisibleRows ~= true or visibleMember ~= nil)
      then
        includedDeferredMemberKeys[resolvedDeferredMemberKey] = true
        normalizedDeferredMemberKeys[#normalizedDeferredMemberKeys + 1] = resolvedDeferredMemberKey
      end
    end
    table.sort(normalizedDeferredMemberKeys)
    return normalizedDeferredMemberKeys
  end

  local function BuildDeferredJoinMemberSnapshotKeys(activeSession, memberKey)
    activeSession = type(activeSession) == "table" and activeSession or nil
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    local deferredMemberSnapshotKeys = {}
    if type(activeSession) ~= "table" or type(activeSession.members) ~= "table" or resolvedMemberKey == "" then
      return deferredMemberSnapshotKeys
    end

    for storedMemberKey, storedMember in pairs(activeSession.members) do
      local resolvedStoredMemberKey = NormalizeCharacterKey(storedMemberKey)
      if resolvedStoredMemberKey ~= ""
        and not AreCharacterKeysSame(resolvedStoredMemberKey, activeSession.host or "")
        and not AreCharacterKeysSame(resolvedStoredMemberKey, resolvedMemberKey)
        and IsSessionMemberVisibleForCurrentState(storedMember)
      then
        deferredMemberSnapshotKeys[#deferredMemberSnapshotKeys + 1] = resolvedStoredMemberKey
      end
    end
    table.sort(deferredMemberSnapshotKeys)
    return deferredMemberSnapshotKeys
  end

  profileSyncMetaOps.buildJoinRosterDeliveryPlan = function(activeSession, memberKey)
    activeSession = type(activeSession) == "table" and activeSession or nil
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    local immediateMemberKeys = {}
    local includedImmediateMemberKeys = {}
    if type(activeSession) ~= "table" or type(activeSession.members) ~= "table" or resolvedMemberKey == "" then
      return immediateMemberKeys, {}
    end

    local function IncludeImmediateMember(candidateKey)
      local resolvedCandidateKey = NormalizeCharacterKey(candidateKey)
      local candidateMember = select(1, FindSessionMember(activeSession, resolvedCandidateKey))
      if resolvedCandidateKey ~= ""
        and includedImmediateMemberKeys[resolvedCandidateKey] ~= true
        and type(candidateMember) == "table"
        and IsSessionMemberVisibleForCurrentState(candidateMember)
      then
        includedImmediateMemberKeys[resolvedCandidateKey] = true
        immediateMemberKeys[#immediateMemberKeys + 1] = resolvedCandidateKey
      end
    end

    -- The joiner only needs their own row and the host row to begin bootstrap.
    -- Older roster rows are non-blocking and are delivered after this member is
    -- ready, avoiding an O(n^2) immediate MEMBER burst when a raid joins at once.
    IncludeImmediateMember(activeSession.host)
    IncludeImmediateMember(resolvedMemberKey)
    table.sort(immediateMemberKeys)
    return immediateMemberKeys, BuildDeferredJoinMemberSnapshotKeys(activeSession, resolvedMemberKey)
  end
  INTERNAL_API.LIDCOUNCIL_BuildJoinRosterDeliveryPlan_Impl = profileSyncMetaOps.buildJoinRosterDeliveryPlan

  local function BuildDeferredJoinMemberKeySignature(memberKeys)
    local signatureParts = {}
    for _, memberKey in ipairs(type(memberKeys) == "table" and memberKeys or {}) do
      local resolvedMemberKey = NormalizeCharacterKey(memberKey)
      if resolvedMemberKey ~= "" then
        signatureParts[#signatureParts + 1] = resolvedMemberKey
      end
    end
    return table.concat(signatureParts, "\31")
  end

  local function GetDeferredJoinMemberSnapshotSignature(snapshot)
    if type(snapshot) ~= "table" then
      return ""
    end
    local existingSignature = TrimText(snapshot.signature)
    if existingSignature ~= "" then
      return existingSignature
    end
    return BuildDeferredJoinMemberKeySignature(snapshot.memberKeys)
  end

  PruneStaleDeferredJoinMemberSnapshots = function(activeSession, now)
    activeSession = type(activeSession) == "table" and activeSession or nil
    local pendingDeferredSnapshots, sessionKey = profileSyncMetaOps.getDeferredJoinMemberSnapshotStore(activeSession, false)
    if type(pendingDeferredSnapshots) ~= "table" then
      return false
    end
    local currentTime = math.max(0, tonumber(now) or 0)
    if currentTime <= 0 then
      currentTime = GetProfileCheckpointSyncTime()
    end
    local changed = false
    for pendingOwnerKey, pendingSnapshot in pairs(pendingDeferredSnapshots) do
      local updatedAt = math.max(0, tonumber(type(pendingSnapshot) == "table" and pendingSnapshot.updatedAt or 0) or 0)
      if updatedAt <= 0
        or (currentTime - updatedAt) >= sessionConfig.pendingDeferredMemberSnapshotRetentionSeconds
      then
        pendingDeferredSnapshots[pendingOwnerKey] = nil
        changed = true
      end
    end
    if not next(pendingDeferredSnapshots) then
      sessionRuntime.pendingDeferredMemberSnapshotsBySession[sessionKey] = nil
      changed = true
    end
    return changed
  end

  local function RemoveDeferredJoinMemberKeyFromPendingSnapshots(activeSession, memberKey)
    activeSession = type(activeSession) == "table" and activeSession or nil
    local pendingDeferredSnapshots, sessionKey = profileSyncMetaOps.getDeferredJoinMemberSnapshotStore(activeSession, false)
    if type(pendingDeferredSnapshots) ~= "table" then
      return false
    end
    PruneStaleDeferredJoinMemberSnapshots(activeSession, GetProfileCheckpointSyncTime())
    pendingDeferredSnapshots = select(1, profileSyncMetaOps.getDeferredJoinMemberSnapshotStore(activeSession, false))
    if type(pendingDeferredSnapshots) ~= "table" then
      return false
    end
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if resolvedMemberKey == "" then
      return false
    end
    local changed = false
    for pendingOwnerKey, pendingSnapshot in pairs(pendingDeferredSnapshots) do
      if type(pendingSnapshot) == "table" and type(pendingSnapshot.memberKeys) == "table" then
        local filteredMemberKeys = {}
        local includedMemberKeys = {}
        for _, pendingMemberKey in ipairs(pendingSnapshot.memberKeys) do
          local resolvedPendingMemberKey = NormalizeCharacterKey(pendingMemberKey)
          if resolvedPendingMemberKey ~= ""
            and not AreCharacterKeysSame(resolvedPendingMemberKey, resolvedMemberKey)
            and includedMemberKeys[resolvedPendingMemberKey] ~= true
          then
            includedMemberKeys[resolvedPendingMemberKey] = true
            filteredMemberKeys[#filteredMemberKeys + 1] = resolvedPendingMemberKey
          else
            changed = true
          end
        end
        table.sort(filteredMemberKeys)
        if #filteredMemberKeys == 0 then
          pendingDeferredSnapshots[pendingOwnerKey] = nil
        else
          pendingSnapshot.memberKeys = filteredMemberKeys
          pendingSnapshot.signature = BuildDeferredJoinMemberKeySignature(filteredMemberKeys)
          pendingSnapshot.updatedAt = GetProfileCheckpointSyncTime()
        end
      end
    end
    if not next(pendingDeferredSnapshots) then
      sessionRuntime.pendingDeferredMemberSnapshotsBySession[sessionKey] = nil
    end
    return changed
  end

  INTERNAL_API.LIDCOUNCIL_StoreDeferredJoinMemberRows = function(activeSession, profileName, memberKey, deferredMemberKeys)
    activeSession = type(activeSession) == "table" and activeSession or nil
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if type(activeSession) ~= "table" or resolvedMemberKey == "" then
      return false
    end
    PruneStaleDeferredJoinMemberSnapshots(activeSession, GetProfileCheckpointSyncTime())

    local normalizedDeferredMemberKeys = NormalizeDeferredJoinMemberKeys(activeSession, resolvedMemberKey, deferredMemberKeys, {
      requireMemberRows = true,
      requireVisibleRows = true,
    })
    if #normalizedDeferredMemberKeys == 0 then
      return INTERNAL_API.LIDCOUNCIL_ClearDeferredJoinMemberRows(activeSession, resolvedMemberKey)
    end

    local resolvedProfileName = FirstNonEmptyText(profileName, activeSession.profileName, activeSession.remoteProfileName)
    local deferredMemberKeySignature = BuildDeferredJoinMemberKeySignature(normalizedDeferredMemberKeys)
    local deferredSnapshotNow = GetProfileCheckpointSyncTime()
    local deferredSnapshotToken = string.format("DMS-%d-%d", tonumber(time and time() or 0) or 0, math.random(1000, 9999))
    local pendingDeferredSnapshots = select(1, profileSyncMetaOps.getDeferredJoinMemberSnapshotStore(activeSession, true))
    local existingPendingSnapshot = pendingDeferredSnapshots[resolvedMemberKey]
    if type(existingPendingSnapshot) == "table"
      and FirstNonEmptyText(existingPendingSnapshot.profileName) == resolvedProfileName
      and GetDeferredJoinMemberSnapshotSignature(existingPendingSnapshot) == deferredMemberKeySignature
    then
      existingPendingSnapshot.profileName = resolvedProfileName
      existingPendingSnapshot.signature = deferredMemberKeySignature
      existingPendingSnapshot.token = deferredSnapshotToken
      existingPendingSnapshot.updatedAt = deferredSnapshotNow
    else
      pendingDeferredSnapshots[resolvedMemberKey] = {
        profileName = resolvedProfileName,
        memberKeys = normalizedDeferredMemberKeys,
        signature = deferredMemberKeySignature,
        token = deferredSnapshotToken,
        updatedAt = deferredSnapshotNow,
      }
    end
    if type(Compat) == "table" and type(Compat.After) == "function" then
      local deferredCleanupSessionId = TrimText(activeSession.id)
      Compat.After(sessionConfig.pendingDeferredMemberSnapshotRetentionSeconds, function()
        local currentSession = GetActiveLootSession()
        currentSession = type(currentSession) == "table" and currentSession or nil
        if type(currentSession) ~= "table" or TrimText(currentSession.id) ~= deferredCleanupSessionId then
          return
        end
        local pendingDeferredSnapshots = select(1, profileSyncMetaOps.getDeferredJoinMemberSnapshotStore(currentSession, false))
        local pendingDeferredSnapshot = type(pendingDeferredSnapshots) == "table"
          and pendingDeferredSnapshots[resolvedMemberKey]
          or nil
        if type(pendingDeferredSnapshot) == "table" and pendingDeferredSnapshot.token == deferredSnapshotToken then
          INTERNAL_API.LIDCOUNCIL_ClearDeferredJoinMemberRows(currentSession, resolvedMemberKey)
        end
      end)
    end
    return true
  end

  INTERNAL_API.LIDCOUNCIL_GetDeferredJoinMemberBootstrapState = function(activeSession, profileName, memberKey, member, opts)
    opts = type(opts) == "table" and opts or {}
    activeSession = type(activeSession) == "table" and activeSession or nil
    member = type(member) == "table" and member or nil
    local resolvedProfileName = TrimText(profileName)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if type(member) ~= "table" then
      return "PENDING"
    end

    local displayState = TrimText(opts.displayState)
    if displayState ~= "" then
      local separatorIndex = string.find(displayState, "\30", 1, true)
      local displayBootstrapState = separatorIndex and string.sub(displayState, separatorIndex + 1) or displayState
      local resolvedDisplayBootstrapState = string.upper(TrimText(displayBootstrapState))
      if resolvedDisplayBootstrapState ~= "" then
        return resolvedDisplayBootstrapState
      end
    end
    if opts.bootstrapReady == true then
      return "READY"
    end

    local status = string.upper(TrimText(member.status or "JOINED"))
    if status == "DECLINED" then
      return "DECLINED"
    end
    if type(activeSession) == "table"
      and resolvedMemberKey ~= ""
      and AreCharacterKeysSame(resolvedMemberKey, activeSession.host or "")
    then
      return "READY"
    end
    local selfMemberKey = NormalizeCharacterKey(opts.selfMemberKey)
    if resolvedMemberKey ~= "" and selfMemberKey ~= "" and AreCharacterKeysSame(resolvedMemberKey, selfMemberKey) then
      if opts.localSharedProfileReady == false then
        return "PENDING"
      end
      if opts.localSharedProfileReady == true then
        return "READY"
      end
    end
    if resolvedProfileName == "" then
      return "PENDING"
    end
    if not tonumber(member.lastSyncAt) then
      return "PENDING"
    end
    if TrimText(member.addonVersion) == "" then
      return "PENDING"
    end

    local localProfileId = FirstNonEmptyText(opts.localProfileId, TrimText(select(1, deps.GetLootProfileId(resolvedProfileName)) or ""))
    if localProfileId == "" then
      return "PENDING"
    end
    local memberProfileId = TrimText(member.sharedProfileId)
    if memberProfileId == "" then
      return "PENDING"
    end
    if string.lower(localProfileId) ~= string.lower(memberProfileId) then
      return "REVIEW"
    end

    local localSummary = type(opts.localSummary) == "table" and opts.localSummary or GetLootProfileRevisionSummary(resolvedProfileName)
    local localSettingsRevision = math.max(0, tonumber(type(localSummary) == "table" and localSummary.settings) or 0)
    local localPermissionsRevision = math.max(0, tonumber(type(localSummary) == "table" and localSummary.permissions) or 0)
    local localSettingsChecksum = TrimText(type(localSummary) == "table" and localSummary.settingsChecksum or "")
    local localPermissionsChecksum = TrimText(type(localSummary) == "table" and localSummary.permissionsChecksum or "")
    local memberSettingsChecksum = TrimText(member.settingsChecksum)
    local memberPermissionsChecksum = TrimText(member.permissionsChecksum)
    local settingsMatch = (localSettingsChecksum ~= "" and memberSettingsChecksum ~= "")
      and string.lower(localSettingsChecksum) == string.lower(memberSettingsChecksum)
      or localSettingsRevision == math.max(0, tonumber(member.settingsRevision) or 0)
    local permissionsMatch = (localPermissionsChecksum ~= "" and memberPermissionsChecksum ~= "")
      and string.lower(localPermissionsChecksum) == string.lower(memberPermissionsChecksum)
      or localPermissionsRevision == math.max(0, tonumber(member.permissionsRevision) or 0)
    if settingsMatch and permissionsMatch then
      return "READY"
    end
    if (tonumber(member.settingsRevision) or 0) > localSettingsRevision
      or (tonumber(member.permissionsRevision) or 0) > localPermissionsRevision
    then
      return "REVIEW"
    end
    return "PENDING"
  end

  INTERNAL_API.LIDCOUNCIL_GetPreciseSyncCandidateState = function(candidate, rosterLookup)
    candidate = type(candidate) == "table" and candidate or nil
    if not candidate then
      return nil
    end
    local visibleState = string.lower(TrimText(candidate.visibleState))
    local comparison = string.lower(TrimText(candidate.effectiveComparison ~= "" and candidate.effectiveComparison or candidate.comparison))
    if visibleState == "waiting_apply" or string.upper(TrimText(candidate.applyAckPhase)) == "QUEUED" then
      return "PENDING"
    end
    if visibleState == "aligned" or visibleState == "converged" or visibleState == "background" or comparison == "same" then
      return "SYNCED"
    end
    if visibleState == "lineage" or visibleState == "unknown" or comparison == "different_lineage" or comparison == "unknown" then
      return "PARTIAL"
    end
    local remoteDomains = type(candidate.effectiveRemoteNewerDomains) == "table" and candidate.effectiveRemoteNewerDomains or candidate.remoteNewerDomains
    local localDomains = type(candidate.effectiveLocalNewerDomains) == "table" and candidate.effectiveLocalNewerDomains or candidate.localNewerDomains
    if HasComparedDomain(remoteDomains, "settings")
      or HasComparedDomain(remoteDomains, "permissions")
      or HasComparedDomain(localDomains, "settings")
      or HasComparedDomain(localDomains, "permissions")
    then
      return "PARTIAL"
    end
    if candidate.generationConverged == true then
      return "SYNCED"
    end
    if not HasComparedDomain(remoteDomains, "loot") and not HasComparedDomain(localDomains, "loot") then
      return "SYNCED"
    end
    if candidate.liveLootAligned == true then
      return "SYNCED"
    end
    if candidate.preciseDetailLoaded ~= true then
      return nil
    end
    local differentByDomain = type(candidate.preciseDifferentSubdomainsByDomain) == "table"
      and candidate.preciseDifferentSubdomainsByDomain
      or {}
    local liveLootMismatch = false
    for _, subdomain in ipairs(type(differentByDomain.loot) == "table" and differentByDomain.loot or {}) do
      if profileSyncMetaOps.classifyLootRepairSubdomainTier(subdomain, rosterLookup) == "live" then
        liveLootMismatch = true
        break
      end
    end
    return liveLootMismatch and "PARTIAL" or "SYNCED"
  end

  INTERNAL_API.LIDCOUNCIL_CompareMemberPayloadSyncState = function(referenceState, memberState, opts)
    opts = type(opts) == "table" and opts or {}
    referenceState = type(referenceState) == "table" and referenceState or nil
    memberState = type(memberState) == "table" and memberState or nil
    if type(referenceState) ~= "table" or type(memberState) ~= "table" then
      return nil
    end

    local referenceOperationalRevision = math.max(0, tonumber(referenceState.operationalRevision) or 0)
    local referenceLootRevision = math.max(0, tonumber(referenceState.lootRevision) or referenceOperationalRevision)
    local referenceSettingsRevision = math.max(0, tonumber(referenceState.settingsRevision) or 0)
    local referencePermissionsRevision = math.max(0, tonumber(referenceState.permissionsRevision) or 0)
    local referenceSettingsChecksum = TrimText(referenceState.settingsChecksum)
    local referencePermissionsChecksum = TrimText(referenceState.permissionsChecksum)
    local referenceOperationalChecksum = TrimText(referenceState.operationalChecksum)
    local referenceLootChecksum = TrimText(referenceState.lootChecksum)
    local referenceSessionChecksum = TrimText(referenceState.sessionChecksum)
    local referenceLiveLootChecksum = FirstNonEmptyText(opts.referenceLiveLootChecksum, TrimText(referenceState.liveLootChecksum))
    local memberOperationalRevision = math.max(0, tonumber(memberState.operationalRevision) or 0)
    local memberLootRevision = math.max(0, tonumber(memberState.lootRevision) or memberOperationalRevision)
    local memberSettingsRevision = math.max(0, tonumber(memberState.settingsRevision) or 0)
    local memberPermissionsRevision = math.max(0, tonumber(memberState.permissionsRevision) or 0)
    local memberSettingsChecksum = TrimText(memberState.settingsChecksum)
    local memberPermissionsChecksum = TrimText(memberState.permissionsChecksum)
    local memberOperationalChecksum = TrimText(memberState.operationalChecksum)
    local memberLootChecksum = TrimText(memberState.lootChecksum)
    local memberSessionChecksum = TrimText(memberState.sessionChecksum)
    local memberLiveLootChecksum = FirstNonEmptyText(opts.memberLiveLootChecksum, TrimText(memberState.liveLootChecksum))
    if referenceLootChecksum == "" then
      referenceLootChecksum = referenceOperationalChecksum
    end
    if memberLootChecksum == "" then
      memberLootChecksum = memberOperationalChecksum
    end
    if opts.currentSessionOnly == true then
      if referenceSessionChecksum == "" or memberSessionChecksum == "" then
        return "PARTIAL"
      end
      return string.lower(referenceSessionChecksum) == string.lower(memberSessionChecksum)
        and "SYNCED"
        or "PARTIAL"
    end
    local hasSettingsChecksum = referenceSettingsChecksum ~= "" and memberSettingsChecksum ~= ""
    local hasPermissionsChecksum = referencePermissionsChecksum ~= "" and memberPermissionsChecksum ~= ""
    local hasLootChecksum = referenceLootChecksum ~= "" and memberLootChecksum ~= ""
    if hasSettingsChecksum and string.lower(referenceSettingsChecksum) ~= string.lower(memberSettingsChecksum) then
      return "PARTIAL"
    end
    if hasPermissionsChecksum and string.lower(referencePermissionsChecksum) ~= string.lower(memberPermissionsChecksum) then
      return "PARTIAL"
    end
    if referenceLiveLootChecksum ~= "" and memberLiveLootChecksum ~= ""
      and string.lower(referenceLiveLootChecksum) == string.lower(memberLiveLootChecksum)
    then
      return "SYNCED"
    end
    if hasLootChecksum and string.lower(referenceLootChecksum) ~= string.lower(memberLootChecksum) then
      return "PARTIAL"
    end
    if hasSettingsChecksum and hasPermissionsChecksum and hasLootChecksum then
      return "SYNCED"
    end
    if referenceSettingsRevision == memberSettingsRevision
      and referencePermissionsRevision == memberPermissionsRevision
      and referenceLootRevision == memberLootRevision
    then
      return "SYNCED"
    end
    return "PARTIAL"
  end

  INTERNAL_API.LIDCOUNCIL_GetReferenceMemberSyncState = function(referenceMember, member, opts)
    opts = type(opts) == "table" and opts or {}
    referenceMember = type(referenceMember) == "table" and referenceMember or nil
    member = type(member) == "table" and member or nil
    if type(referenceMember) ~= "table" or type(member) ~= "table" then
      return nil
    end
    local referenceProfileId = FirstNonEmptyText(opts.referenceProfileId, TrimText(referenceMember.sharedProfileId))
    local memberProfileId = FirstNonEmptyText(opts.memberProfileId, TrimText(member.sharedProfileId))
    if referenceProfileId == "" or memberProfileId == "" then
      return nil
    end
    if string.lower(referenceProfileId) ~= string.lower(memberProfileId) then
      return "PARTIAL"
    end
    return INTERNAL_API.LIDCOUNCIL_CompareMemberPayloadSyncState(referenceMember, member, opts)
  end

  INTERNAL_API.LIDCOUNCIL_GetLocalJoinedMemberSyncState = function(activeSession, profileName, memberKey, member, opts)
    opts = type(opts) == "table" and opts or {}
    activeSession = type(activeSession) == "table" and activeSession or nil
    member = type(member) == "table" and member or nil
    local resolvedProfileName = TrimText(profileName)
    if type(member) ~= "table" then
      return "PENDING"
    end

    local localProfileId = FirstNonEmptyText(opts.localProfileId, resolvedProfileName ~= "" and TrimText(select(1, deps.GetLootProfileId(resolvedProfileName)) or "") or "")
    local memberProfileId = TrimText(member.sharedProfileId)
    if localProfileId == "" or memberProfileId == "" or string.lower(localProfileId) ~= string.lower(memberProfileId) then
      return "PARTIAL"
    end

    local localSummary = type(opts.localSummary) == "table" and opts.localSummary or (
      resolvedProfileName ~= "" and GetLootProfileRevisionSummary(resolvedProfileName) or nil
    )
    return INTERNAL_API.LIDCOUNCIL_CompareMemberPayloadSyncState({
      settingsRevision = type(localSummary) == "table" and localSummary.settings or 0,
      permissionsRevision = type(localSummary) == "table" and localSummary.permissions or 0,
      operationalRevision = type(localSummary) == "table" and localSummary.operational or 0,
      lootRevision = type(localSummary) == "table" and localSummary.loot or 0,
      settingsChecksum = type(localSummary) == "table" and localSummary.settingsChecksum or "",
      permissionsChecksum = type(localSummary) == "table" and localSummary.permissionsChecksum or "",
      operationalChecksum = type(localSummary) == "table" and localSummary.operationalChecksum or "",
      lootChecksum = type(localSummary) == "table" and localSummary.lootChecksum or "",
      sessionChecksum = type(localSummary) == "table" and localSummary.sessionChecksum or "",
      liveLootChecksum = TrimText(opts.localLiveLootChecksum),
    }, member, opts) or "PARTIAL"
  end

  INTERNAL_API.LIDCOUNCIL_GetJoinedMemberSyncState = function(activeSession, profileName, memberKey, member, opts)
    opts = type(opts) == "table" and opts or {}
    activeSession = type(activeSession) == "table" and activeSession or nil
    member = type(member) == "table" and member or nil
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if type(member) ~= "table" then
      return "PENDING"
    end

    local status = string.upper(TrimText(member.status or "JOINED"))
    if status == "DECLINED" then
      return "DECLINED"
    end
    if string.upper(TrimText(member.profileApplyAckPhase)) == "QUEUED" then
      return "PENDING"
    end
    if tonumber(member.lastSyncAt)
      and type(activeSession) == "table"
      and resolvedMemberKey ~= ""
      and AreCharacterKeysSame(resolvedMemberKey, activeSession.host or "")
    then
      return "SYNCED"
    end
    if tonumber(member.lastSyncAt) and TrimText(member.addonVersion) ~= "" then
      local candidateState = string.upper(TrimText(opts.candidateState))
      if candidateState ~= "" and opts.currentSessionOnly ~= true then
        return candidateState
      end
      if type(opts.referenceMember) == "table" then
        local referenceState = INTERNAL_API.LIDCOUNCIL_GetReferenceMemberSyncState(opts.referenceMember, member, opts)
        if referenceState ~= nil then
          return referenceState
        end
        return FirstNonEmptyText(opts.referenceFallbackState, "PENDING")
      end
      return INTERNAL_API.LIDCOUNCIL_GetLocalJoinedMemberSyncState(activeSession, profileName, resolvedMemberKey, member, opts)
    end
    if tonumber(member.lastSyncAt) then
      return "PARTIAL"
    end
    return "PENDING"
  end

  INTERNAL_API.LIDCOUNCIL_GetHostMemberSyncStatusMatrix = function(member)
    return profileSyncMetaOps.decodeHostMemberStatusMatrix(
      profileSyncMetaOps.getHostMemberStatusMatrixValue(member)
    )
  end

  INTERNAL_API.LIDCOUNCIL_GetHostMemberP2ProofDiagnostics = function(
    activeSession,
    profileName,
    memberKey,
    member,
    viewerKey,
    sharedContext
  )
    activeSession = type(activeSession) == "table" and activeSession or nil
    member = type(member) == "table" and member or nil
    local resolvedProfileName = TrimText(profileName)
    local resolvedMemberKey = NormalizeCharacterKey(FirstNonEmptyText(
      memberKey,
      type(member) == "table" and member.name or ""
    ))
    local activeSessionId = TrimText(type(activeSession) == "table" and activeSession.id or "")
    if type(activeSession) ~= "table" or type(member) ~= "table"
      or resolvedProfileName == "" or resolvedMemberKey == "" or activeSessionId == ""
    then
      return INTERNAL_API.LIDCOUNCIL_ResolveHostMemberP2ProofDiagnostics_Impl({})
    end

    local resolvedViewerKey = NormalizeCharacterKey(FirstNonEmptyText(viewerKey, GetCharacterKey() or ""))
    local isHostView = AreCharacterKeysSame(activeSession.host or "", resolvedViewerKey)
    local isHostRow = AreCharacterKeysSame(activeSession.host or "", resolvedMemberKey)
    local statusMatrix = INTERNAL_API.LIDCOUNCIL_GetHostMemberSyncStatusMatrix(member)
    local currentProof = isHostView and profileSyncMetaOps.getHostMemberReadinessProof(
      member,
      activeSessionId,
      resolvedMemberKey
    ) or nil
    local previousProof = isHostView
      and type(sessionRuntime.hostMemberReadinessProofByMember[member]) == "table"
      and sessionRuntime.hostMemberReadinessProofByMember[member]
      or nil
    sharedContext = type(sharedContext) == "table" and sharedContext or {}
    local needsComparisonContext = (isHostView and type(currentProof) == "table")
      or (not isHostView and type(statusMatrix) == "table" and statusMatrix.p2 == "REVIEW")
    if needsComparisonContext and sharedContext.localProfileId == nil then
      sharedContext.localProfileId = TrimText(select(1, deps.GetLootProfileId(resolvedProfileName)) or "")
    end
    if needsComparisonContext and sharedContext.localSessionChecksum == nil then
      local localSummary = GetLootProfileRevisionSummary(resolvedProfileName)
      sharedContext.localSessionChecksum = type(localSummary) == "table"
        and TrimText(localSummary.sessionChecksum)
        or ""
    end

    return INTERNAL_API.LIDCOUNCIL_ResolveHostMemberP2ProofDiagnostics_Impl({
      matrixState = type(statusMatrix) == "table" and statusMatrix.p2 or "",
      activeSessionId = activeSessionId,
      statusSessionId = type(statusMatrix) == "table" and activeSessionId or FirstNonEmptyText(
        member.hostSyncStatusSessionId,
        sessionRuntime.hostMemberSyncStatusSessionByMember[member]
      ),
      isHostRow = isHostRow,
      proofInspectable = isHostView,
      proofAvailable = type(currentProof) == "table",
      proofSessionId = type(currentProof) == "table" and currentProof.sessionId or "",
      previousProofSessionId = type(previousProof) == "table" and previousProof.sessionId or "",
      expectedMemberKey = resolvedMemberKey,
      proofMemberKey = type(currentProof) == "table" and currentProof.memberKey or "",
      localProfileId = sharedContext.localProfileId or "",
      memberProfileId = FirstNonEmptyText(
        type(currentProof) == "table" and currentProof.sharedProfileId or nil,
        type(currentProof) == "table" and currentProof.profileId or nil,
        not isHostView and member.sharedProfileId or nil,
        not isHostView and member.profileId or nil
      ),
      localSessionChecksum = sharedContext.localSessionChecksum or "",
      memberSessionChecksum = FirstNonEmptyText(
        type(currentProof) == "table" and currentProof.sessionChecksum or nil,
        not isHostView and member.sessionChecksum or nil
      ),
      proofLastSyncAt = type(currentProof) == "table" and currentProof.lastSyncAt or nil,
      proofAddonVersion = type(currentProof) == "table" and currentProof.addonVersion or "",
    })
  end

  profileSyncMetaOps.buildHostMemberSyncStatusMatrix = function(activeSession, profileName, memberKey, member, opts)
    opts = type(opts) == "table" and opts or {}
    activeSession = type(activeSession) == "table" and activeSession or nil
    member = type(member) == "table" and member or nil
    local resolvedProfileName = TrimText(profileName)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if type(activeSession) ~= "table" or type(member) ~= "table"
      or resolvedProfileName == "" or resolvedMemberKey == ""
    then
      return nil
    end

    if AreCharacterKeysSame(resolvedMemberKey, activeSession.host or "") then
      return {
        p1 = "READY",
        p2 = "READY",
        lootList = "READY",
        itemHistory = "READY",
        sessionHistory = "READY",
        funAwards = "READY",
        p3 = "READY",
      }
    end

    local readinessProof = profileSyncMetaOps.getHostMemberReadinessProof(
      member,
      TrimText(activeSession.id),
      resolvedMemberKey
    )
    if type(readinessProof) ~= "table" then
      return {
        p1 = "VALIDATING",
        p2 = "VALIDATING",
        lootList = "VALIDATING",
        itemHistory = "VALIDATING",
        sessionHistory = "VALIDATING",
        funAwards = "VALIDATING",
        p3 = "VALIDATING",
      }
    end

    local localProfileId = FirstNonEmptyText(
      opts.localProfileId,
      TrimText(select(1, deps.GetLootProfileId(resolvedProfileName)) or "")
    )
    local localSummary = type(opts.localSummary) == "table"
      and opts.localSummary
      or GetLootProfileRevisionSummary(resolvedProfileName)
    local localLiveLootChecksum = FirstNonEmptyText(
      opts.localLiveLootChecksum,
      profileSyncMetaOps.buildSessionLiveLootChecksum(resolvedProfileName, activeSession)
    )
    local matrix = {
      p1 = profileSyncMetaOps.normalizeHostMemberStatusState(
        INTERNAL_API.LIDCOUNCIL_GetDeferredJoinMemberBootstrapState(
          activeSession,
          resolvedProfileName,
          resolvedMemberKey,
          readinessProof,
          {
            localProfileId = localProfileId,
            localSummary = localSummary,
          }
        )
      ),
      p2 = profileSyncMetaOps.normalizeHostMemberStatusState(
        INTERNAL_API.LIDCOUNCIL_GetJoinedMemberSyncState(
          activeSession,
          resolvedProfileName,
          resolvedMemberKey,
          readinessProof,
          {
            localProfileId = localProfileId,
            localSummary = localSummary,
            localLiveLootChecksum = localLiveLootChecksum,
            candidateState = opts.candidateState,
            currentSessionOnly = true,
          }
        )
      ),
    }
    local expectedChecksums = profileSyncMetaOps.buildSessionArchiveScopeChecksums(
      resolvedProfileName,
      activeSession
    )
    local checksumFields = {
      lootList = "lootListArchiveChecksum",
      itemHistory = "itemHistoryArchiveChecksum",
      sessionHistory = "sessionHistoryArchiveChecksum",
      funAwards = "funAwardsArchiveChecksum",
    }
    matrix.p3 = "READY"
    for scopeName, checksumField in pairs(checksumFields) do
      local expectedChecksum = TrimText(expectedChecksums[scopeName])
      local memberChecksum = TrimText(readinessProof[checksumField])
      if expectedChecksum == "" or memberChecksum == "" then
        matrix[scopeName] = "PENDING"
      elseif string.lower(expectedChecksum) == string.lower(memberChecksum) then
        matrix[scopeName] = "READY"
      else
        matrix[scopeName] = "STALE"
      end
    end
    matrix.p3 = INTERNAL_API.LIDCOUNCIL_AggregateHostMemberArchiveState_Impl(matrix)
    local pendingJoinState = type(profileSyncMetaOps.getPendingJoinManifestRepair) == "function"
      and profileSyncMetaOps.getPendingJoinManifestRepair(TrimText(activeSession.id), resolvedMemberKey)
      or nil
    local validationState = INTERNAL_API.LIDCOUNCIL_ResolveJoinManifestValidationState_Impl(
      pendingJoinState,
      {
        sessionId = TrimText(activeSession.id),
        profileName = resolvedProfileName,
        memberKey = resolvedMemberKey,
        profileId = localProfileId,
        memberProfileId = FirstNonEmptyText(readinessProof.sharedProfileId, readinessProof.profileId),
      }
    )
    INTERNAL_API.LIDCOUNCIL_ApplyJoinManifestValidationToStatusMatrix_Impl(matrix, validationState)
    return matrix
  end

  INTERNAL_API.LIDCOUNCIL_BuildJoinedMemberDisplayInputSignature = function(activeSession, profileName, opts)
    opts = type(opts) == "table" and opts or {}
    activeSession = type(activeSession) == "table" and activeSession or nil
    local resolvedProfileName = TrimText(profileName)
    if type(activeSession) ~= "table" then
      return ""
    end

    local hostCurrentSessionDisplayBaseContext = type(opts.hostCurrentSessionDisplayBaseContext) == "table"
      and opts.hostCurrentSessionDisplayBaseContext
      or nil
    local selfMemberKey = NormalizeCharacterKey(FirstNonEmptyText(opts.selfMemberKey, GetCharacterKey() or ""))
    local sessionHost = NormalizeCharacterKey(activeSession.host or "")
    local localProfileId = FirstNonEmptyText(
      opts.localProfileId,
      type(hostCurrentSessionDisplayBaseContext) == "table" and hostCurrentSessionDisplayBaseContext.localProfileId or nil,
      resolvedProfileName ~= "" and TrimText(select(1, deps.GetLootProfileId(resolvedProfileName)) or "") or ""
    )
    local localSummary = type(opts.localSummary) == "table" and opts.localSummary
      or type(hostCurrentSessionDisplayBaseContext) == "table" and hostCurrentSessionDisplayBaseContext.localSummary
      or (resolvedProfileName ~= "" and GetLootProfileRevisionSummary(resolvedProfileName) or nil)
    local localLiveLootChecksum = FirstNonEmptyText(
      opts.localLiveLootChecksum,
      type(hostCurrentSessionDisplayBaseContext) == "table" and hostCurrentSessionDisplayBaseContext.localLiveLootChecksum or nil,
      resolvedProfileName ~= "" and profileSyncMetaOps.buildSessionLiveLootChecksum(resolvedProfileName, activeSession) or ""
    )
    local signatureParts = {
      TrimText(activeSession.id),
      activeSession.sharedProfileReady == false and "0" or "1",
      selfMemberKey,
      sessionHost,
      localProfileId,
      tostring(math.max(0, tonumber(type(localSummary) == "table" and localSummary.settings) or 0)),
      tostring(math.max(0, tonumber(type(localSummary) == "table" and localSummary.permissions) or 0)),
      tostring(math.max(0, tonumber(type(localSummary) == "table" and localSummary.operational) or 0)),
      tostring(math.max(0, tonumber(type(localSummary) == "table" and localSummary.loot) or 0)),
      TrimText(type(localSummary) == "table" and localSummary.settingsChecksum or ""),
      TrimText(type(localSummary) == "table" and localSummary.permissionsChecksum or ""),
      TrimText(type(localSummary) == "table" and localSummary.operationalChecksum or ""),
      TrimText(type(localSummary) == "table" and localSummary.lootChecksum or ""),
      localLiveLootChecksum,
    }

    local rosterLookup = type(opts.rosterLookup) == "table" and opts.rosterLookup
      or type(hostCurrentSessionDisplayBaseContext) == "table" and type(hostCurrentSessionDisplayBaseContext.rosterLookup) == "table"
        and hostCurrentSessionDisplayBaseContext.rosterLookup
      or profileSyncMetaOps.buildActiveSessionRosterLookup(activeSession)
    local candidateSnapshot = type(opts.syncCandidateSnapshot) == "table" and opts.syncCandidateSnapshot or BuildActiveSyncCandidateSnapshot()
    local candidateEntries = type(opts.candidateEntries) == "table"
      and opts.candidateEntries
      or BuildActiveSyncCandidateStateEntries(candidateSnapshot, rosterLookup)
    table.sort(candidateEntries)
    for _, entry in ipairs(candidateEntries) do
      signatureParts[#signatureParts + 1] = entry
    end

    local memberEntries = {}
    for memberKey, member in pairs(type(activeSession.members) == "table" and activeSession.members or {}) do
      if type(member) == "table" then
        local resolvedMemberKey = NormalizeCharacterKey(memberKey ~= "" and memberKey or member.name or "")
        if resolvedMemberKey ~= "" and IsSessionMemberVisibleForCurrentState(member) then
          memberEntries[#memberEntries + 1] = resolvedMemberKey
            .. "\30"
            .. BuildSessionVisibleMemberStateSignature(member)
        end
      end
    end
    table.sort(memberEntries)
    for _, entry in ipairs(memberEntries) do
      signatureParts[#signatureParts + 1] = entry
    end
    return table.concat(signatureParts, "\31")
  end

  INTERNAL_API.LIDCOUNCIL_RequestSessionEditorRefresh = function(opts)
    opts = type(opts) == "table" and opts or {}
    if opts.refreshEditor == false then
      return false
    end

    local refreshPages = {}
    for pageKey, enabled in pairs(type(opts.refreshPages) == "table" and opts.refreshPages or {}) do
      if enabled == true then
        refreshPages[pageKey] = true
      end
    end

    local lootSessionSections = {}
    for sectionKey, enabled in pairs(type(opts.lootSessionSections) == "table" and opts.lootSessionSections or {}) do
      if enabled == true then
        lootSessionSections[sectionKey] = true
      end
    end
    if next(lootSessionSections) ~= nil then
      refreshPages.Panels = true
    end

    local refreshAllLoot = opts.refreshAllLoot == true
    local refreshAbout = opts.refreshAbout == true
    local refreshHiddenPages = opts.refreshHiddenPages == true
    if not refreshAllLoot
      and not refreshAbout
      and next(refreshPages) == nil
      and next(lootSessionSections) == nil
    then
      return false
    end

    local function BuildEditorRefreshRequestState()
      local requestRefreshPages = {}
      for pageKey, enabled in pairs(refreshPages) do
        if enabled == true then
          requestRefreshPages[pageKey] = true
        end
      end
      local requestLootSessionSections = {}
      for sectionKey, enabled in pairs(lootSessionSections) do
        if enabled == true then
          requestLootSessionSections[sectionKey] = true
        end
      end
      local refreshPanelsFull = requestRefreshPages.Panels == true and next(requestLootSessionSections) == nil
      if next(requestLootSessionSections) ~= nil then
        requestRefreshPages.Panels = true
      end
      return {
        refreshAllLoot = refreshAllLoot == true,
        refreshAbout = refreshAbout == true,
        refreshHiddenPages = refreshHiddenPages == true,
        refreshPages = requestRefreshPages,
        lootSessionSections = requestLootSessionSections,
        refreshPanelsFull = refreshPanelsFull == true,
        defer = opts.defer ~= false,
        delaySeconds = tonumber(opts.delaySeconds) or 0,
        forceImmediate = opts.forceImmediate == true,
      }
    end

    local function FilterEditorRefreshRequestStateByVisibleState(requestState)
      requestState = type(requestState) == "table" and requestState or nil
      if type(requestState) ~= "table" then
        return nil
      end
      if requestState.refreshAllLoot == true
        or requestState.refreshHiddenPages == true
        or requestState.forceImmediate == true
      then
        return requestState
      end
      local refreshContext = type(deps.GetVisibleEditorRefreshContext) == "function"
        and deps.GetVisibleEditorRefreshContext()
        or nil
      if type(refreshContext) ~= "table" or refreshContext.shown ~= true then
        return nil
      end

      local currentPage = TrimText(refreshContext.currentPage)
      local currentLootSessionSection = string.upper(TrimText(
        refreshContext.lootSessionSection ~= "" and refreshContext.lootSessionSection or "CURRENT"
      ))
      local filteredRequestState = {
        refreshAllLoot = false,
        refreshAbout = requestState.refreshAbout == true and currentPage == "About",
        refreshHiddenPages = false,
        refreshPages = {},
        lootSessionSections = {},
        refreshPanelsFull = false,
        defer = requestState.defer ~= false,
        delaySeconds = tonumber(requestState.delaySeconds) or 0,
        forceImmediate = false,
      }

      for pageKey in pairs(type(requestState.refreshPages) == "table" and requestState.refreshPages or {}) do
        if pageKey == "Panels" then
          if currentPage == "Panels" then
            if requestState.refreshPanelsFull == true then
              filteredRequestState.refreshPages.Panels = true
              filteredRequestState.refreshPanelsFull = true
            else
              for sectionKey in pairs(type(requestState.lootSessionSections) == "table" and requestState.lootSessionSections or {}) do
                if sectionKey == currentLootSessionSection then
                  filteredRequestState.lootSessionSections[sectionKey] = true
                end
              end
              if next(filteredRequestState.lootSessionSections) ~= nil then
                filteredRequestState.refreshPages.Panels = true
              end
            end
          end
        elseif currentPage == pageKey then
          filteredRequestState.refreshPages[pageKey] = true
        end
      end

      if filteredRequestState.refreshPages.Panels ~= true then
        filteredRequestState.lootSessionSections = {}
      end
      if filteredRequestState.refreshPanelsFull ~= true and next(filteredRequestState.lootSessionSections) == nil then
        filteredRequestState.refreshPages.Panels = nil
      end
      if next(filteredRequestState.refreshPages) == nil and filteredRequestState.refreshAbout ~= true then
        return nil
      end
      return filteredRequestState
    end

    local requestState = FilterEditorRefreshRequestStateByVisibleState(BuildEditorRefreshRequestState())
    if type(requestState) ~= "table" then
      return false
    end
    local effectiveRefreshAllLoot = requestState.refreshAllLoot == true
    local effectiveRefreshAbout = requestState.refreshAbout == true
    local effectiveRefreshHiddenPages = requestState.refreshHiddenPages == true
    local effectiveRefreshPages = type(requestState.refreshPages) == "table" and requestState.refreshPages or {}
    local effectiveLootSessionSections = type(requestState.lootSessionSections) == "table" and requestState.lootSessionSections or {}
    if not effectiveRefreshAllLoot
      and not effectiveRefreshAbout
      and next(effectiveRefreshPages) == nil
      and next(effectiveLootSessionSections) == nil
    then
      return false
    end
    local refreshOpts = {
      defer = opts.defer ~= false,
    }
    if effectiveRefreshAllLoot then
      refreshOpts.refreshAllLoot = true
    end
    if effectiveRefreshAbout then
      refreshOpts.refreshAbout = true
    end
    if effectiveRefreshHiddenPages then
      refreshOpts.refreshHiddenPages = true
    end
    if opts.delaySeconds ~= nil then
      refreshOpts.delaySeconds = tonumber(opts.delaySeconds) or 0
    end
    if opts.forceImmediate == true then
      refreshOpts.forceImmediate = true
    end
    if next(effectiveRefreshPages) ~= nil then
      refreshOpts.refreshPages = effectiveRefreshPages
    end
    if next(effectiveLootSessionSections) ~= nil then
      refreshOpts.lootSessionSections = effectiveLootSessionSections
    end

    deps.RefreshEditor(refreshOpts)
    return true
  end

  INTERNAL_API.LIDCOUNCIL_RefreshEditorForCurrentAndSyncSections = function(currentSectionChanged, opts)
    opts = type(opts) == "table" and opts or {}
    return INTERNAL_API.LIDCOUNCIL_RequestSessionEditorRefresh({
      refreshEditor = opts.refreshEditor,
      defer = opts.defer,
      delaySeconds = opts.delaySeconds,
      forceImmediate = opts.forceImmediate,
      lootSessionSections = currentSectionChanged and {
        CURRENT = true,
        SYNCMGMT = true,
      } or {
        SYNCMGMT = true,
      },
    })
  end

  INTERNAL_API.LIDCOUNCIL_RefreshEditorForCurrentSection = function(opts)
    opts = type(opts) == "table" and opts or {}
    return INTERNAL_API.LIDCOUNCIL_RequestSessionEditorRefresh({
      refreshEditor = opts.refreshEditor,
      defer = opts.defer,
      delaySeconds = opts.delaySeconds,
      forceImmediate = opts.forceImmediate,
      lootSessionSections = {
        CURRENT = true,
      },
    })
  end

  INTERNAL_API.LIDCOUNCIL_RefreshEditorForAutoPassSection = function(opts)
    opts = type(opts) == "table" and opts or {}
    return INTERNAL_API.LIDCOUNCIL_RequestSessionEditorRefresh({
      refreshEditor = opts.refreshEditor,
      defer = opts.defer,
      delaySeconds = opts.delaySeconds,
      forceImmediate = opts.forceImmediate,
      lootSessionSections = {
        AUTOPASS = true,
      },
    })
  end

  INTERNAL_API.LIDCOUNCIL_RefreshEditorForCurrentAndAutoPassSections = function(opts)
    opts = type(opts) == "table" and opts or {}
    return INTERNAL_API.LIDCOUNCIL_RequestSessionEditorRefresh({
      refreshEditor = opts.refreshEditor,
      defer = opts.defer,
      delaySeconds = opts.delaySeconds,
      forceImmediate = opts.forceImmediate,
      lootSessionSections = {
        CURRENT = true,
        AUTOPASS = true,
      },
    })
  end

  INTERNAL_API.LIDCOUNCIL_RefreshEditorForPanelsAndLiveBoard = function(opts)
    opts = type(opts) == "table" and opts or {}
    return INTERNAL_API.LIDCOUNCIL_RequestSessionEditorRefresh({
      refreshEditor = opts.refreshEditor,
      defer = opts.defer,
      delaySeconds = opts.delaySeconds,
      forceImmediate = opts.forceImmediate,
      refreshPages = {
        Panels = true,
        LiveBoard = true,
      },
    })
  end

  INTERNAL_API.LIDCOUNCIL_RefreshEditorForSyncManagementSection = function(opts)
    opts = type(opts) == "table" and opts or {}
    return INTERNAL_API.LIDCOUNCIL_RequestSessionEditorRefresh({
      refreshEditor = opts.refreshEditor,
      defer = opts.defer,
      delaySeconds = opts.delaySeconds,
      forceImmediate = opts.forceImmediate,
      lootSessionSections = {
        SYNCMGMT = true,
      },
    })
  end

  INTERNAL_API.LIDCOUNCIL_GetCurrentSectionChangeFromProbe = function(activeSession, previousCurrentSectionState, previousCurrentSectionProbe, memberKeys, buildCurrentSectionState)
    activeSession = type(activeSession) == "table" and activeSession or nil
    if type(activeSession) ~= "table" or type(buildCurrentSectionState) ~= "function" then
      return false
    end
    if previousCurrentSectionProbe ~= INTERNAL_API.LIDCOUNCIL_BuildCurrentSectionChangeProbe(activeSession, memberKeys) then
      return previousCurrentSectionState ~= buildCurrentSectionState()
    end
    return false
  end

  INTERNAL_API.LIDCOUNCIL_GetCurrentSectionChangeFromDisplayInputs = function(activeSession, profileName, previousCurrentSectionDisplay, previousCurrentSectionDisplayInputs, buildCurrentSectionDisplaySignature, opts)
    opts = type(opts) == "table" and opts or {}
    activeSession = type(activeSession) == "table" and activeSession or nil
    local resolvedProfileName = TrimText(profileName)
    if type(activeSession) ~= "table"
      or resolvedProfileName == ""
      or type(buildCurrentSectionDisplaySignature) ~= "function"
    then
      return false
    end
    if previousCurrentSectionDisplayInputs ~= INTERNAL_API.LIDCOUNCIL_BuildJoinedMemberDisplayInputSignature(
      activeSession,
      resolvedProfileName,
      opts
    ) then
      return previousCurrentSectionDisplay ~= buildCurrentSectionDisplaySignature(opts)
    end
    return false
  end

  INTERNAL_API.LIDCOUNCIL_BuildHostCurrentSessionDisplayContext = function(activeSession, profileName, memberKey, opts)
    opts = type(opts) == "table" and opts or {}
    activeSession = type(activeSession) == "table" and activeSession or nil
    local resolvedProfileName = TrimText(profileName)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    local rosterLookup = type(opts.rosterLookup) == "table" and opts.rosterLookup or (
      type(activeSession) == "table" and profileSyncMetaOps.buildActiveSessionRosterLookup(activeSession) or {}
    )
    local syncCandidateSnapshot = type(opts.syncCandidateSnapshot) == "table" and opts.syncCandidateSnapshot or nil
    local candidateSyncState = resolvedMemberKey ~= ""
      and INTERNAL_API.LIDCOUNCIL_GetPreciseSyncCandidateState(
        select(1, GetActiveSyncCandidateContextFromSnapshot(resolvedMemberKey, syncCandidateSnapshot)),
        rosterLookup
      )
      or ""
    return {
      localProfileId = FirstNonEmptyText(
        opts.localProfileId,
        resolvedProfileName ~= "" and TrimText(select(1, deps.GetLootProfileId(resolvedProfileName)) or "") or ""
      ),
      localSummary = type(opts.localSummary) == "table" and opts.localSummary or (
        resolvedProfileName ~= "" and GetLootProfileRevisionSummary(resolvedProfileName) or nil
      ),
      localLiveLootChecksum = FirstNonEmptyText(
        opts.localLiveLootChecksum,
        resolvedProfileName ~= "" and profileSyncMetaOps.buildSessionLiveLootChecksum(resolvedProfileName, activeSession) or ""
      ),
      rosterLookup = rosterLookup,
      candidateState = FirstNonEmptyText(
        opts.candidateState,
        candidateSyncState,
        ""
      ),
    }
  end

  INTERNAL_API.LIDCOUNCIL_BuildHostCurrentSessionDisplayContextFromBase = function(activeSession, profileName, memberKey, baseContext, syncCandidateSnapshot)
    baseContext = type(baseContext) == "table" and baseContext or nil
    return INTERNAL_API.LIDCOUNCIL_BuildHostCurrentSessionDisplayContext(
      activeSession,
      profileName,
      memberKey,
      {
        localProfileId = type(baseContext) == "table" and baseContext.localProfileId or nil,
        localSummary = type(baseContext) == "table" and baseContext.localSummary or nil,
        localLiveLootChecksum = type(baseContext) == "table" and baseContext.localLiveLootChecksum or nil,
        rosterLookup = type(baseContext) == "table" and baseContext.rosterLookup or nil,
        syncCandidateSnapshot = type(syncCandidateSnapshot) == "table" and syncCandidateSnapshot or nil,
      }
    )
  end

  INTERNAL_API.LIDCOUNCIL_BuildHostCurrentSessionMemberDisplayState = function(activeSession, profileName, memberKey, member, opts)
    opts = type(opts) == "table" and opts or {}
    activeSession = type(activeSession) == "table" and activeSession or nil
    member = type(member) == "table" and member or nil
    local resolvedProfileName = TrimText(profileName)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if type(member) ~= "table" then
      return table.concat({ "PENDING", "PENDING", "" }, "\30")
    end

    local localProfileId = opts.localProfileId
    local localSummary = type(opts.localSummary) == "table" and opts.localSummary or nil
    local localLiveLootChecksum = opts.localLiveLootChecksum
    local candidateState = opts.candidateState
    local rosterLookup = type(opts.rosterLookup) == "table" and opts.rosterLookup or nil
    if localProfileId == nil or localSummary == nil or localLiveLootChecksum == nil
      or (candidateState == nil and resolvedMemberKey ~= "" and type(rosterLookup) ~= "table")
    then
      local context = INTERNAL_API.LIDCOUNCIL_BuildHostCurrentSessionDisplayContext(activeSession, resolvedProfileName, resolvedMemberKey, opts)
      localProfileId = FirstNonEmptyText(localProfileId, context.localProfileId)
      localSummary = type(localSummary) == "table" and localSummary or context.localSummary
      localLiveLootChecksum = localLiveLootChecksum ~= nil and localLiveLootChecksum or context.localLiveLootChecksum
      rosterLookup = type(rosterLookup) == "table" and rosterLookup or context.rosterLookup
      candidateState = candidateState ~= nil and candidateState or context.candidateState
    end
    localProfileId = FirstNonEmptyText(localProfileId)
    localLiveLootChecksum = TrimText(localLiveLootChecksum)
    candidateState = string.upper(TrimText(candidateState))
    if candidateState == "" and resolvedMemberKey ~= "" and opts.candidateState == nil then
      rosterLookup = type(rosterLookup) == "table"
        and rosterLookup
        or profileSyncMetaOps.buildActiveSessionRosterLookup(activeSession)
      candidateState = FirstNonEmptyText(
        INTERNAL_API.LIDCOUNCIL_GetPreciseSyncCandidateState(
          select(1, GetActiveSyncCandidateContextFromSnapshot(
            resolvedMemberKey,
            type(opts.syncCandidateSnapshot) == "table" and opts.syncCandidateSnapshot or nil
          )),
          rosterLookup
        ),
        ""
      )
    end
    return table.concat({
      INTERNAL_API.LIDCOUNCIL_GetJoinedMemberSyncState(activeSession, resolvedProfileName, resolvedMemberKey, member, {
        localProfileId = localProfileId,
        localSummary = localSummary,
        localLiveLootChecksum = localLiveLootChecksum,
        candidateState = candidateState,
        currentSessionOnly = true,
      }),
      INTERNAL_API.LIDCOUNCIL_GetDeferredJoinMemberBootstrapState(activeSession, resolvedProfileName, resolvedMemberKey, member, {
        localProfileId = localProfileId,
        localSummary = localSummary,
      }),
      GetSessionMemberDeltaRecoveryDisplayState(member),
    }, "\30")
  end

  INTERNAL_API.LIDCOUNCIL_BuildHostCurrentSectionDisplaySignature = function(activeSession, profileName, opts)
    opts = type(opts) == "table" and opts or {}
    activeSession = type(activeSession) == "table" and activeSession or nil
    local resolvedProfileName = TrimText(profileName)
    if type(activeSession) ~= "table" or resolvedProfileName == "" then
      return ""
    end

    local syncCandidateSnapshot = type(opts.syncCandidateSnapshot) == "table"
      and opts.syncCandidateSnapshot
      or BuildActiveSyncCandidateSnapshot()
    local hostCurrentSessionDisplayBaseContext = type(opts.hostCurrentSessionDisplayBaseContext) == "table"
      and opts.hostCurrentSessionDisplayBaseContext
      or INTERNAL_API.LIDCOUNCIL_BuildHostCurrentSessionDisplayContext(
        activeSession,
        resolvedProfileName,
        nil,
        {
          syncCandidateSnapshot = syncCandidateSnapshot,
        }
      )
    local localProfileId = hostCurrentSessionDisplayBaseContext.localProfileId
    local localSummary = hostCurrentSessionDisplayBaseContext.localSummary
    local localLiveLootChecksum = hostCurrentSessionDisplayBaseContext.localLiveLootChecksum
    local rosterLookup = hostCurrentSessionDisplayBaseContext.rosterLookup
    local candidateSyncStateByMemberKey = type(opts.candidateSyncStateByMemberKey) == "table"
      and opts.candidateSyncStateByMemberKey
      or select(2, BuildActiveSyncCandidateStateEntries(syncCandidateSnapshot, rosterLookup))

    local signatureParts = {
      activeSession.sharedProfileReady == false and "0" or "1",
    }
    local memberEntries = {}
    for memberKey, member in pairs(type(activeSession.members) == "table" and activeSession.members or {}) do
      if type(member) == "table" then
        local resolvedKey = NormalizeCharacterKey(memberKey ~= "" and memberKey or member.name or "")
        if resolvedKey ~= "" and IsSessionMemberVisibleForCurrentState(member) then
          memberEntries[#memberEntries + 1] = resolvedKey
            .. "\30"
            .. INTERNAL_API.LIDCOUNCIL_BuildHostCurrentSessionMemberDisplayState(
              activeSession,
              resolvedProfileName,
              resolvedKey,
              member,
              {
                localProfileId = localProfileId,
                localSummary = localSummary,
                localLiveLootChecksum = localLiveLootChecksum,
                rosterLookup = rosterLookup,
                candidateState = candidateSyncStateByMemberKey[resolvedKey],
              }
            )
        end
      end
    end
    table.sort(memberEntries)
    for _, entry in ipairs(memberEntries) do
      signatureParts[#signatureParts + 1] = entry
    end
    return table.concat(signatureParts, "\31")
  end

  INTERNAL_API.LIDCOUNCIL_BuildHostCurrentSectionDisplayProbe = function(activeSession, profileName, opts)
    opts = type(opts) == "table" and opts or {}
    activeSession = type(activeSession) == "table" and activeSession or nil
    local resolvedProfileName = TrimText(profileName)
    if type(activeSession) ~= "table" or resolvedProfileName == "" then
      return nil
    end

    local syncCandidateSnapshot = type(opts.syncCandidateSnapshot) == "table"
      and opts.syncCandidateSnapshot
      or BuildActiveSyncCandidateSnapshot()
    local hostCurrentSessionDisplayBaseContext = type(opts.hostCurrentSessionDisplayBaseContext) == "table"
      and opts.hostCurrentSessionDisplayBaseContext
      or INTERNAL_API.LIDCOUNCIL_BuildHostCurrentSessionDisplayContext(
        activeSession,
        resolvedProfileName,
        nil,
        {
          syncCandidateSnapshot = syncCandidateSnapshot,
        }
      )
    local candidateEntries = type(opts.candidateEntries) == "table" and opts.candidateEntries or nil
    local candidateSyncStateByMemberKey = type(opts.candidateSyncStateByMemberKey) == "table"
      and opts.candidateSyncStateByMemberKey
      or nil
    if type(candidateEntries) ~= "table" or type(candidateSyncStateByMemberKey) ~= "table" then
      candidateEntries, candidateSyncStateByMemberKey = BuildActiveSyncCandidateStateEntries(
        syncCandidateSnapshot,
        hostCurrentSessionDisplayBaseContext.rosterLookup
      )
    end

    return {
      syncCandidateSnapshot = syncCandidateSnapshot,
      hostCurrentSessionDisplayBaseContext = hostCurrentSessionDisplayBaseContext,
      candidateEntries = candidateEntries,
      candidateSyncStateByMemberKey = candidateSyncStateByMemberKey,
      displaySignature = INTERNAL_API.LIDCOUNCIL_BuildHostCurrentSectionDisplaySignature(
        activeSession,
        resolvedProfileName,
        {
          hostCurrentSessionDisplayBaseContext = hostCurrentSessionDisplayBaseContext,
          syncCandidateSnapshot = syncCandidateSnapshot,
          candidateSyncStateByMemberKey = candidateSyncStateByMemberKey,
        }
      ),
      inputSignature = INTERNAL_API.LIDCOUNCIL_BuildJoinedMemberDisplayInputSignature(
        activeSession,
        resolvedProfileName,
        {
          hostCurrentSessionDisplayBaseContext = hostCurrentSessionDisplayBaseContext,
          syncCandidateSnapshot = syncCandidateSnapshot,
          candidateEntries = candidateEntries,
        }
      ),
    }
  end

  INTERNAL_API.LIDCOUNCIL_GetHostCurrentSectionChangeFromProbe = function(activeSession, profileName, previousProbe, opts)
    previousProbe = type(previousProbe) == "table" and previousProbe or nil
    local currentProbe = INTERNAL_API.LIDCOUNCIL_BuildHostCurrentSectionDisplayProbe(activeSession, profileName, {
      syncCandidateSnapshot = type(opts) == "table" and type(opts.syncCandidateSnapshot) == "table"
        and opts.syncCandidateSnapshot
        or (type(previousProbe) == "table" and previousProbe.syncCandidateSnapshot or nil),
      hostCurrentSessionDisplayBaseContext = type(opts) == "table" and type(opts.hostCurrentSessionDisplayBaseContext) == "table"
        and opts.hostCurrentSessionDisplayBaseContext
        or (type(previousProbe) == "table" and previousProbe.hostCurrentSessionDisplayBaseContext or nil),
      candidateEntries = type(opts) == "table" and type(opts.candidateEntries) == "table"
        and opts.candidateEntries
        or (type(previousProbe) == "table" and previousProbe.candidateEntries or nil),
      candidateSyncStateByMemberKey = type(opts) == "table" and type(opts.candidateSyncStateByMemberKey) == "table"
        and opts.candidateSyncStateByMemberKey
        or (type(previousProbe) == "table" and previousProbe.candidateSyncStateByMemberKey or nil),
    })
    if type(previousProbe) ~= "table" or type(currentProbe) ~= "table" then
      return false, currentProbe
    end
    if previousProbe.inputSignature ~= currentProbe.inputSignature then
      return previousProbe.displaySignature ~= currentProbe.displaySignature, currentProbe
    end
    return false, currentProbe
  end

  INTERNAL_API.LIDCOUNCIL_BuildMemberCurrentSessionDisplayContext = function(activeSession, profileName, selfMemberKey, opts)
    opts = type(opts) == "table" and opts or {}
    activeSession = type(activeSession) == "table" and activeSession or nil
    local resolvedProfileName = TrimText(profileName)
    local resolvedSelfMemberKey = NormalizeCharacterKey(FirstNonEmptyText(selfMemberKey, opts.selfMemberKey, GetCharacterKey() or ""))
    local resolvedSessionHost = NormalizeCharacterKey(FirstNonEmptyText(
      opts.sessionHost,
      type(activeSession) == "table" and activeSession.host or ""
    ))
    local rosterLookup = type(opts.rosterLookup) == "table" and opts.rosterLookup or (
      type(activeSession) == "table" and profileSyncMetaOps.buildActiveSessionRosterLookup(activeSession) or {}
    )
    local hostBaseContext = INTERNAL_API.LIDCOUNCIL_BuildHostCurrentSessionDisplayContext(
      activeSession,
      resolvedProfileName,
      nil,
      {
        localProfileId = opts.localProfileId,
        localSummary = opts.localSummary,
        localLiveLootChecksum = opts.localLiveLootChecksum,
        rosterLookup = rosterLookup,
        syncCandidateSnapshot = opts.syncCandidateSnapshot,
      }
    )
    local candidateSyncStateByMemberKey = type(opts.candidateSyncStateByMemberKey) == "table"
      and opts.candidateSyncStateByMemberKey
      or select(2, BuildActiveSyncCandidateStateEntries(
        type(opts.syncCandidateSnapshot) == "table" and opts.syncCandidateSnapshot or BuildActiveSyncCandidateSnapshot(),
        rosterLookup
      ))
    return {
      isMemberCurrentSessionContext = true,
      localProfileId = hostBaseContext.localProfileId,
      localSummary = hostBaseContext.localSummary,
      localLiveLootChecksum = hostBaseContext.localLiveLootChecksum,
      rosterLookup = rosterLookup,
      selfMemberKey = resolvedSelfMemberKey,
      hostReferenceMember = resolvedSessionHost ~= "" and FindSessionMember(activeSession, resolvedSessionHost) or nil,
      selfVsHostCandidateState = resolvedSelfMemberKey ~= "" and resolvedSessionHost ~= ""
        and candidateSyncStateByMemberKey[resolvedSessionHost]
        or nil,
      localSharedProfileReady = type(activeSession) == "table" and activeSession.sharedProfileReady == false and false or true,
    }
  end

  INTERNAL_API.LIDCOUNCIL_BuildMemberCurrentSessionMemberDisplayState = function(activeSession, profileName, memberKey, member, opts)
    opts = type(opts) == "table" and opts or {}
    activeSession = type(activeSession) == "table" and activeSession or nil
    member = type(member) == "table" and member or nil
    local resolvedProfileName = TrimText(profileName)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if type(member) ~= "table" then
      return table.concat({ "PENDING", "PENDING" }, "\30")
    end

    local hostStatusMatrix = INTERNAL_API.LIDCOUNCIL_GetHostMemberSyncStatusMatrix(member)
    if type(hostStatusMatrix) == "table" then
      local p2State = hostStatusMatrix.p2 == "READY" and "SYNCED"
        or hostStatusMatrix.p2 == "REVIEW" and "PARTIAL"
        or "PENDING"
      return table.concat({ p2State, hostStatusMatrix.p1 or "PENDING" }, "\30")
    end

    local context = opts.isMemberCurrentSessionContext == true
      and opts
      or INTERNAL_API.LIDCOUNCIL_BuildMemberCurrentSessionDisplayContext(
        activeSession,
        resolvedProfileName,
        opts.selfMemberKey,
        opts
      )
    return table.concat({
      INTERNAL_API.LIDCOUNCIL_GetJoinedMemberSyncState(activeSession, resolvedProfileName, resolvedMemberKey, member, {
        localProfileId = context.localProfileId,
        localSummary = context.localSummary,
        localLiveLootChecksum = context.localLiveLootChecksum,
        candidateState = resolvedMemberKey == context.selfMemberKey and context.selfVsHostCandidateState or nil,
        referenceMember = context.hostReferenceMember,
        referenceFallbackState = "PENDING",
        currentSessionOnly = true,
      }),
      INTERNAL_API.LIDCOUNCIL_GetDeferredJoinMemberBootstrapState(activeSession, resolvedProfileName, resolvedMemberKey, member, {
        localProfileId = context.localProfileId,
        localSummary = context.localSummary,
        selfMemberKey = context.selfMemberKey,
        localSharedProfileReady = context.localSharedProfileReady,
      }),
    }, "\30")
  end

  INTERNAL_API.LIDCOUNCIL_BuildCurrentSectionChangeProbe = function(activeSession, memberKeys)
    activeSession = type(activeSession) == "table" and activeSession or nil
    if type(activeSession) ~= "table" then
      return ""
    end

    local signatureParts = {
      TrimText(activeSession.profileName),
      TrimText(activeSession.remoteProfileName),
      TrimText(activeSession.host),
      TrimText(activeSession.status),
      activeSession.sharedProfileReady == false and "0" or "1",
      tostring(math.max(0, tonumber(activeSession.startedAt) or 0)),
      tostring(math.max(0, tonumber(activeSession.activatedAt) or 0)),
    }
    local orderedMemberKeys = {}
    local includedMemberKeys = {}
    for _, memberKey in ipairs(type(memberKeys) == "table" and memberKeys or {}) do
      local resolvedMemberKey = NormalizeCharacterKey(memberKey)
      if resolvedMemberKey ~= "" and includedMemberKeys[resolvedMemberKey] ~= true then
        includedMemberKeys[resolvedMemberKey] = true
        orderedMemberKeys[#orderedMemberKeys + 1] = resolvedMemberKey
      end
    end
    table.sort(orderedMemberKeys)
    for _, resolvedMemberKey in ipairs(orderedMemberKeys) do
      local member = type(activeSession.members) == "table" and activeSession.members[resolvedMemberKey] or nil
      if IsSessionMemberVisibleForCurrentState(member) then
        signatureParts[#signatureParts + 1] = resolvedMemberKey .. "\30" .. BuildSessionVisibleMemberStateSignature(member)
      end
    end
    return table.concat(signatureParts, "\31")
  end

  INTERNAL_API.LIDCOUNCIL_BuildCurrentSectionStateSignature = function(activeSession)
    activeSession = type(activeSession) == "table" and activeSession or nil
    if type(activeSession) ~= "table" then
      return ""
    end

    local signatureParts = {
      TrimText(activeSession.profileName),
      TrimText(activeSession.remoteProfileName),
      TrimText(activeSession.host),
      TrimText(activeSession.status),
      activeSession.sharedProfileReady == false and "0" or "1",
      tostring(math.max(0, tonumber(activeSession.startedAt) or 0)),
      tostring(math.max(0, tonumber(activeSession.activatedAt) or 0)),
    }
    local memberEntries = {}
    for memberKey, member in pairs(type(activeSession.members) == "table" and activeSession.members or {}) do
      if type(member) == "table" then
        local resolvedMemberKey = NormalizeCharacterKey(memberKey ~= "" and memberKey or member.name or "")
        if resolvedMemberKey ~= "" and IsSessionMemberVisibleForCurrentState(member) then
          memberEntries[#memberEntries + 1] = resolvedMemberKey .. "\30" .. BuildSessionVisibleMemberStateSignature(member)
        end
      end
    end
    table.sort(memberEntries)
    for _, entry in ipairs(memberEntries) do
      signatureParts[#signatureParts + 1] = entry
    end
    return table.concat(signatureParts, "\31")
  end

  local function ClearSessionMemberBroadcastCaches(sessionId, activeSessionOverride)
    local resolvedSessionId = TrimText(sessionId)
    if resolvedSessionId == "" then
      return
    end
    local keyPrefix = string.lower(resolvedSessionId) .. "|"
    for broadcastKey in pairs(sessionRuntime.pendingSessionMemberBroadcasts) do
      if type(broadcastKey) == "string" and string.sub(broadcastKey, 1, #keyPrefix) == keyPrefix then
        sessionRuntime.pendingSessionMemberBroadcasts[broadcastKey] = nil
      end
    end
    for whisperKey in pairs(sessionRuntime.recentMemberSnapshotWhispers) do
      if type(whisperKey) == "string" and string.sub(whisperKey, 1, #keyPrefix) == keyPrefix then
        sessionRuntime.recentMemberSnapshotWhispers[whisperKey] = nil
      end
    end
    for resendKey in pairs(sessionRuntime.recentDuplicateJoinRecoveryResends) do
      if type(resendKey) == "string" and string.sub(resendKey, 1, #keyPrefix) == keyPrefix then
        sessionRuntime.recentDuplicateJoinRecoveryResends[resendKey] = nil
      end
    end
    for bootstrapKey in pairs(sessionRuntime.recentMissingMemberBootstrapRequests) do
      if type(bootstrapKey) == "string" and string.sub(bootstrapKey, 1, #keyPrefix) == keyPrefix then
        sessionRuntime.recentMissingMemberBootstrapRequests[bootstrapKey] = nil
      end
    end
    for checkpointKey in pairs(sessionRuntime.recentSessionMemberCheckpointStates) do
      if type(checkpointKey) == "string" and string.sub(checkpointKey, 1, #keyPrefix) == keyPrefix then
        sessionRuntime.recentSessionMemberCheckpointStates[checkpointKey] = nil
      end
    end
    for checkpointRequestKey in pairs(sessionRuntime.recentProfileCheckpointRequestStates) do
      if type(checkpointRequestKey) == "string" and string.sub(checkpointRequestKey, 1, #keyPrefix) == keyPrefix then
        sessionRuntime.recentProfileCheckpointRequestStates[checkpointRequestKey] = nil
      end
    end
    for emissionKey in pairs(sessionRuntime.recentRuntimeStateEmissionStates) do
      if type(emissionKey) == "string" and string.sub(emissionKey, 1, #keyPrefix) == keyPrefix then
        sessionRuntime.recentRuntimeStateEmissionStates[emissionKey] = nil
      end
    end
    local ackTimeoutRevalidationPrefix = "ack_timeout_revalidation|" .. string.lower(resolvedSessionId) .. "|"
    for revalidationKey in pairs(sessionRuntime.pendingAckTimeoutRevalidations) do
      if type(revalidationKey) == "string" and string.sub(revalidationKey, 1, #ackTimeoutRevalidationPrefix) == ackTimeoutRevalidationPrefix then
        sessionRuntime.pendingAckTimeoutRevalidations[revalidationKey] = nil
      end
    end
    if type(profileSyncMetaOps.recentAutomaticHostRepairRequestStates) == "table" then
      for repairRequestKey in pairs(profileSyncMetaOps.recentAutomaticHostRepairRequestStates) do
        if type(repairRequestKey) == "string" and string.sub(repairRequestKey, 1, #keyPrefix) == keyPrefix then
          profileSyncMetaOps.recentAutomaticHostRepairRequestStates[repairRequestKey] = nil
        end
      end
    end
    sessionRuntime.pendingDeferredMemberSnapshotsBySession[string.lower(resolvedSessionId)] = nil
    local activeSession = type(activeSessionOverride) == "table"
      and TrimText(activeSessionOverride.id) == resolvedSessionId
      and activeSessionOverride
      or GetActiveLootSession()
    activeSession = type(activeSession) == "table" and activeSession or nil
    if type(activeSession) == "table"
      and TrimText(activeSession.id) == resolvedSessionId
    then
      INTERNAL_API.LIDCOUNCIL_ClearDeferredJoinMemberRows(activeSession)
    end
  end

  local function ClearSessionTargetMemberSnapshotWhispers(sessionId, targetMemberKey)
    local resolvedSessionId = TrimText(sessionId)
    local resolvedTargetMemberKey = NormalizeCharacterKey(targetMemberKey)
    if resolvedSessionId == "" or resolvedTargetMemberKey == "" then
      return
    end
    local keyPrefix = BuildTargetMemberSnapshotWhisperStateKey(resolvedSessionId, resolvedTargetMemberKey, nil)
    for whisperKey in pairs(sessionRuntime.recentMemberSnapshotWhispers) do
      if type(whisperKey) == "string" and string.sub(whisperKey, 1, #keyPrefix) == keyPrefix then
        sessionRuntime.recentMemberSnapshotWhispers[whisperKey] = nil
      end
    end
  end

  local function ClearSessionMemberTargetedSyncRuntime(sessionId, profileName, memberKey, activeSessionOverride)
    local resolvedSessionId = TrimText(sessionId)
    local resolvedProfileName = TrimText(profileName)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if resolvedSessionId == "" or resolvedMemberKey == "" then
      return false
    end

    local activeSession = type(activeSessionOverride) == "table"
      and TrimText(activeSessionOverride.id) == resolvedSessionId
      and activeSessionOverride
      or GetActiveLootSession()
    activeSession = type(activeSession) == "table" and activeSession or nil
    if type(activeSession) == "table" and TrimText(activeSession.id) == resolvedSessionId then
      INTERNAL_API.LIDCOUNCIL_ClearDeferredJoinMemberRows(activeSession, resolvedMemberKey)
      RemoveDeferredJoinMemberKeyFromPendingSnapshots(activeSession, resolvedMemberKey)
      local activeMember = FindSessionMember(activeSession, resolvedMemberKey)
      if type(activeMember) == "table" then
        activeMember.profileApplyAckPhase = nil
        activeMember.profileApplyQueuedAt = nil
        activeMember.profileApplyPendingId = nil
        activeMember.profileApplyPendingKind = nil
      end
    end

    local memberKeyLower = string.lower(resolvedMemberKey)
    local sessionKeyLower = string.lower(resolvedSessionId)
    local directBroadcastKey = sessionKeyLower .. "|" .. memberKeyLower
    local detailedComparisonRequestPrefix = directBroadcastKey .. "|"
    local autoDetailTimerKey = "auto_detail_timer|" .. directBroadcastKey
    local postBootstrapRevalidationTimerKey = "post_bootstrap_revalidation|" .. directBroadcastKey
    local ackTimeoutRevalidationKey = "ack_timeout_revalidation|" .. directBroadcastKey
    sessionRuntime.pendingSessionMemberBroadcasts[directBroadcastKey] = nil
    ClearSessionTargetMemberSnapshotWhispers(resolvedSessionId, resolvedMemberKey)
    sessionRuntime.recentDuplicateJoinRecoveryResends[directBroadcastKey] = nil
    sessionRuntime.recentMissingMemberBootstrapRequests[directBroadcastKey] = nil
    sessionRuntime.recentMemberRepairRequestStates[directBroadcastKey] = nil
    sessionRuntime.recentMemberPrecisePrewarmRequests[directBroadcastKey] = nil
    local missingMemberHistoryTimerPrefix = BuildMissingMemberHistoryTimerKey(resolvedSessionId, resolvedMemberKey)
    for timerKey in pairs(sessionRuntime.pendingMissingMemberHistoryTimers) do
      if timerKey == missingMemberHistoryTimerPrefix
        or string.sub(timerKey, 1, #missingMemberHistoryTimerPrefix + 1) == (missingMemberHistoryTimerPrefix .. "|")
      then
        sessionRuntime.pendingMissingMemberHistoryTimers[timerKey] = nil
      end
    end
    for catchupKey in pairs(sessionRuntime.latestSessionHistoryCatchups) do
      if type(catchupKey) == "string" and string.sub(catchupKey, 1, #sessionKeyPrefix) == sessionKeyPrefix then
        sessionRuntime.latestSessionHistoryCatchups[catchupKey] = nil
      end
    end
    sessionRuntime.pendingAutoDetailedComparisonTimers[autoDetailTimerKey] = nil
    sessionRuntime.pendingPostBootstrapRevalidationTimers[postBootstrapRevalidationTimerKey] = nil
    sessionRuntime.pendingAckTimeoutRevalidations[ackTimeoutRevalidationKey] = nil
    for requestStamp in pairs(sessionRuntime.recentAutoSubcheckRequestTimes) do
      if type(requestStamp) == "string" and string.sub(requestStamp, 1, #detailedComparisonRequestPrefix) == detailedComparisonRequestPrefix then
        sessionRuntime.recentAutoSubcheckRequestTimes[requestStamp] = nil
      end
    end

    if type(profileSyncMetaOps.clearPendingJoinManifestRepair) == "function" then
      profileSyncMetaOps.clearPendingJoinManifestRepair(resolvedSessionId, resolvedMemberKey)
    end
    if type(profileSyncMetaOps.clearPendingPatchStateRetry) == "function" then
      profileSyncMetaOps.clearPendingPatchStateRetry(resolvedSessionId, resolvedMemberKey)
    end

    if resolvedProfileName ~= "" then
      local checkpointStateKey = BuildProfileCheckpointStateKey(resolvedSessionId, resolvedProfileName)
      local checkpointMemberStateKey = checkpointStateKey .. "|member|" .. memberKeyLower
      local checkpointRepairStateKey = checkpointStateKey .. "|" .. memberKeyLower
      sessionRuntime.recentSessionMemberCheckpointStates[checkpointMemberStateKey] = nil
      if type(profileSyncMetaOps.recentAutomaticHostRepairRequestStates) == "table" then
        profileSyncMetaOps.recentAutomaticHostRepairRequestStates[checkpointRepairStateKey] = nil
      end

      local pendingCheckpoint = sessionRuntime.pendingProfileCheckpointSyncs[checkpointStateKey]
      local checkpointRowId = "session:member:" .. resolvedMemberKey
      if type(pendingCheckpoint) == "table" then
        local rowsChanged = false
        if type(pendingCheckpoint.prebuiltRowsBySubdomain) == "table" then
          for subdomain, rows in pairs(pendingCheckpoint.prebuiltRowsBySubdomain) do
            if type(rows) == "table" then
              local keptRows = {}
              local removedAny = false
              for _, row in ipairs(rows) do
                if tostring(type(row) == "table" and row.id or "") ~= checkpointRowId then
                  keptRows[#keptRows + 1] = row
                else
                  removedAny = true
                end
              end
              if removedAny then
                rowsChanged = true
                if #keptRows > 0 then
                  pendingCheckpoint.prebuiltRowsBySubdomain[subdomain] = keptRows
                else
                  pendingCheckpoint.prebuiltRowsBySubdomain[subdomain] = nil
                end
              end
            end
          end
        end
        if type(pendingCheckpoint.prebuiltRowSignaturesBySubdomain) == "table" then
          for subdomain, rowSignatures in pairs(pendingCheckpoint.prebuiltRowSignaturesBySubdomain) do
            if type(rowSignatures) == "table" and rowSignatures[checkpointRowId] ~= nil then
              rowSignatures[checkpointRowId] = nil
              rowsChanged = true
              if not next(rowSignatures) then
                pendingCheckpoint.prebuiltRowSignaturesBySubdomain[subdomain] = nil
              end
            end
          end
        end
        if rowsChanged then
          pendingCheckpoint.__checkpointRequestSignature = nil
          pendingCheckpoint.__checkpointTargetSignature = nil
          pendingCheckpoint.__checkpointTransportSignature = nil
        end
      end
    end

    for changeId, pendingAck in pairs(sessionRuntime.pendingProfileDeltaAcks) do
      if type(pendingAck) == "table" and type(pendingAck.missing) == "table" and pendingAck.missing[resolvedMemberKey] ~= nil then
        pendingAck.missing[resolvedMemberKey] = nil
        if type(pendingAck.queued) == "table" then
          pendingAck.queued[resolvedMemberKey] = nil
        end
        if not next(pendingAck.missing) then
          sessionRuntime.pendingProfileDeltaAcks[changeId] = nil
        end
      end
    end
    return true
  end

  local function ClearSessionScopedSyncRuntime(sessionId, activeSessionOverride)
    local resolvedSessionId = TrimText(sessionId)
    if resolvedSessionId == "" then
      return false
    end

    local sessionKeyPrefix = string.lower(resolvedSessionId) .. "|"
    local deltaRuntimeKeyPrefix = resolvedSessionId .. ":"
    local autoDetailTimerPrefix = "auto_detail_timer|" .. string.lower(resolvedSessionId) .. "|"
    local postBootstrapRevalidationTimerPrefix = "post_bootstrap_revalidation|" .. string.lower(resolvedSessionId) .. "|"
    local patchRetryPrefix = "patchstate|" .. sessionKeyPrefix

    sessionRuntime.pendingInvites[resolvedSessionId] = nil
    sessionRuntime.pendingJoinRequests[resolvedSessionId] = nil

    ClearSessionMemberBroadcastCaches(resolvedSessionId, activeSessionOverride)
    for repairRequestKey in pairs(sessionRuntime.recentMemberRepairRequestStates) do
      if type(repairRequestKey) == "string" and string.sub(repairRequestKey, 1, #sessionKeyPrefix) == sessionKeyPrefix then
        sessionRuntime.recentMemberRepairRequestStates[repairRequestKey] = nil
      end
    end

    for timerKey in pairs(sessionRuntime.pendingMissingMemberHistoryTimers) do
      if type(timerKey) == "string" and string.sub(timerKey, 1, #sessionKeyPrefix) == sessionKeyPrefix then
        sessionRuntime.pendingMissingMemberHistoryTimers[timerKey] = nil
      end
    end
    for repairKey in pairs(sessionRuntime.pendingJoinManifestRepairTimers.joinManifest) do
      if type(repairKey) == "string" and string.sub(repairKey, 1, #sessionKeyPrefix) == sessionKeyPrefix then
        sessionRuntime.pendingJoinManifestRepairTimers.joinManifest[repairKey] = nil
      end
    end
    if type(profileSyncMetaOps.clearJoinManifestProofTombstones) == "function" then
      profileSyncMetaOps.clearJoinManifestProofTombstones(resolvedSessionId)
    end
    for retryKey in pairs(sessionRuntime.pendingJoinManifestRepairTimers.patchStateRetry) do
      if type(retryKey) == "string" and string.sub(retryKey, 1, #patchRetryPrefix) == patchRetryPrefix then
        sessionRuntime.pendingJoinManifestRepairTimers.patchStateRetry[retryKey] = nil
      end
    end
    for pendingKey in pairs(sessionRuntime.pendingProfileCheckpointSyncs) do
      if type(pendingKey) == "string" and string.sub(pendingKey, 1, #sessionKeyPrefix) == sessionKeyPrefix then
        sessionRuntime.pendingProfileCheckpointSyncs[pendingKey] = nil
      end
    end
    for timerKey in pairs(sessionRuntime.pendingProfileCheckpointTimers) do
      if type(timerKey) == "string" and string.sub(timerKey, 1, #sessionKeyPrefix) == sessionKeyPrefix then
        sessionRuntime.pendingProfileCheckpointTimers[timerKey] = nil
      end
    end
    for lastSentKey in pairs(sessionRuntime.lastProfileCheckpointSyncAt) do
      if type(lastSentKey) == "string" and string.sub(lastSentKey, 1, #sessionKeyPrefix) == sessionKeyPrefix then
        sessionRuntime.lastProfileCheckpointSyncAt[lastSentKey] = nil
      end
    end
    for changeId, pendingAck in pairs(sessionRuntime.pendingProfileDeltaAcks) do
      if type(pendingAck) == "table" and TrimText(pendingAck.sessionId) == resolvedSessionId then
        sessionRuntime.pendingProfileDeltaAcks[changeId] = nil
      end
    end
    sessionRuntime.profileDeltaAckSupersededTotal = 0
    for runtimeKey in pairs(sessionRuntime.profileDeltaLastSequence) do
      if type(runtimeKey) == "string" and string.sub(runtimeKey, 1, #deltaRuntimeKeyPrefix) == deltaRuntimeKeyPrefix then
        sessionRuntime.profileDeltaLastSequence[runtimeKey] = nil
      end
    end
    for changeId, seenState in pairs(sessionRuntime.appliedProfileDeltaIds) do
      if type(seenState) == "table" and TrimText(seenState.sessionId) == resolvedSessionId then
        sessionRuntime.appliedProfileDeltaIds[changeId] = nil
      end
    end
    for requestStamp in pairs(sessionRuntime.recentAutoSubcheckRequestTimes) do
      if type(requestStamp) == "string" and string.sub(requestStamp, 1, #sessionKeyPrefix) == sessionKeyPrefix then
        sessionRuntime.recentAutoSubcheckRequestTimes[requestStamp] = nil
      end
    end
    for requestKey in pairs(sessionRuntime.recentMemberPrecisePrewarmRequests) do
      if type(requestKey) == "string" and string.sub(requestKey, 1, #sessionKeyPrefix) == sessionKeyPrefix then
        sessionRuntime.recentMemberPrecisePrewarmRequests[requestKey] = nil
      end
    end
    for pendingKey in pairs(sessionRuntime.pendingAutoDetailedComparisonTimers) do
      if type(pendingKey) == "string" and string.sub(pendingKey, 1, #autoDetailTimerPrefix) == autoDetailTimerPrefix then
        sessionRuntime.pendingAutoDetailedComparisonTimers[pendingKey] = nil
      end
    end
    for pendingKey in pairs(sessionRuntime.pendingPostBootstrapRevalidationTimers) do
      if type(pendingKey) == "string" and string.sub(pendingKey, 1, #postBootstrapRevalidationTimerPrefix) == postBootstrapRevalidationTimerPrefix then
        sessionRuntime.pendingPostBootstrapRevalidationTimers[pendingKey] = nil
      end
    end
    if type(INTERNAL_API.LIDCOUNCIL_ClearCombatSyncInboxSession_Impl) == "function" then
      INTERNAL_API.LIDCOUNCIL_ClearCombatSyncInboxSession_Impl(resolvedSessionId)
    end
    if type(INTERNAL_API.LIDCOUNCIL_ClearLootRuntimeCommSessionState_Impl) == "function" then
      INTERNAL_API.LIDCOUNCIL_ClearLootRuntimeCommSessionState_Impl(resolvedSessionId)
    end

    return true
  end

  function sessionLifecycleOps.emitRuntimeStateNotice(sessionId, profileName, runtimeOpts, opts)
    runtimeOpts = type(runtimeOpts) == "table" and runtimeOpts or {}
    opts = type(opts) == "table" and opts or {}
    local coalesced, coalesceKey, coalesceSignature, coalesceNow = sessionLifecycleOps.shouldCoalesceRuntimeStateEmission(
      sessionId,
      profileName,
      runtimeOpts,
      opts
    )
    if coalesced then
      return false
    end
    local runtimeStateKey = TrimText(runtimeOpts.runtimeStateKey)
    local runtimeStateMessage = TrimText(runtimeOpts.runtimeStateMessage)
    local refreshEditor = runtimeOpts.refreshEditor
    if opts.refreshEditor ~= nil then
      refreshEditor = opts.refreshEditor
    end
    local runtimeStateChanged = false
    if runtimeStateKey ~= "" and runtimeStateMessage ~= "" then
      runtimeStateChanged = deps.SetProfileSyncRuntimeState(
        sessionId,
        profileName,
        runtimeStateKey,
        FirstNonEmptyText(runtimeOpts.runtimeStateLevel, "info"),
        runtimeStateMessage,
        {
          sender = opts.sender ~= nil and opts.sender or runtimeOpts.sender,
          localDomains = type(opts.localDomains) == "table" and opts.localDomains or nil,
          remoteDomains = type(opts.remoteDomains) == "table" and opts.remoteDomains or nil,
          rosterEvent = type(opts.rosterEvent) == "table" and opts.rosterEvent or nil,
          skipIfSame = opts.skipIfSame == true,
          refreshEditor = refreshEditor,
        }
      )
    end
    if runtimeStateChanged then
      RecordRaidTestTraceEvent("SYNC_STATE", runtimeStateMessage, {
        state = runtimeStateKey,
        level = FirstNonEmptyText(runtimeOpts.runtimeStateLevel, "info"),
        sender = opts.sender ~= nil and opts.sender or runtimeOpts.sender,
        session = TrimText(sessionId),
        profile = TrimText(profileName),
      })
    end
    local noticeText = TrimText(FirstNonEmptyText(opts.noticeText, runtimeStateMessage))
    if opts.printNotice ~= false and noticeText ~= "" and (runtimeStateChanged or opts.printWhenChangedOnly ~= true) then
      Print(noticeText)
    end
    if opts.refreshSyncManagement == true and runtimeStateChanged and refreshEditor == false then
      sessionUiOps.refreshSyncManagementSection({
        defer = opts.defer,
        delaySeconds = opts.delaySeconds,
        forceImmediate = opts.forceImmediate,
      })
    end
    if type(coalesceKey) == "string" and coalesceKey ~= "" then
      sessionLifecycleOps.rememberRuntimeStateEmission(coalesceKey, coalesceSignature, coalesceNow)
    end
    return runtimeStateChanged
  end

  function sessionLifecycleOps.buildRuntimeStateEmissionCoalesceState(sessionId, profileName, runtimeOpts, opts)
    runtimeOpts = type(runtimeOpts) == "table" and runtimeOpts or {}
    opts = type(opts) == "table" and opts or {}
    local coalesceWindowSeconds = math.max(0, tonumber(opts.coalesceWindowSeconds) or 0)
    if coalesceWindowSeconds <= 0 then
      return nil
    end

    local resolvedCoalesceKey = TrimText(opts.coalesceKey)
    if resolvedCoalesceKey == "" then
      local resolvedRuntimeStateKey = TrimText(runtimeOpts.runtimeStateKey)
      local resolvedSender = NormalizeSenderKey(opts.sender ~= nil and opts.sender or runtimeOpts.sender)
      local resolvedNoticeText = TrimText(FirstNonEmptyText(opts.noticeText, runtimeOpts.runtimeStateMessage))
      if resolvedRuntimeStateKey == "" and resolvedNoticeText == "" then
        return nil
      end
      resolvedCoalesceKey = "runtime"
      if resolvedRuntimeStateKey ~= "" then
        resolvedCoalesceKey = resolvedCoalesceKey .. "|" .. string.lower(resolvedRuntimeStateKey)
      end
      if resolvedSender ~= "" then
        resolvedCoalesceKey = resolvedCoalesceKey .. "|" .. string.lower(resolvedSender)
      end
    end

    local resolvedSessionId = string.lower(TrimText(sessionId))
    local resolvedProfileName = string.lower(TrimText(profileName))
    local fullCoalesceKey = resolvedSessionId .. "|" .. resolvedProfileName .. "|" .. string.lower(resolvedCoalesceKey)
    local resolvedCoalesceSignature = TrimText(opts.coalesceSignature)
    if resolvedCoalesceSignature == "" then
      resolvedCoalesceSignature = table.concat({
        TrimText(runtimeOpts.runtimeStateKey),
        FirstNonEmptyText(runtimeOpts.runtimeStateLevel, "info"),
        TrimText(runtimeOpts.runtimeStateMessage),
        TrimText(FirstNonEmptyText(opts.noticeText, "")),
      }, "\31")
    end

    return fullCoalesceKey, resolvedCoalesceSignature, coalesceWindowSeconds, GetProfileCheckpointSyncTime()
  end

  function sessionLifecycleOps.shouldCoalesceRuntimeStateEmission(sessionId, profileName, runtimeOpts, opts)
    local coalesceKey, coalesceSignature, coalesceWindowSeconds, now =
      sessionLifecycleOps.buildRuntimeStateEmissionCoalesceState(sessionId, profileName, runtimeOpts, opts)
    if type(coalesceKey) ~= "string" or coalesceKey == "" then
      return false, nil, nil, now
    end

    local recentState = sessionRuntime.recentRuntimeStateEmissionStates[coalesceKey]
    local emittedAt = math.max(0, tonumber(type(recentState) == "table" and recentState.emittedAt or 0) or 0)
    if emittedAt > 0
      and (math.max(0, tonumber(now) or 0) - emittedAt) < coalesceWindowSeconds
      and TrimText(type(recentState) == "table" and recentState.signature or "") == coalesceSignature
    then
      recentState.updatedAt = math.max(0, tonumber(now) or 0)
      return true, coalesceKey, coalesceSignature, now
    end

    return false, coalesceKey, coalesceSignature, now
  end

  function sessionLifecycleOps.rememberRuntimeStateEmission(coalesceKey, coalesceSignature, now)
    local resolvedCoalesceKey = TrimText(coalesceKey)
    if resolvedCoalesceKey == "" then
      return false
    end

    local resolvedNow = math.max(0, tonumber(now) or 0)
    if resolvedNow <= 0 then
      resolvedNow = GetProfileCheckpointSyncTime()
    end
    sessionRuntime.recentRuntimeStateEmissionStates[resolvedCoalesceKey] = {
      signature = TrimText(coalesceSignature),
      emittedAt = resolvedNow,
      updatedAt = resolvedNow,
    }
    return true
  end

  function sessionLifecycleOps.finalizeEndedLocalLootSession(sessionId, profileName, opts)
    opts = type(opts) == "table" and opts or {}
    local resolvedSessionId = TrimText(sessionId)
    local resolvedProfileName = FirstNonEmptyText(profileName)

    if resolvedSessionId ~= "" then
      ClearSessionScopedSyncRuntime(resolvedSessionId, opts.activeSession)
      optionalApiOps.cancelSessionSyncArtifacts(resolvedSessionId)
    end

    if type(INTERNAL_API.LIDCOUNCIL_ResetDeferredEditorRefresh_Impl) == "function" then
      INTERNAL_API.LIDCOUNCIL_ResetDeferredEditorRefresh_Impl()
    end
    if type(INTERNAL_API.LIDCOUNCIL_ResetDeferredRuntimeUiRefreshState_Impl) == "function" then
      INTERNAL_API.LIDCOUNCIL_ResetDeferredRuntimeUiRefreshState_Impl()
    end
    optionalApiOps.clearLiveLootRuntime()

    sessionLifecycleOps.emitRuntimeStateNotice(resolvedSessionId, resolvedProfileName, opts, {
      printNotice = false,
      refreshEditor = false,
    })

    if opts.refreshEditor ~= false then
      sessionUiOps.refreshPanelsAndLiveBoard()
    end

    return true
  end

  function sessionLifecycleOps.emitTransitionStateNotice(sessionId, profileName, eventKey, opts)
    opts = type(opts) == "table" and opts or {}
    local runtimeOpts = sessionLifecycleOps.buildTransitionRuntimeOpts(eventKey, opts)
    return sessionLifecycleOps.emitRuntimeStateNotice(sessionId, profileName, runtimeOpts, {
      printNotice = opts.printNotice,
      noticeText = sessionLifecycleOps.buildTransitionNoticeText(eventKey, opts),
    })
  end

  function sessionLifecycleOps.emitMemberStateNotice(sessionId, profileName, eventKey, opts)
    opts = type(opts) == "table" and opts or {}
    local runtimeOpts = sessionLifecycleOps.buildMemberRuntimeOpts(eventKey, opts)
    return sessionLifecycleOps.emitRuntimeStateNotice(sessionId, profileName, runtimeOpts, {
      printNotice = opts.printNotice,
      noticeText = sessionLifecycleOps.buildMemberNoticeText(eventKey, opts),
      rosterEvent = type(opts.rosterEvent) == "table" and opts.rosterEvent or nil,
    })
  end

  function sessionLifecycleOps.finalizeEndedSessionEvent(sessionId, profileName, eventKey, opts)
    opts = type(opts) == "table" and opts or {}
    sessionLifecycleOps.finalizeEndedLocalLootSession(
      sessionId,
      profileName,
      sessionLifecycleOps.buildEndFinalizeOpts(eventKey, opts)
    )
    if opts.printNotice ~= false then
      local noticeText = sessionLifecycleOps.buildEndNoticeText(eventKey, opts)
      if TrimText(noticeText) ~= "" then
        Print(noticeText)
      end
    end
    return true
  end

  function sessionLifecycleOps.emitSyncRuntimeStateNotice(sessionId, profileName, eventKey, opts)
    opts = type(opts) == "table" and opts or {}
    local runtimeOpts = sessionLifecycleOps.buildSyncRuntimeOpts(eventKey, opts)
    return sessionLifecycleOps.emitRuntimeStateNotice(sessionId, profileName, runtimeOpts, {
      sender = runtimeOpts.sender,
      localDomains = opts.localDomains,
      remoteDomains = opts.remoteDomains,
      skipIfSame = opts.skipIfSame == true,
      refreshEditor = runtimeOpts.refreshEditor,
      printNotice = opts.printNotice,
      printWhenChangedOnly = opts.printWhenChangedOnly,
      noticeText = sessionLifecycleOps.buildSyncNoticeText(eventKey, opts),
      coalesceWindowSeconds = opts.coalesceWindowSeconds,
      coalesceKey = opts.coalesceKey,
      coalesceSignature = opts.coalesceSignature,
    })
  end

  function sessionLifecycleOps.emitSyncRuntimeState(sessionId, profileName, runtimeStateKey, runtimeStateLevel, runtimeStateMessage, opts)
    opts = type(opts) == "table" and opts or {}
    local resolvedRuntimeStateKey = TrimText(runtimeStateKey)
    local resolvedRuntimeStateMessage = TrimText(runtimeStateMessage)
    return sessionLifecycleOps.emitRuntimeStateNotice(sessionId, profileName, {
      runtimeStateKey = resolvedRuntimeStateKey,
      runtimeStateLevel = runtimeStateLevel,
      runtimeStateMessage = resolvedRuntimeStateMessage,
      sender = opts.sender,
      refreshEditor = false,
    }, {
      sender = opts.sender,
      localDomains = opts.localDomains,
      remoteDomains = opts.remoteDomains,
      skipIfSame = opts.skipIfSame == true,
      refreshEditor = false,
      printNotice = opts.printNotice,
      printWhenChangedOnly = opts.printWhenChangedOnly,
      noticeText = FirstNonEmptyText(opts.noticeText, resolvedRuntimeStateMessage),
      rosterEvent = type(opts.rosterEvent) == "table" and opts.rosterEvent or nil,
      refreshSyncManagement = opts.refreshSyncManagement == true,
      coalesceWindowSeconds = opts.coalesceWindowSeconds,
      coalesceKey = opts.coalesceKey,
      coalesceSignature = opts.coalesceSignature,
    })
  end

  function sessionLifecycleOps.emitRepairRuntimeState(sessionId, profileName, runtimeStateKey, runtimeStateLevel, runtimeStateMessage, opts)
    opts = type(opts) == "table" and opts or {}
    return sessionLifecycleOps.emitSyncRuntimeState(sessionId, profileName, runtimeStateKey, runtimeStateLevel, runtimeStateMessage, {
      sender = opts.sender,
      localDomains = opts.localDomains,
      remoteDomains = opts.remoteDomains,
      skipIfSame = opts.skipIfSame ~= false,
      printNotice = opts.printNotice,
      printWhenChangedOnly = opts.printWhenChangedOnly,
      noticeText = FirstNonEmptyText(opts.noticeText, TrimText(runtimeStateMessage)),
      refreshSyncManagement = opts.refreshSyncManagement == true,
      coalesceWindowSeconds = opts.coalesceWindowSeconds,
      coalesceKey = opts.coalesceKey,
      coalesceSignature = opts.coalesceSignature,
    })
  end

  local function RefreshHostSessionMemberState(profileName, sessionId, opts)
    opts = type(opts) == "table" and opts or {}
    local activeSession, activeProfileName = GetActiveLootSession()
    if type(activeSession) ~= "table" then
      return false, "No active session."
    end

    local resolvedProfileName = FirstNonEmptyText(profileName, activeProfileName, activeSession.profileName, activeSession.remoteProfileName)
    local resolvedSessionId = FirstNonEmptyText(sessionId, activeSession.id)
    if resolvedProfileName == "" or resolvedSessionId == "" then
      return false, "Missing active session identity."
    end
    if TrimText(activeSession.id) ~= TrimText(resolvedSessionId)
      or not DoesActiveSessionMatch(activeSession, activeProfileName, resolvedSessionId, resolvedProfileName) then
      return false, "No matching active session."
    end

    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if selfKey == "" or not AreCharacterKeysSame(activeSession.host or "", selfKey) then
      return false, "Only the host can refresh the host member row."
    end

    local currentMember = type(activeSession.members) == "table" and activeSession.members[selfKey] or nil
    local previousVisibleState = BuildSessionVisibleMemberStateSignature(currentMember)
    local revisionSummary = type(GetLootProfileRevisionSummary) == "function" and GetLootProfileRevisionSummary(resolvedProfileName) or nil
    local payloadDetails = deps.GetMemberPayloadDetails(nil, true)
    local resolvedTarget = NormalizeCharacterKey(opts.target)
    local desiredHostMemberState = BuildMemberBroadcastPayloadState(resolvedProfileName, resolvedSessionId, selfKey, {
      status = FirstNonEmptyText(opts.status, type(currentMember) == "table" and currentMember.status or "JOINED"),
      joinedAt = tonumber(type(currentMember) == "table" and currentMember.joinedAt) or (time and time() or 0),
      leftAt = opts.clearLeftAt == true and nil or (type(currentMember) == "table" and currentMember.leftAt or nil),
      profileMaster = type(deps.GetLootProfileMaster) == "function" and deps.GetLootProfileMaster(resolvedProfileName) or "",
      role = type(deps.GetLootProfileRole) == "function" and deps.GetLootProfileRole(resolvedProfileName, selfKey) or "",
      addonVersion = payloadDetails.addonVersion,
      clientVersion = payloadDetails.clientVersion,
      className = payloadDetails.className,
      classFile = payloadDetails.classFile,
      specName = payloadDetails.specName,
      specIcon = payloadDetails.specIcon,
      localAutoPassEnabled = type(deps.GetLocalAutoPassEnabled) == "function"
        and (deps.GetLocalAutoPassEnabled() and true or false)
        or payloadDetails.localAutoPassEnabled,
      revisionSummary = revisionSummary,
    })
    local desiredVisibleState = BuildSessionVisibleMemberStateSignature(desiredHostMemberState)
    local desiredPayloadSignature = BuildMemberBroadcastPayloadSignature(desiredHostMemberState)
    local hasExplicitTarget = TrimText(opts.channel) ~= "" or resolvedTarget ~= ""
    local targetedSendDecision = hasExplicitTarget and GetTargetedMemberSnapshotSendDecision(
      resolvedSessionId,
      resolvedTarget,
      selfKey,
      desiredHostMemberState,
      {
        onlyChangedForTarget = opts.onlyChangedForTarget == true,
      }
    ) or nil
    local payloadUnchanged = previousVisibleState == desiredVisibleState
    local shouldBroadcast = opts.broadcast ~= false and (
      opts.forceBroadcast == true or hasExplicitTarget or not payloadUnchanged
    )
    if hasExplicitTarget
      and opts.onlyChangedForTarget == true
      and type(targetedSendDecision) == "table"
      and targetedSendDecision.shouldSend ~= true
    then
      return true, currentMember, {
        updatedMember = currentMember,
        payloadUnchanged = payloadUnchanged,
        visibleStateChanged = not payloadUnchanged,
        mutated = false,
        broadcastSent = false,
        skippedForTarget = true,
        explicitTarget = true,
        target = resolvedTarget,
        visibleStateSignature = desiredVisibleState,
        payloadSignature = desiredPayloadSignature,
      }
    end
    if not shouldBroadcast and payloadUnchanged then
      return true, currentMember, {
        updatedMember = currentMember,
        payloadUnchanged = true,
        visibleStateChanged = false,
        mutated = false,
        broadcastSent = false,
        skippedForTarget = false,
        explicitTarget = hasExplicitTarget,
        target = resolvedTarget,
        visibleStateSignature = desiredVisibleState,
        payloadSignature = desiredPayloadSignature,
      }
    end
    if shouldBroadcast and payloadUnchanged and type(currentMember) == "table" then
      local broadcastSent = BroadcastMember(
        resolvedProfileName,
        resolvedSessionId,
        selfKey,
        currentMember,
        opts.channel,
        opts.target,
        {
          suppressCheckpoint = opts.suppressCheckpoint ~= false,
          payloadBundle = {
            payloadState = desiredHostMemberState,
            payloadSignature = desiredPayloadSignature,
            visibleStateSignature = desiredVisibleState,
          },
        }
      )
      return true, currentMember, {
        updatedMember = currentMember,
        payloadUnchanged = true,
        visibleStateChanged = false,
        mutated = false,
        broadcastSent = broadcastSent == true,
        skippedForTarget = false,
        explicitTarget = hasExplicitTarget,
        target = resolvedTarget,
        visibleStateSignature = desiredVisibleState,
        payloadSignature = desiredPayloadSignature,
      }
    end
    desiredHostMemberState.revisionSummary = revisionSummary
    desiredHostMemberState.suppressProfileTouch = true
    local ok, member = UpsertLootSessionMember(resolvedProfileName, resolvedSessionId, selfKey, desiredHostMemberState)
    if not ok then
      return false, member
    end
    local updatedMember = member or currentMember or {}
    local broadcastSent = false
    if shouldBroadcast then
      broadcastSent = BroadcastMember(
        resolvedProfileName,
        resolvedSessionId,
        selfKey,
        updatedMember,
        opts.channel,
        opts.target,
        {
          suppressCheckpoint = opts.suppressCheckpoint ~= false,
          payloadBundle = {
            payloadState = desiredHostMemberState,
            payloadSignature = desiredPayloadSignature,
            visibleStateSignature = desiredVisibleState,
          },
        }
      )
    end
    return true, member, {
      updatedMember = updatedMember,
      payloadUnchanged = false,
      visibleStateChanged = true,
      mutated = true,
      broadcastSent = broadcastSent == true,
      skippedForTarget = false,
      explicitTarget = hasExplicitTarget,
      target = resolvedTarget,
      visibleStateSignature = desiredVisibleState,
      payloadSignature = desiredPayloadSignature,
    }
  end

  local function SendMemberSnapshot(activeSession, profileName, target, opts)
    opts = type(opts) == "table" and opts or {}
    if type(activeSession) ~= "table" or type(activeSession.members) ~= "table" then
      return 0
    end
    local resolvedSessionId = TrimText(activeSession.id)
    local resolvedTarget = NormalizeCharacterKey(target)
    if resolvedSessionId == "" or resolvedTarget == "" then
      return 0
    end
    local includedMemberKeys = nil
    local orderedIncludedMemberKeys = nil
    if type(opts.memberKeys) == "table" then
      includedMemberKeys = {}
      orderedIncludedMemberKeys = {}
      for _, value in ipairs(opts.memberKeys) do
        local resolvedValue = NormalizeCharacterKey(value)
        if resolvedValue ~= "" and includedMemberKeys[resolvedValue] ~= true then
          includedMemberKeys[resolvedValue] = true
          orderedIncludedMemberKeys[#orderedIncludedMemberKeys + 1] = resolvedValue
        end
      end
    end
    local alwaysIncludeMemberKeys = {}
    if type(opts.alwaysIncludeMemberKeys) == "table" then
      for _, value in ipairs(opts.alwaysIncludeMemberKeys) do
        local resolvedValue = NormalizeCharacterKey(value)
        if resolvedValue ~= "" then
          alwaysIncludeMemberKeys[resolvedValue] = true
        end
      end
    end
    local now = GetProfileCheckpointSyncTime()
    local sentCount = 0
    local function SendSnapshotRow(memberKey, member)
      local resolvedMemberKey = NormalizeCharacterKey(memberKey)
      if resolvedMemberKey ~= ""
        and (includedMemberKeys == nil or includedMemberKeys[resolvedMemberKey] == true)
        and type(member) == "table"
        and IsSessionMemberVisibleForCurrentState(member)
      then
        local payloadState = type(opts.prebuiltPayloadStates) == "table"
          and type(opts.prebuiltPayloadStates[resolvedMemberKey]) == "table"
          and opts.prebuiltPayloadStates[resolvedMemberKey]
          or BuildMemberBroadcastPayloadState(profileName, resolvedSessionId, resolvedMemberKey, member)
        local alwaysInclude = alwaysIncludeMemberKeys[resolvedMemberKey] == true
        local prebuiltVisibleStateSignature = type(opts.prebuiltVisibleSignatures) == "table"
          and TrimText(opts.prebuiltVisibleSignatures[resolvedMemberKey])
          or ""
        local sendDecision = opts.skipSendDecision == true and {
          shouldSend = true,
          signature = prebuiltVisibleStateSignature ~= ""
            and prebuiltVisibleStateSignature
            or BuildSessionVisibleMemberStateSignature(payloadState),
          dedupeKey = BuildTargetMemberSnapshotWhisperStateKey(
            resolvedSessionId,
            resolvedTarget,
            resolvedMemberKey
          ),
        } or GetTargetedMemberSnapshotSendDecision(
          resolvedSessionId,
          resolvedTarget,
          resolvedMemberKey,
          payloadState,
          {
            onlyChangedForTarget = opts.onlyChangedForTarget == true,
            alwaysInclude = alwaysInclude,
            now = now,
          }
        )
        if sendDecision.shouldSend then
          local payloadSignature = BuildMemberBroadcastPayloadSignature(payloadState)
          local sent = BroadcastMember(profileName, resolvedSessionId, resolvedMemberKey, member, "WHISPER", resolvedTarget, {
            payloadBundle = {
              payloadState = payloadState,
              payloadSignature = payloadSignature,
              visibleStateSignature = sendDecision.signature,
            },
          })
          if sent then
            sentCount = sentCount + 1
            sessionRuntime.recentMemberSnapshotWhispers[sendDecision.dedupeKey] = {
              signature = sendDecision.signature,
              sentAt = now,
            }
          end
        end
      end
    end
    if type(orderedIncludedMemberKeys) == "table" then
      for _, resolvedMemberKey in ipairs(orderedIncludedMemberKeys) do
        SendSnapshotRow(resolvedMemberKey, select(1, FindSessionMember(activeSession, resolvedMemberKey)))
      end
    else
      for memberKey, member in pairs(activeSession.members) do
        SendSnapshotRow(memberKey, member)
      end
    end
    return sentCount
  end

  local function GetDeferredJoinSnapshotMemberPriority(member)
    member = type(member) == "table" and member or nil
    local status = string.upper(TrimText(type(member) == "table" and member.status or "JOINED"))
    if status == "LEFT" then
      return 0, math.max(0, tonumber(type(member) == "table" and member.leftAt) or 0)
    end
    if status ~= "JOINED" then
      return 1, math.max(0, tonumber(type(member) == "table" and member.leftAt) or 0)
    end
    return 2, math.max(0, tonumber(type(member) == "table" and member.joinedAt) or 0)
  end

  local function BuildPriorityTargetedMemberSnapshotSendPlan(activeSession, profileName, targetMemberKey, memberKeys, opts)
    opts = type(opts) == "table" and opts or {}
    activeSession = type(activeSession) == "table" and activeSession or nil
    local resolvedProfileName = TrimText(profileName)
    local resolvedTargetMemberKey = NormalizeCharacterKey(targetMemberKey)
    local resolvedSessionId = TrimText(type(activeSession) == "table" and activeSession.id or "")
    if type(activeSession) ~= "table"
      or type(activeSession.members) ~= "table"
      or resolvedProfileName == ""
      or resolvedSessionId == ""
      or resolvedTargetMemberKey == ""
    then
      return {}
    end

    local normalizedMemberKeys = {}
    local includedMemberKeys = {}
    for _, value in ipairs(type(memberKeys) == "table" and memberKeys or {}) do
      local resolvedValue = NormalizeCharacterKey(value)
      if resolvedValue ~= "" and includedMemberKeys[resolvedValue] ~= true then
        includedMemberKeys[resolvedValue] = true
        normalizedMemberKeys[#normalizedMemberKeys + 1] = resolvedValue
      end
    end
    local alwaysIncludeLookup = {}
    for _, value in ipairs(type(opts.alwaysIncludeMemberKeys) == "table" and opts.alwaysIncludeMemberKeys or {}) do
      local resolvedValue = NormalizeCharacterKey(value)
      if resolvedValue ~= "" then
        alwaysIncludeLookup[resolvedValue] = true
      end
    end

    local plannedMemberKeys = {}
    local prebuiltPayloadStates = opts.collectPayloadStates == true and {} or nil
    local prebuiltVisibleSignatures = opts.collectPayloadStates == true and {} or nil
    local now = GetProfileCheckpointSyncTime()
    for _, resolvedMemberKey in ipairs(normalizedMemberKeys) do
      local member = select(1, FindSessionMember(activeSession, resolvedMemberKey))
      if type(member) == "table" and IsSessionMemberVisibleForCurrentState(member) then
        local payloadState = BuildMemberBroadcastPayloadState(resolvedProfileName, resolvedSessionId, resolvedMemberKey, member)
        local sendDecision = GetTargetedMemberSnapshotSendDecision(
          resolvedSessionId,
          resolvedTargetMemberKey,
          resolvedMemberKey,
          payloadState,
          {
            onlyChangedForTarget = opts.onlyChangedForTarget == true,
            alwaysInclude = alwaysIncludeLookup[resolvedMemberKey] == true,
            now = now,
          }
        )
        if sendDecision.shouldSend then
          plannedMemberKeys[#plannedMemberKeys + 1] = resolvedMemberKey
          if type(prebuiltPayloadStates) == "table" then
            prebuiltPayloadStates[resolvedMemberKey] = payloadState
          end
          if type(prebuiltVisibleSignatures) == "table" then
            prebuiltVisibleSignatures[resolvedMemberKey] = sendDecision.signature
          end
        end
      end
    end
    return plannedMemberKeys, prebuiltPayloadStates, prebuiltVisibleSignatures
  end

  profileSyncMetaOps.sendJoinTargetedMemberBurst = function(activeSession, profileName, sessionId, memberKey, opts)
    opts = type(opts) == "table" and opts or {}
    activeSession = type(activeSession) == "table" and activeSession or nil
    local resolvedProfileName = TrimText(profileName)
    local resolvedSessionId = FirstNonEmptyText(sessionId, type(activeSession) == "table" and activeSession.id or "")
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    local resolvedHostKey = NormalizeCharacterKey(type(activeSession) == "table" and activeSession.host or "")
    if type(activeSession) ~= "table"
      or type(activeSession.members) ~= "table"
      or resolvedProfileName == ""
      or resolvedSessionId == ""
      or resolvedMemberKey == ""
    then
      return 0, {
        invalid = true,
      }
    end

    local burstStateKey = string.lower(resolvedSessionId) .. "|" .. string.lower(resolvedMemberKey)
    local burstNow = GetProfileCheckpointSyncTime()
    local targetMember = select(1, FindSessionMember(activeSession, resolvedMemberKey))
    local hostMember = select(1, FindSessionMember(activeSession, resolvedHostKey))
    local immediateMemberKeys, deferredMemberKeys = profileSyncMetaOps.buildJoinRosterDeliveryPlan(
      activeSession,
      resolvedMemberKey
    )
    INTERNAL_API.LIDCOUNCIL_StoreDeferredJoinMemberRows(
      activeSession,
      resolvedProfileName,
      resolvedMemberKey,
      deferredMemberKeys
    )
    -- The immediate burst contains only the host and the joiner. Remaining
    -- roster rows are kept in the deferred roster store above. Keying this
    -- dedupe to the whole roster made every later arrival invalidate all prior
    -- members' burst signatures, turning a raid join wave into repeated
    -- returning-member recovery and checksum work.
    local burstSignature = table.concat({
      BuildSessionVisibleMemberStateSignature(hostMember),
      BuildSessionVisibleMemberStateSignature(targetMember),
      resolvedHostKey ~= "" and "1" or "0",
    }, "\31")

    PruneAgedSessionRuntimeTracking(burstNow)
    local recentBurstState = sessionRuntime.recentDuplicateJoinRecoveryResends[burstStateKey]
    if type(recentBurstState) == "table" then
      local recentSentAt = math.max(0, tonumber(recentBurstState.sentAt) or 0)
      if recentSentAt <= 0
        or (burstNow - recentSentAt) >= sessionConfig.duplicateJoinRecoveryResendRetentionSeconds
      then
        sessionRuntime.recentDuplicateJoinRecoveryResends[burstStateKey] = nil
        recentBurstState = nil
      end
    end
    if type(recentBurstState) == "table"
      and TrimText(recentBurstState.signature) == burstSignature
      and (burstNow - math.max(0, tonumber(recentBurstState.sentAt) or 0))
        < sessionConfig.duplicateJoinRecoveryResendDedupeSeconds
    then
      if type(RecordProfileSyncDecision) == "function" then
        RecordProfileSyncDecision("send_join_targeted_member_burst", {
          action = "coalesced_existing_burst",
          sessionId = resolvedSessionId,
          profileName = resolvedProfileName,
          target = resolvedMemberKey,
          targetCount = 1,
          sentMemberRowCount = 0,
          deferredMemberRowCount = #deferredMemberKeys,
        })
      end
      return 0, {
        coalescedExistingBurst = true,
        burstSignature = burstSignature,
        refreshCoveredRow = recentBurstState.refreshCoveredRow == true,
        deferredMemberRowCount = #deferredMemberKeys,
      }
    end

    local _, _, hostRefreshDetail = RefreshHostSessionMemberState(resolvedProfileName, resolvedSessionId, {
      suppressCheckpoint = opts.suppressCheckpoint ~= false,
      channel = "WHISPER",
      target = resolvedMemberKey,
      onlyChangedForTarget = true,
    })
    local refreshCoveredRow = DidTargetedHostMemberRefreshCoverRow(hostRefreshDetail)
    local alwaysIncludeMemberKeys = immediateMemberKeys
    local candidateMemberKeys = immediateMemberKeys

    local plannedMemberKeys, plannedPayloadStates, plannedVisibleSignatures = BuildPriorityTargetedMemberSnapshotSendPlan(
      activeSession,
      resolvedProfileName,
      resolvedMemberKey,
      candidateMemberKeys,
      {
        onlyChangedForTarget = true,
        alwaysIncludeMemberKeys = alwaysIncludeMemberKeys,
        collectPayloadStates = true,
      }
    )
    local sentMemberRowCount = 0
    if #plannedMemberKeys > 0 then
      sentMemberRowCount = SendMemberSnapshot(activeSession, resolvedProfileName, resolvedMemberKey, {
        memberKeys = plannedMemberKeys,
        onlyChangedForTarget = true,
        alwaysIncludeMemberKeys = alwaysIncludeMemberKeys,
        prebuiltPayloadStates = plannedPayloadStates,
        prebuiltVisibleSignatures = plannedVisibleSignatures,
        skipSendDecision = true,
      })
    end

    local storedBurstSignature = table.concat({
      BuildSessionVisibleMemberStateSignature(select(1, FindSessionMember(activeSession, resolvedHostKey))),
      BuildSessionVisibleMemberStateSignature(select(1, FindSessionMember(activeSession, resolvedMemberKey))),
      resolvedHostKey ~= "" and "1" or "0",
    }, "\31")

    sessionRuntime.recentDuplicateJoinRecoveryResends[burstStateKey] = {
      signature = storedBurstSignature,
      sentAt = burstNow,
      refreshCoveredRow = refreshCoveredRow == true,
    }
    if type(RecordProfileSyncDecision) == "function" then
      RecordProfileSyncDecision("send_join_targeted_member_burst", {
        action = "sent",
        sessionId = resolvedSessionId,
        profileName = resolvedProfileName,
        target = resolvedMemberKey,
        targetCount = 1,
        sentMemberRowCount = sentMemberRowCount,
        hostRefreshCoveredRow = refreshCoveredRow == true,
        plannedMemberCount = #plannedMemberKeys,
        deferredMemberRowCount = #deferredMemberKeys,
      })
    end
    return sentMemberRowCount, {
      burstSignature = storedBurstSignature,
      hostRefreshDetail = hostRefreshDetail,
      refreshCoveredRow = refreshCoveredRow == true,
      plannedMemberCount = #plannedMemberKeys,
      deferredMemberRowCount = #deferredMemberKeys,
    }
  end

  local function BuildDeferredJoinMemberSnapshotSendPlan(activeSession, profileName, targetMemberKey, memberKeys, opts)
    opts = type(opts) == "table" and opts or {}
    activeSession = type(activeSession) == "table" and activeSession or nil
    local resolvedProfileName = TrimText(profileName)
    local resolvedTargetMemberKey = NormalizeCharacterKey(targetMemberKey)
    local resolvedSessionId = TrimText(type(activeSession) == "table" and activeSession.id or "")
    if type(activeSession) ~= "table"
      or type(activeSession.members) ~= "table"
      or resolvedProfileName == ""
      or resolvedSessionId == ""
      or resolvedTargetMemberKey == ""
    then
      return {}
    end

    local plannedEntries = {}
    local prebuiltPayloadStates = opts.collectPayloadStates == true and {} or nil
    local prebuiltVisibleSignatures = opts.collectPayloadStates == true and {} or nil
    local normalizedMemberKeys = NormalizeDeferredJoinMemberKeys(activeSession, resolvedTargetMemberKey, memberKeys, {
      requireMemberRows = true,
      requireVisibleRows = true,
    })
    local now = GetProfileCheckpointSyncTime()
    for _, resolvedMemberKey in ipairs(normalizedMemberKeys) do
      local member = select(1, FindSessionMember(activeSession, resolvedMemberKey))
      if type(member) == "table" and IsSessionMemberVisibleForCurrentState(member) then
        local payloadState = BuildMemberBroadcastPayloadState(resolvedProfileName, resolvedSessionId, resolvedMemberKey, member)
        local sendDecision = GetTargetedMemberSnapshotSendDecision(
          resolvedSessionId,
          resolvedTargetMemberKey,
          resolvedMemberKey,
          payloadState,
          {
            onlyChangedForTarget = true,
            now = now,
          }
        )
        if sendDecision.shouldSend then
          local statusPriority, eventAt = GetDeferredJoinSnapshotMemberPriority(member)
          plannedEntries[#plannedEntries + 1] = {
            memberKey = resolvedMemberKey,
            statusPriority = statusPriority,
            eventAt = eventAt,
          }
          if type(prebuiltPayloadStates) == "table" then
            prebuiltPayloadStates[resolvedMemberKey] = payloadState
          end
          if type(prebuiltVisibleSignatures) == "table" then
            prebuiltVisibleSignatures[resolvedMemberKey] = sendDecision.signature
          end
        end
      end
    end

    table.sort(plannedEntries, function(left, right)
      if left.statusPriority ~= right.statusPriority then
        return left.statusPriority < right.statusPriority
      end
      if left.eventAt ~= right.eventAt then
        return left.eventAt > right.eventAt
      end
      return string.lower(left.memberKey) < string.lower(right.memberKey)
    end)

    local orderedMemberKeys = {}
    for _, entry in ipairs(plannedEntries) do
      orderedMemberKeys[#orderedMemberKeys + 1] = entry.memberKey
    end
    return orderedMemberKeys, prebuiltPayloadStates, prebuiltVisibleSignatures
  end

  INTERNAL_API.LIDCOUNCIL_TryFlushDeferredJoinMemberRows = function(activeSession, profileName, memberKey, member, opts)
    opts = type(opts) == "table" and opts or {}
    activeSession = type(activeSession) == "table" and activeSession or nil
    member = type(member) == "table" and member or nil
    local resolvedProfileName = TrimText(profileName)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if type(activeSession) ~= "table"
      or resolvedProfileName == ""
      or resolvedMemberKey == ""
      or type(member) ~= "table"
    then
      return false
    end

    PruneStaleDeferredJoinMemberSnapshots(activeSession, GetProfileCheckpointSyncTime())
    local pendingDeferredSnapshots = select(1, profileSyncMetaOps.getDeferredJoinMemberSnapshotStore(activeSession, false))
    local pendingDeferredSnapshot = type(pendingDeferredSnapshots) == "table" and pendingDeferredSnapshots[resolvedMemberKey] or nil
    if type(pendingDeferredSnapshot) ~= "table" or type(pendingDeferredSnapshot.memberKeys) ~= "table" then
      return false
    end

    if INTERNAL_API.LIDCOUNCIL_GetDeferredJoinMemberBootstrapState(
      activeSession,
      resolvedProfileName,
      resolvedMemberKey,
      member,
      opts
    ) ~= "READY" then
      return false
    end

    local deferredMemberKeys, deferredPayloadStates, deferredVisibleSignatures = BuildDeferredJoinMemberSnapshotSendPlan(
      activeSession,
      FirstNonEmptyText(pendingDeferredSnapshot.profileName, resolvedProfileName),
      resolvedMemberKey,
      pendingDeferredSnapshot.memberKeys,
      {
        collectPayloadStates = true,
      }
    )
    if #deferredMemberKeys == 0 then
      INTERNAL_API.LIDCOUNCIL_ClearDeferredJoinMemberRows(activeSession, resolvedMemberKey)
      return true
    end

    SendMemberSnapshot(activeSession, FirstNonEmptyText(pendingDeferredSnapshot.profileName, resolvedProfileName), resolvedMemberKey, {
      memberKeys = deferredMemberKeys,
      onlyChangedForTarget = true,
      prebuiltPayloadStates = deferredPayloadStates,
      prebuiltVisibleSignatures = deferredVisibleSignatures,
      skipSendDecision = true,
    })
    INTERNAL_API.LIDCOUNCIL_ClearDeferredJoinMemberRows(activeSession, resolvedMemberKey)
    return true
  end

  INTERNAL_API.LIDCOUNCIL_HandleHostMemberPostUpdate = function(activeSession, profileName, sessionId, memberKey, existingMember, member, opts)
    opts = type(opts) == "table" and opts or {}
    activeSession = type(activeSession) == "table" and activeSession or nil
    existingMember = type(existingMember) == "table" and existingMember or nil
    member = type(member) == "table" and member or nil
    local resolvedProfileName = TrimText(profileName)
    local resolvedSessionId = TrimText(sessionId)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if type(activeSession) ~= "table" or resolvedProfileName == "" or resolvedMemberKey == "" then
      return {
        updatedMember = member or existingMember,
        visibleStateChanged = false,
        currentSectionChanged = false,
        refreshed = false,
      }
    end

    local updatedMember = member
      or (type(activeSession.members) == "table" and type(activeSession.members[resolvedMemberKey]) == "table" and activeSession.members[resolvedMemberKey] or nil)
      or existingMember
      or {}
    local skipCurrentDisplayStateDiff = opts.skipCurrentDisplayStateDiff == true and opts.defer ~= false
    local previousCurrentSessionDisplayContext = type(opts.currentSessionDisplayContext) == "table"
      and opts.currentSessionDisplayContext
      or nil
    local currentSessionDisplayContext = type(opts.updatedCurrentSessionDisplayContext) == "table"
      and opts.updatedCurrentSessionDisplayContext
      or (not skipCurrentDisplayStateDiff and INTERNAL_API.LIDCOUNCIL_BuildHostCurrentSessionDisplayContextFromBase(
          activeSession,
          resolvedProfileName,
          resolvedMemberKey,
          previousCurrentSessionDisplayContext,
          type(opts.syncCandidateSnapshot) == "table" and opts.syncCandidateSnapshot or nil
        ) or nil)
    local previousVisibleState = opts.previousVisibleState
    local updatedVisibleState = previousVisibleState ~= nil and BuildSessionVisibleMemberStateSignature(updatedMember) or nil
    local visibleStateChanged = previousVisibleState ~= nil and previousVisibleState ~= updatedVisibleState or false
    local previousCurrentSessionDisplay = opts.previousCurrentSessionDisplay
    local currentDisplayState = previousCurrentSessionDisplay ~= nil
      and not skipCurrentDisplayStateDiff
      and INTERNAL_API.LIDCOUNCIL_BuildHostCurrentSessionMemberDisplayState(
        activeSession,
        resolvedProfileName,
        resolvedMemberKey,
        updatedMember,
        currentSessionDisplayContext
      )
      or nil
    local currentSectionChanged = previousCurrentSessionDisplay ~= nil
      and previousCurrentSessionDisplay ~= currentDisplayState
      or false
    if skipCurrentDisplayStateDiff and opts.forceCurrentSectionRefreshWhenCoalesced == true then
      currentSectionChanged = true
    end

    if opts.flushDeferredJoinRows == true and type(updatedMember) == "table" then
      INTERNAL_API.LIDCOUNCIL_TryFlushDeferredJoinMemberRows(
        activeSession,
        resolvedProfileName,
        resolvedMemberKey,
        updatedMember,
        opts.passDisplayStateToDeferredFlush == true and (
          currentDisplayState ~= nil and { displayState = currentDisplayState }
          or (type(opts.deferredJoinFlushOpts) == "table" and opts.deferredJoinFlushOpts or nil)
        ) or nil
      )
    end
    if (visibleStateChanged or currentSectionChanged or opts.broadcastVisibleStateAlways == true)
      and opts.broadcastVisibleStateChange == true
      and resolvedSessionId ~= ""
    then
      BroadcastMember(
        resolvedProfileName,
        resolvedSessionId,
        resolvedMemberKey,
        updatedMember,
        nil,
        nil,
        {
          forceImmediate = opts.broadcastVisibleStateForceImmediate == true,
          suppressCheckpoint = opts.broadcastVisibleStateSuppressCheckpoint == true,
        }
      )
    end
    if (opts.prewarmWhen == true or (visibleStateChanged and opts.prewarmOnVisibleStateChange == true))
      and resolvedSessionId ~= ""
    then
      if type(profileSyncMetaOps.queueMemberBackgroundSyncBurst) == "function" then
        profileSyncMetaOps.queueMemberBackgroundSyncBurst(activeSession, resolvedProfileName, resolvedSessionId, resolvedMemberKey, {
          queuePrewarm = true,
          prewarmReason = FirstNonEmptyText(opts.prewarmReason, "profile_state"),
          prewarmForce = opts.prewarmForce == true,
          prewarmDomains = CloneCheckpointDomainList(type(opts.prewarmDomains) == "table" and opts.prewarmDomains or nil),
          prewarmSubdomains = CloneCheckpointSubdomainList(type(opts.prewarmSubdomains) == "table" and opts.prewarmSubdomains or nil),
        })
      else
        PrewarmMemberPreciseLiveSyncState(activeSession, resolvedProfileName, resolvedSessionId, resolvedMemberKey, {
          mode = "BACKGROUND",
          reason = FirstNonEmptyText(opts.prewarmReason, "profile_state"),
          force = opts.prewarmForce == true,
          domains = CloneCheckpointDomainList(type(opts.prewarmDomains) == "table" and opts.prewarmDomains or nil),
          subdomains = CloneCheckpointSubdomainList(type(opts.prewarmSubdomains) == "table" and opts.prewarmSubdomains or nil),
        })
      end
    end
    if opts.queueComparisonWhen == true or (visibleStateChanged and opts.queueComparisonOnVisibleStateChange == true) then
      QueueAutoDetailedComparison(resolvedMemberKey, FirstNonEmptyText(opts.queueComparisonReason, "profile_state"))
    end
    if opts.queuePostBootstrapRevalidation == true and resolvedSessionId ~= "" then
      QueuePostBootstrapLiveRevalidation(resolvedProfileName, resolvedSessionId, resolvedMemberKey)
    end
    if opts.skipRefreshWhenUnchanged == true
      and not visibleStateChanged
      and not currentSectionChanged
      and opts.retainRefreshWhenUnchanged ~= true
    then
      local syncManagementRefreshed = false
      if opts.refreshSyncManagementWhenUnchanged == true then
        syncManagementRefreshed = sessionUiOps.refreshSyncManagementSection(opts) == true
      end
      return {
        updatedMember = updatedMember,
        updatedVisibleState = updatedVisibleState,
        currentDisplayState = currentDisplayState,
        visibleStateChanged = visibleStateChanged,
        currentSectionChanged = currentSectionChanged,
        syncManagementRefreshed = syncManagementRefreshed,
        refreshed = syncManagementRefreshed,
      }
    end
    sessionUiOps.refreshCurrentAndSyncSections(currentSectionChanged, opts)
    return {
      updatedMember = updatedMember,
      updatedVisibleState = updatedVisibleState,
      currentDisplayState = currentDisplayState,
      visibleStateChanged = visibleStateChanged,
      currentSectionChanged = currentSectionChanged,
      refreshed = opts.refreshEditor ~= false,
    }
  end

  INTERNAL_API.LIDCOUNCIL_GetSessionMemberRosterRefreshPolicy_Impl = function(existingMember, updatedMember)
    local wasJoined = type(existingMember) == "table"
      and string.upper(TrimText(existingMember.status or "JOINED")) == "JOINED"
    local isJoined = type(updatedMember) == "table"
      and string.upper(TrimText(updatedMember.status or "JOINED")) == "JOINED"
    local rosterMembershipChanged = wasJoined ~= isJoined
    local defer
    if rosterMembershipChanged then
      defer = false
    end
    return {
      rosterMembershipChanged = rosterMembershipChanged,
      forceCurrentSectionRefresh = rosterMembershipChanged,
      forceImmediate = rosterMembershipChanged,
      defer = defer,
    }
  end

  INTERNAL_API.LIDCOUNCIL_HandleSessionMemberVisibleStateUpdate = function(activeSession, memberKey, existingMember, member, opts)
    opts = type(opts) == "table" and opts or {}
    activeSession = type(activeSession) == "table" and activeSession or nil
    existingMember = type(existingMember) == "table" and existingMember or nil
    member = type(member) == "table" and member or nil
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    local updatedMember = member
      or (
        type(activeSession) == "table"
        and type(activeSession.members) == "table"
        and resolvedMemberKey ~= ""
        and type(activeSession.members[resolvedMemberKey]) == "table"
        and activeSession.members[resolvedMemberKey]
        or nil
      )
      or existingMember
      or {}
    local skipVisibleStateDiff = opts.skipVisibleStateDiff == true and opts.defer ~= false
    local previousVisibleState = opts.previousVisibleState
    if previousVisibleState == nil and not skipVisibleStateDiff then
      previousVisibleState = BuildSessionVisibleMemberStateSignature(existingMember)
    end
    local updatedVisibleState = not skipVisibleStateDiff and BuildSessionVisibleMemberStateSignature(updatedMember) or nil
    local currentSectionChanged = not skipVisibleStateDiff and previousVisibleState ~= updatedVisibleState or false
    local currentSectionRefreshForced = currentSectionChanged ~= true and (
      opts.forceCurrentSectionRefreshWhenUnchanged == true
      or (skipVisibleStateDiff and opts.forceCurrentSectionRefreshWhenCoalesced == true)
    )
    local rosterRefreshPolicy = INTERNAL_API.LIDCOUNCIL_GetSessionMemberRosterRefreshPolicy_Impl(existingMember, updatedMember)
    local rosterMembershipChanged = rosterRefreshPolicy.rosterMembershipChanged == true
    if rosterRefreshPolicy.forceCurrentSectionRefresh == true then
      currentSectionRefreshForced = true
    end
    local refreshOpts = opts
    if rosterRefreshPolicy.forceImmediate == true then
      -- A join or leave changes the actionable roster. Repaint it immediately;
      -- routine MEMBER metadata remains coalesced to avoid editor refresh churn.
      refreshOpts = {}
      for optionKey, optionValue in pairs(opts) do
        refreshOpts[optionKey] = optionValue
      end
      refreshOpts.defer = rosterRefreshPolicy.defer
      refreshOpts.forceImmediate = true
    end
    if rosterMembershipChanged then
      sessionUiOps.refreshCurrentSyncAndLootListAfterRosterChange(refreshOpts)
    else
      sessionUiOps.refreshCurrentAndSyncSections(
        currentSectionChanged or currentSectionRefreshForced,
        refreshOpts
      )
    end
    return {
      updatedMember = updatedMember,
      updatedVisibleState = updatedVisibleState,
      currentSectionChanged = currentSectionChanged,
      currentSectionRefreshForced = currentSectionRefreshForced,
      refreshed = refreshOpts.refreshEditor ~= false,
      rosterMembershipChanged = rosterMembershipChanged,
    }
  end

  local function SendJoinAck(activeSession, profileName, memberKey)
    if type(activeSession) ~= "table" then
      return false, "No active session."
    end
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if resolvedMemberKey == "" then
      return false, "Join ACK target is missing."
    end
    local hostAutoPassEnabled = false
    if type(deps.GetLocalAutoPassEnabled) == "function" then
      hostAutoPassEnabled = deps.GetLocalAutoPassEnabled() and true or false
    else
      local hostMember = FindSessionMember(activeSession, activeSession.host or "")
      hostAutoPassEnabled = type(hostMember) == "table"
        and deps.NormalizeEnabledFlag(hostMember.localAutoPassEnabled, false)
        or false
    end
    return SendComm(
      "JACK",
      "WHISPER",
      resolvedMemberKey,
      activeSession.id,
      profileName,
      TrimText(select(1, deps.GetLootProfileId(profileName)) or ""),
      activeSession.host,
      deps.GetLootProfileMaster(profileName),
      tostring(activeSession.startedAt or (time and time() or 0)),
      activeSession.status or "PREPARING",
      tostring(activeSession.activatedAt or ""),
      GetCommProtocolMarker(),
      resolvedMemberKey,
      hostAutoPassEnabled and "1" or "0"
    )
  end

  QueueProfileSnapshotForMember = function(profileName, sessionId, memberKey, opts)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if resolvedMemberKey == "" then
      return false, "Profile snapshot target is missing."
    end
    opts = type(opts) == "table" and opts or {}
    if type(opts.preparedSnapshot) == "table" then
      if type(deps.SendPreparedProfileSnapshotBatch) == "function" then
        return deps.SendPreparedProfileSnapshotBatch(opts.preparedSnapshot, sessionId, { resolvedMemberKey }, opts)
      end
      if type(deps.SendPreparedProfileSnapshot) == "function" then
        return deps.SendPreparedProfileSnapshot(opts.preparedSnapshot, sessionId, resolvedMemberKey, opts)
      end
    end
    if type(deps.SendProfileSnapshotBatch) == "function" then
      return deps.SendProfileSnapshotBatch(profileName, sessionId, { resolvedMemberKey }, opts)
    end
    return deps.SendProfileSnapshot(profileName, sessionId, resolvedMemberKey, opts)
  end

  QueuePreparedRepairTransfersForMember = function(profileName, sessionId, memberKey, opts)
    opts = type(opts) == "table" and opts or {}
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    local mode = TrimText(opts.mode) ~= "" and TrimText(opts.mode) or "LIVE"
    local reason = TrimText(opts.reason) ~= "" and TrimText(opts.reason) or "repair"
    local authoritativeArchiveScope = string.upper(TrimText(opts.authoritativeArchiveScope))
    if authoritativeArchiveScope ~= "LOOT_LIST"
      and authoritativeArchiveScope ~= "SESSION_HISTORY"
      and authoritativeArchiveScope ~= "FUN_AWARDS"
    then
      authoritativeArchiveScope = ""
    end
    local requestedDomains = CloneCheckpointDomainList(opts.domains)
    local requestedSubdomains = CloneCheckpointSubdomainList(opts.subdomains)
    local resolvedDomains, resolvedSubdomains, scopeDetail = profileSyncMetaOps.resolveHostRepairScopeForMember(
      resolvedMemberKey,
      requestedDomains,
      requestedSubdomains,
      opts
    )
    local preparedTransfers = nil
    local prepareError = nil
    local prepareDetail = {
      patchTransfers = 0,
      patchSubdomains = 0,
      snapshotTransfers = 0,
      snapshotSubdomains = 0,
      queueMergeCount = 0,
      queueExactDuplicateCount = 0,
      duplicatePreparedTransfers = 0,
      dedupedTransferCount = 0,
      deferredPatchState = false,
      requestedScope = #resolvedSubdomains > 0 and "precise" or (#resolvedDomains > 0 and "targeted" or "full"),
      scopeEscalated = false,
      fullSnapshotFallback = false,
      scopeEscalationKinds = {},
      requestedDomains = CloneCheckpointDomainList(requestedDomains),
      requestedSubdomains = CloneCheckpointSubdomainList(requestedSubdomains),
      effectiveDomains = CloneCheckpointDomainList(resolvedDomains),
      effectiveSubdomains = CloneCheckpointSubdomainList(resolvedSubdomains),
      prunedDomains = CloneCheckpointDomainList(type(scopeDetail) == "table" and scopeDetail.prunedDomains or {}),
      prunedSubdomains = CloneCheckpointSubdomainList(type(scopeDetail) == "table" and scopeDetail.prunedSubdomains or {}),
      scopeTightened = type(scopeDetail) == "table" and scopeDetail.scopeTightened == true or false,
      skippedNoOp = type(scopeDetail) == "table" and scopeDetail.skippedNoOp == true or false,
      skipReason = TrimText(type(scopeDetail) == "table" and scopeDetail.skipReason or ""),
    }

    if prepareDetail.skippedNoOp and authoritativeArchiveScope == "" then
      if type(RecordProfileSyncDecision) == "function" then
        RecordProfileSyncDecision("queue_prepared_repair", {
          action = "skipped_noop",
          sessionId = TrimText(sessionId),
          profileName = TrimText(profileName),
          mode = mode,
          reason = reason,
          target = resolvedMemberKey,
          targetCount = resolvedMemberKey ~= "" and 1 or 0,
          queuedCount = 0,
          requestedDomains = CloneCheckpointDomainList(requestedDomains),
          requestedSubdomains = CloneCheckpointSubdomainList(requestedSubdomains),
          effectiveDomains = CloneCheckpointDomainList(resolvedDomains),
          effectiveSubdomains = CloneCheckpointSubdomainList(resolvedSubdomains),
          prunedDomains = CloneCheckpointDomainList(prepareDetail.prunedDomains),
          prunedSubdomains = CloneCheckpointSubdomainList(prepareDetail.prunedSubdomains),
          fallbackReason = prepareDetail.skipReason,
          fallbackReasons = prepareDetail.skipReason ~= "" and { prepareDetail.skipReason } or {},
        })
      end
      return true, 0, nil, prepareDetail
    end

    if authoritativeArchiveScope ~= "" then
      local preparedSnapshot
      preparedSnapshot, prepareError = PrepareProfileSnapshotTransfer(profileName, {
        domains = #resolvedDomains > 0 and resolvedDomains or nil,
        subdomains = #resolvedSubdomains > 0 and resolvedSubdomains or nil,
        mode = mode,
        reason = reason,
        sessionId = TrimText(sessionId),
        authoritativeArchiveScope = authoritativeArchiveScope,
      })
      if type(preparedSnapshot) == "table" then
        preparedTransfers = { preparedSnapshot }
        prepareDetail.snapshotTransfers = 1
        prepareDetail.snapshotSubdomains = #(
          type(preparedSnapshot.subdomains) == "table" and preparedSnapshot.subdomains or {}
        )
        prepareDetail.effectiveDomains = CloneCheckpointDomainList(preparedSnapshot.domains)
        prepareDetail.effectiveSubdomains = CloneCheckpointSubdomainList(preparedSnapshot.subdomains)
        prepareDetail.requestedScope = "authoritative_archive"
      end
    elseif type(BuildPreparedProfileRepairTransfers) == "function" and #resolvedSubdomains > 0 then
      preparedTransfers, prepareError, prepareDetail = BuildPreparedProfileRepairTransfers(profileName, sessionId, memberKey, {
        domains = #resolvedDomains > 0 and resolvedDomains or nil,
        subdomains = #resolvedSubdomains > 0 and resolvedSubdomains or nil,
      })
      if type(prepareDetail) == "table" then
        prepareDetail.requestedDomains = CloneCheckpointDomainList(requestedDomains)
        prepareDetail.requestedSubdomains = CloneCheckpointSubdomainList(requestedSubdomains)
        prepareDetail.effectiveDomains = CloneCheckpointDomainList(resolvedDomains)
        prepareDetail.effectiveSubdomains = CloneCheckpointSubdomainList(resolvedSubdomains)
        prepareDetail.prunedDomains = CloneCheckpointDomainList(type(scopeDetail) == "table" and scopeDetail.prunedDomains or {})
        prepareDetail.prunedSubdomains = CloneCheckpointSubdomainList(type(scopeDetail) == "table" and scopeDetail.prunedSubdomains or {})
        prepareDetail.scopeTightened = type(scopeDetail) == "table" and scopeDetail.scopeTightened == true or false
      end
    else
      local preparedSnapshot
      preparedSnapshot, prepareError = PrepareProfileSnapshotTransfer(profileName, {
        domains = #resolvedDomains > 0 and resolvedDomains or nil,
        subdomains = #resolvedSubdomains > 0 and resolvedSubdomains or nil,
        mode = mode,
        reason = reason,
        sessionId = TrimText(sessionId),
      })
      if type(preparedSnapshot) == "table" then
        preparedTransfers = { preparedSnapshot }
        prepareDetail.snapshotTransfers = 1
        prepareDetail.requestedScope = TrimText(preparedSnapshot.requestedScope) ~= ""
          and TrimText(preparedSnapshot.requestedScope)
          or prepareDetail.requestedScope
        prepareDetail.scopeEscalated = preparedSnapshot.scopeEscalated == true
        prepareDetail.fullSnapshotFallback = preparedSnapshot.fullSnapshotFallback == true
        if TrimText(preparedSnapshot.fallbackEscalation) ~= "" then
          prepareDetail.scopeEscalationKinds = { TrimText(preparedSnapshot.fallbackEscalation) }
        end
        prepareDetail.fallbackReasons = MergeDecisionTextLists(
          prepareDetail.fallbackReasons,
          CloneDecisionTextList(type(preparedSnapshot) == "table" and preparedSnapshot.fallbackReasons or {})
        )
        if #resolvedSubdomains > 0 then
          prepareDetail.snapshotSubdomains = #resolvedSubdomains
        elseif #resolvedDomains > 0 then
          prepareDetail.snapshotSubdomains = 0
        end
      end
    end

    local patchStateFallbackSubdomains = CloneCheckpointSubdomainList(
      type(prepareDetail) == "table" and prepareDetail.patchStateFallbackSubdomains or {}
    )
    local snapshotFallbackSubdomains = CloneCheckpointSubdomainList(
      type(prepareDetail) == "table" and prepareDetail.snapshotFallbackSubdomains or {}
    )
    local shouldRetryForPatchState = opts.allowPatchStateRetry ~= false
      and profileSyncMetaOps.shouldRetryPreparedRepairForPatchState({
        patchStateFallbackSubdomains = patchStateFallbackSubdomains,
        snapshotFallbackSubdomains = snapshotFallbackSubdomains,
        fallbackReasons = type(prepareDetail) == "table" and prepareDetail.fallbackReasons or {},
      })

    if shouldRetryForPatchState then
      local retryProfileName = TrimText(profileName)
      local retrySessionId = TrimText(sessionId)
      local retryReason = reason .. "_patchstate_retry"
      local retrySkipScopePrune = opts.skipScopePrune == true
      local pendingPatchStateRetry = type(profileSyncMetaOps.getPendingPatchStateRetry) == "function"
        and profileSyncMetaOps.getPendingPatchStateRetry(retrySessionId, resolvedMemberKey)
        or nil
      local pendingPatchStateSubdomains = CloneCheckpointSubdomainList(
        type(pendingPatchStateRetry) == "table" and pendingPatchStateRetry.subdomains or {}
      )
      local pendingPatchStateLookup = {}
      for _, subdomain in ipairs(pendingPatchStateSubdomains) do
        local resolvedSubdomain = string.lower(TrimText(subdomain))
        if resolvedSubdomain ~= "" then
          pendingPatchStateLookup[resolvedSubdomain] = true
        end
      end
      local newPatchStateRetrySubdomains = {}
      for _, subdomain in ipairs(patchStateFallbackSubdomains) do
        local resolvedSubdomain = TrimText(subdomain)
        local resolvedKey = string.lower(resolvedSubdomain)
        if resolvedSubdomain ~= "" and not pendingPatchStateLookup[resolvedKey] then
          pendingPatchStateLookup[resolvedKey] = true
          newPatchStateRetrySubdomains[#newPatchStateRetrySubdomains + 1] = resolvedSubdomain
        end
      end
      local mergedPatchStateRetrySubdomains = MergeCheckpointSubdomainLists(
        pendingPatchStateSubdomains,
        patchStateFallbackSubdomains
      )
      local coalescePendingPatchStateRetry = type(pendingPatchStateRetry) == "table"
        and #newPatchStateRetrySubdomains == 0
      local extendPendingPatchStateRetry = type(pendingPatchStateRetry) == "table"
        and #newPatchStateRetrySubdomains > 0

      if coalescePendingPatchStateRetry then
        pendingPatchStateRetry.profileName = retryProfileName
        pendingPatchStateRetry.mode = mode
        pendingPatchStateRetry.reason = retryReason
        pendingPatchStateRetry.skipScopePrune = retrySkipScopePrune
        pendingPatchStateRetry.subdomains = CloneCheckpointSubdomainList(mergedPatchStateRetrySubdomains)
        profileSyncMetaOps.upsertPendingPatchStateRetry(retrySessionId, resolvedMemberKey, pendingPatchStateRetry)
      else
        local requestedPatchManifestSubdomains = extendPendingPatchStateRetry
          and CloneCheckpointSubdomainList(newPatchStateRetrySubdomains)
          or CloneCheckpointSubdomainList(patchStateFallbackSubdomains)
        if type(deps.SendProfilePatchManifestRequests) == "function" then
          deps.SendProfilePatchManifestRequests(resolvedMemberKey, requestedPatchManifestSubdomains, {
            force = true,
            auto = true,
          })
        end

        local token = string.format("PMR-%d-%d", tonumber(time and time() or 0) or 0, math.random(1000, 9999))
        profileSyncMetaOps.upsertPendingPatchStateRetry(retrySessionId, resolvedMemberKey, {
          token = token,
          profileName = retryProfileName,
          mode = mode,
          reason = retryReason,
          skipScopePrune = retrySkipScopePrune,
          subdomains = mergedPatchStateRetrySubdomains,
        })

        local function RunDeferredPatchStateRetry()
          local currentPending = type(profileSyncMetaOps.getPendingPatchStateRetry) == "function"
            and profileSyncMetaOps.getPendingPatchStateRetry(retrySessionId, resolvedMemberKey)
            or nil
          local currentToken = type(currentPending) == "table" and TrimText(currentPending.token) or nil
          if currentToken ~= token then
            return
          end
          profileSyncMetaOps.clearPendingPatchStateRetry(retrySessionId, resolvedMemberKey)

          local currentRetryProfileName = TrimText(type(currentPending) == "table" and currentPending.profileName or retryProfileName)
          local currentRetryMode = TrimText(type(currentPending) == "table" and currentPending.mode or "") ~= ""
            and TrimText(currentPending.mode)
            or mode
          local currentRetryReason = TrimText(type(currentPending) == "table" and currentPending.reason or "") ~= ""
            and TrimText(currentPending.reason)
            or retryReason
          local currentRetrySubdomains = CloneCheckpointSubdomainList(
            type(currentPending) == "table" and currentPending.subdomains or patchStateFallbackSubdomains
          )
          local currentRetryDomains = {}

          local activeSession, activeProfileName = GetActiveLootSession()
          local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
          if not activeSession
            or not DoesActiveSessionMatch(activeSession, activeProfileName, retrySessionId, currentRetryProfileName)
            or not AreCharacterKeysSame(activeSession.host or "", selfKey)
            or not IsJoinedSessionCharacter(activeSession, resolvedMemberKey)
          then
            return
          end

          if type(profileSyncMetaOps.resolveHostRepairScopeForMember) == "function" then
            local effectiveRetryDomains, effectiveRetrySubdomains = profileSyncMetaOps.resolveHostRepairScopeForMember(
              resolvedMemberKey,
              currentRetryDomains,
              currentRetrySubdomains,
              {}
            )
            currentRetryDomains = CloneCheckpointDomainList(effectiveRetryDomains)
            currentRetrySubdomains = CloneCheckpointSubdomainList(effectiveRetrySubdomains)
          end
          if #currentRetryDomains == 0 and #currentRetrySubdomains == 0 then
            return
          end

          QueueLiveFirstRepairTransfersForMember(activeSession, currentRetryProfileName, retrySessionId, resolvedMemberKey, {
            mode = currentRetryMode,
            reason = currentRetryReason,
            domains = currentRetryDomains,
            subdomains = currentRetrySubdomains,
            skipScopePrune = true,
            allowPatchStateRetry = false,
          })
        end

        if type(Compat) == "table" and type(Compat.After) == "function" then
          Compat.After(0.25, RunDeferredPatchStateRetry)
        else
          RunDeferredPatchStateRetry()
        end
      end

      if type(prepareDetail) == "table" then
        prepareDetail.deferredPatchState = true
        prepareDetail.deferredPatchStateCoalesced = coalescePendingPatchStateRetry == true
        prepareDetail.deferredPatchStateExtended = extendPendingPatchStateRetry == true
        prepareDetail.snapshotTransfers = 0
        prepareDetail.snapshotSubdomains = 0
      end

      local immediateTransfers = {}
      for _, preparedTransfer in ipairs(type(preparedTransfers) == "table" and preparedTransfers or {}) do
        local transferKind = string.upper(TrimText(type(preparedTransfer) == "table" and preparedTransfer.transferKind or ""))
        if transferKind ~= "SUBDOMAINS" then
          immediateTransfers[#immediateTransfers + 1] = preparedTransfer
        end
      end
      preparedTransfers = immediateTransfers

      if #preparedTransfers == 0 then
        if type(RecordProfileSyncDecision) == "function" then
          RecordProfileSyncDecision("queue_prepared_repair", {
            action = "deferred_patch_state",
            sessionId = TrimText(sessionId),
            profileName = TrimText(profileName),
            mode = mode,
            reason = reason,
            target = resolvedMemberKey,
            targetCount = resolvedMemberKey ~= "" and 1 or 0,
            queuedCount = 0,
            requestedDomains = CloneCheckpointDomainList(requestedDomains),
            requestedSubdomains = CloneCheckpointSubdomainList(requestedSubdomains),
            effectiveDomains = CloneCheckpointDomainList(resolvedDomains),
            effectiveSubdomains = CloneCheckpointSubdomainList(resolvedSubdomains),
            prunedDomains = CloneCheckpointDomainList(type(scopeDetail) == "table" and scopeDetail.prunedDomains or {}),
            prunedSubdomains = CloneCheckpointSubdomainList(type(scopeDetail) == "table" and scopeDetail.prunedSubdomains or {}),
            patchSubdomains = CloneCheckpointSubdomainList(type(prepareDetail) == "table" and prepareDetail.patchTransferSubdomains or {}),
            snapshotFallbackSubdomains = CloneCheckpointSubdomainList(snapshotFallbackSubdomains),
            fallbackReason = type(prepareDetail) == "table" and type(prepareDetail.fallbackReasons) == "table" and prepareDetail.fallbackReasons[1] or "",
            fallbackReasons = CloneDecisionTextList(type(prepareDetail) == "table" and prepareDetail.fallbackReasons or {}),
          })
        end
        return true, 0, nil, prepareDetail
      end
    end

    local duplicatePreparedTransfers = 0
    preparedTransfers, duplicatePreparedTransfers, prepareDetail = profileSyncMetaOps.dedupePreparedRepairTransfers(preparedTransfers, prepareDetail)
    if duplicatePreparedTransfers > 0 and type(RecordProfileSyncDecision) == "function" then
      RecordProfileSyncDecision("queue_prepared_repair", {
        action = "deduped_prepared_transfers",
        sessionId = TrimText(sessionId),
        profileName = TrimText(profileName),
        mode = mode,
        reason = reason,
        target = resolvedMemberKey,
        targetCount = resolvedMemberKey ~= "" and 1 or 0,
        queuedCount = 0,
        transferCount = #preparedTransfers,
        duplicatePreparedTransfers = duplicatePreparedTransfers,
        transferKinds = profileSyncMetaOps.buildPreparedTransferKindList(preparedTransfers),
        requestedDomains = CloneCheckpointDomainList(requestedDomains),
        requestedSubdomains = CloneCheckpointSubdomainList(requestedSubdomains),
        effectiveDomains = CloneCheckpointDomainList(resolvedDomains),
        effectiveSubdomains = CloneCheckpointSubdomainList(resolvedSubdomains),
        prunedDomains = CloneCheckpointDomainList(type(scopeDetail) == "table" and scopeDetail.prunedDomains or {}),
        prunedSubdomains = CloneCheckpointSubdomainList(type(scopeDetail) == "table" and scopeDetail.prunedSubdomains or {}),
      })
    end

    if type(preparedTransfers) ~= "table" or #preparedTransfers == 0 then
      if type(RecordProfileSyncDecision) == "function" then
        RecordProfileSyncDecision("queue_prepared_repair", {
          action = "failed",
          sessionId = TrimText(sessionId),
          profileName = TrimText(profileName),
          mode = mode,
          reason = reason,
          target = resolvedMemberKey,
          targetCount = resolvedMemberKey ~= "" and 1 or 0,
          duplicatePreparedTransfers = math.max(0, tonumber(type(prepareDetail) == "table" and prepareDetail.duplicatePreparedTransfers or 0) or 0),
          requestedDomains = CloneCheckpointDomainList(requestedDomains),
          requestedSubdomains = CloneCheckpointSubdomainList(requestedSubdomains),
          effectiveDomains = CloneCheckpointDomainList(resolvedDomains),
          effectiveSubdomains = CloneCheckpointSubdomainList(resolvedSubdomains),
          prunedDomains = CloneCheckpointDomainList(type(scopeDetail) == "table" and scopeDetail.prunedDomains or {}),
          prunedSubdomains = CloneCheckpointSubdomainList(type(scopeDetail) == "table" and scopeDetail.prunedSubdomains or {}),
          patchSubdomains = CloneCheckpointSubdomainList(type(prepareDetail) == "table" and prepareDetail.patchTransferSubdomains or {}),
          snapshotFallbackSubdomains = CloneCheckpointSubdomainList(type(prepareDetail) == "table" and prepareDetail.snapshotFallbackSubdomains or {}),
          transferKinds = CloneDecisionTextList(type(prepareDetail) == "table" and prepareDetail.transferKinds or {}),
          fallbackReason = type(prepareDetail) == "table" and type(prepareDetail.fallbackReasons) == "table" and prepareDetail.fallbackReasons[1] or "",
          fallbackReasons = CloneDecisionTextList(type(prepareDetail) == "table" and prepareDetail.fallbackReasons or {}),
          error = prepareError,
        })
      end
      return false, 0, prepareError, prepareDetail
    end

    local queuedAny = false
    local totalQueuedCount = 0
    local lastQueueError = nil
    for _, preparedTransfer in ipairs(preparedTransfers) do
      local ok, queuedCountOrError, queueBatchDetail = QueueProfileSnapshotForMember(profileName, sessionId, memberKey, {
        mode = mode,
        reason = reason,
        domains = #resolvedDomains > 0 and resolvedDomains or nil,
        subdomains = #resolvedSubdomains > 0 and resolvedSubdomains or nil,
        preparedSnapshot = preparedTransfer,
      })
      if ok then
        queuedAny = true
        totalQueuedCount = totalQueuedCount + math.max(1, tonumber(queuedCountOrError) or 1)
        profileSyncMetaOps.applyOutboundQueueStatsToRepairDetail(prepareDetail, queueBatchDetail)
      else
        lastQueueError = queuedCountOrError
      end
    end

    if not queuedAny then
      if type(RecordProfileSyncDecision) == "function" then
        RecordProfileSyncDecision("queue_prepared_repair", {
          action = "failed",
          sessionId = TrimText(sessionId),
          profileName = TrimText(profileName),
          mode = mode,
          reason = reason,
          target = resolvedMemberKey,
          targetCount = resolvedMemberKey ~= "" and 1 or 0,
          queuedCount = 0,
          transferCount = #preparedTransfers,
          duplicatePreparedTransfers = math.max(0, tonumber(type(prepareDetail) == "table" and prepareDetail.duplicatePreparedTransfers or 0) or 0),
          transferKinds = profileSyncMetaOps.buildPreparedTransferKindList(preparedTransfers),
          requestedDomains = CloneCheckpointDomainList(requestedDomains),
          requestedSubdomains = CloneCheckpointSubdomainList(requestedSubdomains),
          effectiveDomains = CloneCheckpointDomainList(resolvedDomains),
          effectiveSubdomains = CloneCheckpointSubdomainList(resolvedSubdomains),
          prunedDomains = CloneCheckpointDomainList(type(scopeDetail) == "table" and scopeDetail.prunedDomains or {}),
          prunedSubdomains = CloneCheckpointSubdomainList(type(scopeDetail) == "table" and scopeDetail.prunedSubdomains or {}),
          patchSubdomains = CloneCheckpointSubdomainList(type(prepareDetail) == "table" and prepareDetail.patchTransferSubdomains or {}),
          snapshotFallbackSubdomains = CloneCheckpointSubdomainList(type(prepareDetail) == "table" and prepareDetail.snapshotFallbackSubdomains or {}),
          fallbackReason = type(prepareDetail) == "table" and type(prepareDetail.fallbackReasons) == "table" and prepareDetail.fallbackReasons[1] or "",
          fallbackReasons = CloneDecisionTextList(type(prepareDetail) == "table" and prepareDetail.fallbackReasons or {}),
          error = lastQueueError or prepareError,
        })
      end
      return false, 0, lastQueueError or prepareError, prepareDetail
    end
    if type(RecordProfileSyncDecision) == "function" then
      RecordProfileSyncDecision("queue_prepared_repair", {
        action = "queued",
        sessionId = TrimText(sessionId),
        profileName = TrimText(profileName),
        mode = mode,
        reason = reason,
        target = resolvedMemberKey,
        targetCount = resolvedMemberKey ~= "" and 1 or 0,
        queuedCount = totalQueuedCount,
        transferCount = #preparedTransfers,
        duplicatePreparedTransfers = math.max(0, tonumber(type(prepareDetail) == "table" and prepareDetail.duplicatePreparedTransfers or 0) or 0),
        transferKinds = profileSyncMetaOps.buildPreparedTransferKindList(preparedTransfers),
        requestedDomains = CloneCheckpointDomainList(requestedDomains),
        requestedSubdomains = CloneCheckpointSubdomainList(requestedSubdomains),
        effectiveDomains = CloneCheckpointDomainList(resolvedDomains),
        effectiveSubdomains = CloneCheckpointSubdomainList(resolvedSubdomains),
        prunedDomains = CloneCheckpointDomainList(type(scopeDetail) == "table" and scopeDetail.prunedDomains or {}),
        prunedSubdomains = CloneCheckpointSubdomainList(type(scopeDetail) == "table" and scopeDetail.prunedSubdomains or {}),
        patchSubdomains = CloneCheckpointSubdomainList(type(prepareDetail) == "table" and prepareDetail.patchTransferSubdomains or {}),
        snapshotFallbackSubdomains = CloneCheckpointSubdomainList(type(prepareDetail) == "table" and prepareDetail.snapshotFallbackSubdomains or {}),
        fallbackReason = type(prepareDetail) == "table" and type(prepareDetail.fallbackReasons) == "table" and prepareDetail.fallbackReasons[1] or "",
        fallbackReasons = CloneDecisionTextList(type(prepareDetail) == "table" and prepareDetail.fallbackReasons or {}),
      })
    end
    return true, totalQueuedCount, nil, prepareDetail
  end

  QueueLiveFirstRepairTransfersForMember = function(activeSession, profileName, sessionId, memberKey, opts)
    opts = type(opts) == "table" and opts or {}
    local resolvedProfileName = TrimText(profileName)
    local resolvedSessionId = TrimText(sessionId)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    local resolvedDomains = CloneCheckpointDomainList(opts.domains)
    local resolvedSubdomains = CloneCheckpointSubdomainList(opts.subdomains)
    local baseMode = TrimText(opts.mode) ~= "" and TrimText(opts.mode) or "LIVE"
    local baseReason = TrimText(opts.reason) ~= "" and TrimText(opts.reason) or "repair"
    local authoritativeArchiveScope = string.upper(TrimText(opts.authoritativeArchiveScope))
    if authoritativeArchiveScope ~= "LOOT_LIST"
      and authoritativeArchiveScope ~= "SESSION_HISTORY"
      and authoritativeArchiveScope ~= "FUN_AWARDS"
    then
      authoritativeArchiveScope = ""
    end
    local requestedScope = ClassifyRequestedRepairScope(
      resolvedDomains,
      resolvedSubdomains,
      #resolvedSubdomains > 0 and "precise" or (#resolvedDomains > 0 and "targeted" or "same")
    )
    local coalesceExistingRepair, repairRequestState, _, coalescedRepairReason
    if authoritativeArchiveScope == "" then
      coalesceExistingRepair, repairRequestState, _, coalescedRepairReason = EvaluateRecentMemberRepairRequest(
        activeSession,
        resolvedProfileName,
        resolvedSessionId,
        resolvedMemberKey,
        resolvedDomains,
        resolvedSubdomains,
        {
          mode = baseMode,
          syncCandidate = type(opts.syncCandidate) == "table" and opts.syncCandidate or nil,
          localRepairRevisionSignature = TrimText(opts.localRepairRevisionSignature),
        }
      )
    end
    if coalesceExistingRepair then
      local coalescedDetail = {
        patchTransfers = 0,
        patchSubdomains = 0,
        snapshotTransfers = 0,
        snapshotSubdomains = 0,
        patchTransferSubdomains = {},
        snapshotFallbackSubdomains = {},
      fallbackReasons = {},
      transferKinds = {},
      duplicatePreparedTransfers = 0,
      dedupedTransferCount = 0,
      duplicateQueueSteps = 0,
      dedupedQueueStepCount = 0,
      queueMergeCount = 0,
      queueExactDuplicateCount = 0,
      skippedNoOp = true,
      deferredPatchState = false,
      scopeEscalated = false,
        fullSnapshotFallback = false,
        scopeEscalationKinds = {},
        requestedScope = requestedScope,
        effectiveDomains = CloneCheckpointDomainList(resolvedDomains),
        effectiveSubdomains = CloneCheckpointSubdomainList(resolvedSubdomains),
        coalescedExistingRepair = true,
        coalescedRepairReason = TrimText(coalescedRepairReason),
      }
      if type(RecordProfileSyncDecision) == "function" then
        RecordProfileSyncDecision("queue_live_first_repair", {
          action = "coalesced_existing_repair",
          sessionId = resolvedSessionId,
          profileName = resolvedProfileName,
          mode = baseMode,
          reason = baseReason,
          target = resolvedMemberKey,
          targetCount = resolvedMemberKey ~= "" and 1 or 0,
          queuedCount = 0,
          requestedScope = requestedScope,
          requestedDomains = CloneCheckpointDomainList(resolvedDomains),
          requestedSubdomains = CloneCheckpointSubdomainList(resolvedSubdomains),
          coalescedReason = TrimText(coalescedRepairReason),
        })
      end
      return true, 0, nil, coalescedDetail
    end

    local nonLootSubdomains, liveLootSubdomains, statsLootSubdomains, archiveLootSubdomains =
      profileSyncMetaOps.splitRepairSubdomainsForActiveSession(activeSession, resolvedSubdomains)

    local queueSteps = {}
    local hasPreciseLoot = (#liveLootSubdomains + #statsLootSubdomains + #archiveLootSubdomains) > 0
    local immediateDomains = hasPreciseLoot
      and profileSyncMetaOps.removeCheckpointDomain(resolvedDomains, "loot")
      or resolvedDomains
    local immediateSubdomains = MergeCheckpointSubdomainLists(nonLootSubdomains, liveLootSubdomains)

    if #immediateDomains > 0 or #immediateSubdomains > 0 then
      queueSteps[#queueSteps + 1] = {
        mode = baseMode,
        reason = baseReason,
        domains = immediateDomains,
        subdomains = immediateSubdomains,
        skipScopePrune = opts.skipScopePrune == true,
        syncCandidate = opts.syncCandidate,
      }
    end
    if #statsLootSubdomains > 0 then
      queueSteps[#queueSteps + 1] = {
        mode = "BACKGROUND",
        reason = baseReason .. "_stats_background",
        domains = nil,
        subdomains = statsLootSubdomains,
        skipScopePrune = opts.skipScopePrune == true,
        syncCandidate = opts.syncCandidate,
      }
    end
    if #archiveLootSubdomains > 0 then
      queueSteps[#queueSteps + 1] = {
        mode = "BACKGROUND",
        reason = baseReason .. "_archive_background",
        domains = nil,
        subdomains = archiveLootSubdomains,
        skipScopePrune = opts.skipScopePrune == true,
        syncCandidate = opts.syncCandidate,
      }
    end
    if #queueSteps == 0 then
      queueSteps[1] = {
        mode = baseMode,
        reason = baseReason,
        domains = resolvedDomains,
        subdomains = resolvedSubdomains,
        skipScopePrune = opts.skipScopePrune == true,
        syncCandidate = opts.syncCandidate,
      }
    end

    if authoritativeArchiveScope ~= "" then
      for _, step in ipairs(queueSteps) do
        local stepArchiveScope = profileSyncMetaOps.resolveAuthoritativeArchiveScope(step.subdomains)
        local emptyManifestDomainMatch = #CloneCheckpointSubdomainList(step.subdomains) == 0
          and (
            authoritativeArchiveScope == "LOOT_LIST" and HasComparedDomain(step.domains, "loot")
            or authoritativeArchiveScope == "SESSION_HISTORY" and HasComparedDomain(step.domains, "session")
            or authoritativeArchiveScope == "FUN_AWARDS" and HasComparedDomain(step.domains, "loot")
          )
        if stepArchiveScope == authoritativeArchiveScope or emptyManifestDomainMatch then
          step.authoritativeArchiveScope = authoritativeArchiveScope
          step.mode = "BACKGROUND"
          step.reason = baseReason .. "_" .. string.lower(authoritativeArchiveScope) .. "_archive_authoritative"
        end
      end
    end

    local duplicateQueueSteps = 0
    queueSteps, duplicateQueueSteps = profileSyncMetaOps.dedupeRepairQueueSteps(queueSteps)

    local completedAny = false
    local queuedAny = false
    local totalQueuedCount = 0
    local lastQueueError = nil
    local mergedDetail = {
      patchTransfers = 0,
      patchSubdomains = 0,
      snapshotTransfers = 0,
      snapshotSubdomains = 0,
      patchTransferSubdomains = {},
      snapshotFallbackSubdomains = {},
      fallbackReasons = {},
      transferKinds = {},
      duplicatePreparedTransfers = 0,
      dedupedTransferCount = 0,
      duplicateQueueSteps = math.max(0, tonumber(duplicateQueueSteps) or 0),
      dedupedQueueStepCount = #(type(queueSteps) == "table" and queueSteps or {}),
      queueMergeCount = 0,
      queueExactDuplicateCount = 0,
      skippedNoOp = false,
      deferredPatchState = false,
      scopeEscalated = false,
      fullSnapshotFallback = false,
      scopeEscalationKinds = {},
      requestedScope = requestedScope,
      effectiveDomains = CloneCheckpointDomainList(resolvedDomains),
      effectiveSubdomains = CloneCheckpointSubdomainList(resolvedSubdomains),
      coalescedExistingRepair = false,
      coalescedRepairReason = "",
    }
    if duplicateQueueSteps > 0 and type(RecordProfileSyncDecision) == "function" then
      RecordProfileSyncDecision("queue_live_first_repair", {
        action = "deduped_queue_steps",
        sessionId = resolvedSessionId,
        profileName = resolvedProfileName,
        mode = baseMode,
        reason = baseReason,
        target = resolvedMemberKey,
        targetCount = resolvedMemberKey ~= "" and 1 or 0,
        queuedCount = 0,
        duplicateQueueSteps = duplicateQueueSteps,
        dedupedQueueStepCount = #queueSteps,
        requestedScope = requestedScope,
        requestedDomains = CloneCheckpointDomainList(resolvedDomains),
        requestedSubdomains = CloneCheckpointSubdomainList(resolvedSubdomains),
      })
    end
    for _, step in ipairs(queueSteps) do
      local ok, queuedCount, queueError, prepareDetail = QueuePreparedRepairTransfersForMember(profileName, sessionId, memberKey, step)
      if ok then
        completedAny = true
        if math.max(0, tonumber(queuedCount) or 0) > 0 then
          queuedAny = true
          totalQueuedCount = totalQueuedCount + math.max(0, tonumber(queuedCount) or 0)
        end
      elseif TrimText(queueError) ~= "" then
        lastQueueError = queueError
      end
      if type(prepareDetail) == "table" then
        mergedDetail.patchTransfers = mergedDetail.patchTransfers + math.max(0, tonumber(prepareDetail.patchTransfers) or 0)
        mergedDetail.patchSubdomains = mergedDetail.patchSubdomains + math.max(0, tonumber(prepareDetail.patchSubdomains) or 0)
        mergedDetail.snapshotTransfers = mergedDetail.snapshotTransfers + math.max(0, tonumber(prepareDetail.snapshotTransfers) or 0)
        mergedDetail.snapshotSubdomains = mergedDetail.snapshotSubdomains + math.max(0, tonumber(prepareDetail.snapshotSubdomains) or 0)
        mergedDetail.patchTransferSubdomains = MergeDecisionTextLists(
          mergedDetail.patchTransferSubdomains,
          prepareDetail.patchTransferSubdomains
        )
        mergedDetail.snapshotFallbackSubdomains = MergeDecisionTextLists(
          mergedDetail.snapshotFallbackSubdomains,
          prepareDetail.snapshotFallbackSubdomains
        )
        mergedDetail.duplicatePreparedTransfers = mergedDetail.duplicatePreparedTransfers
          + math.max(0, tonumber(prepareDetail.duplicatePreparedTransfers) or 0)
        mergedDetail.dedupedTransferCount = mergedDetail.dedupedTransferCount
          + math.max(0, tonumber(prepareDetail.dedupedTransferCount) or 0)
        mergedDetail.queueMergeCount = mergedDetail.queueMergeCount
          + math.max(0, tonumber(prepareDetail.queueMergeCount) or 0)
        mergedDetail.queueExactDuplicateCount = mergedDetail.queueExactDuplicateCount
          + math.max(0, tonumber(prepareDetail.queueExactDuplicateCount) or 0)
        mergedDetail.fallbackReasons = MergeDecisionTextLists(
          mergedDetail.fallbackReasons,
          prepareDetail.fallbackReasons
        )
        mergedDetail.transferKinds = MergeDecisionTextLists(
          mergedDetail.transferKinds,
          prepareDetail.transferKinds
        )
        mergedDetail.skippedNoOp = mergedDetail.skippedNoOp or prepareDetail.skippedNoOp == true
        mergedDetail.deferredPatchState = mergedDetail.deferredPatchState or prepareDetail.deferredPatchState == true
        mergedDetail.scopeEscalated = mergedDetail.scopeEscalated or prepareDetail.scopeEscalated == true
        mergedDetail.fullSnapshotFallback = mergedDetail.fullSnapshotFallback or prepareDetail.fullSnapshotFallback == true
        mergedDetail.scopeEscalationKinds = MergeDecisionTextLists(
          mergedDetail.scopeEscalationKinds,
          prepareDetail.scopeEscalationKinds
        )
      end
    end

    if not completedAny then
      if type(RecordProfileSyncDecision) == "function" then
        RecordProfileSyncDecision("queue_live_first_repair", {
          action = "failed",
          sessionId = TrimText(sessionId),
          profileName = TrimText(profileName),
          mode = baseMode,
          reason = baseReason,
          target = NormalizeCharacterKey(memberKey),
          targetCount = NormalizeCharacterKey(memberKey) ~= "" and 1 or 0,
          queuedCount = 0,
          transferCount = mergedDetail.patchTransfers + mergedDetail.snapshotTransfers,
          duplicatePreparedTransfers = math.max(0, tonumber(mergedDetail.duplicatePreparedTransfers) or 0),
          duplicateQueueSteps = math.max(0, tonumber(mergedDetail.duplicateQueueSteps) or 0),
          dedupedQueueStepCount = math.max(0, tonumber(mergedDetail.dedupedQueueStepCount) or 0),
          transferKinds = CloneDecisionTextList(mergedDetail.transferKinds),
          requestedDomains = CloneCheckpointDomainList(resolvedDomains),
          requestedSubdomains = CloneCheckpointSubdomainList(resolvedSubdomains),
          patchSubdomains = CloneCheckpointSubdomainList(mergedDetail.patchTransferSubdomains),
          snapshotFallbackSubdomains = CloneCheckpointSubdomainList(mergedDetail.snapshotFallbackSubdomains),
          scopeEscalated = mergedDetail.scopeEscalated == true,
          fullSnapshotFallback = mergedDetail.fullSnapshotFallback == true,
          scopeEscalationKinds = CloneDecisionTextList(mergedDetail.scopeEscalationKinds),
          fallbackReason = mergedDetail.fallbackReasons[1],
          fallbackReasons = CloneDecisionTextList(mergedDetail.fallbackReasons),
          error = lastQueueError,
        })
      end
      return false, 0, lastQueueError, mergedDetail
    end
    if type(RecordProfileSyncDecision) == "function" then
      RecordProfileSyncDecision("queue_live_first_repair", {
        action = queuedAny
          and "queued"
          or (mergedDetail.deferredPatchState and "deferred_patch_state"
            or (mergedDetail.skippedNoOp and "skipped_noop" or "completed")),
        sessionId = TrimText(sessionId),
        profileName = TrimText(profileName),
        mode = baseMode,
        reason = baseReason,
        target = NormalizeCharacterKey(memberKey),
        targetCount = NormalizeCharacterKey(memberKey) ~= "" and 1 or 0,
        queuedCount = totalQueuedCount,
        transferCount = mergedDetail.patchTransfers + mergedDetail.snapshotTransfers,
        duplicatePreparedTransfers = math.max(0, tonumber(mergedDetail.duplicatePreparedTransfers) or 0),
        duplicateQueueSteps = math.max(0, tonumber(mergedDetail.duplicateQueueSteps) or 0),
        dedupedQueueStepCount = math.max(0, tonumber(mergedDetail.dedupedQueueStepCount) or 0),
        transferKinds = CloneDecisionTextList(mergedDetail.transferKinds),
        requestedDomains = CloneCheckpointDomainList(resolvedDomains),
        requestedSubdomains = CloneCheckpointSubdomainList(resolvedSubdomains),
        patchSubdomains = CloneCheckpointSubdomainList(mergedDetail.patchTransferSubdomains),
        snapshotFallbackSubdomains = CloneCheckpointSubdomainList(mergedDetail.snapshotFallbackSubdomains),
        scopeEscalated = mergedDetail.scopeEscalated == true,
        fullSnapshotFallback = mergedDetail.fullSnapshotFallback == true,
        scopeEscalationKinds = CloneDecisionTextList(mergedDetail.scopeEscalationKinds),
        fallbackReason = mergedDetail.fallbackReasons[1],
        fallbackReasons = CloneDecisionTextList(mergedDetail.fallbackReasons),
      })
    end
    if (queuedAny or mergedDetail.deferredPatchState == true) and type(repairRequestState) == "table" then
      RememberRecentMemberRepairRequestState(resolvedSessionId, resolvedMemberKey, repairRequestState)
    end
    return true, totalQueuedCount, nil, mergedDetail
  end

  profileSyncMetaOps.buildAutomaticHostRepairTransportState = function(activeSession, profileName, sessionId, memberKey, detail, syncCandidate, localRepairRevisionSignature, repairDomains, repairSubdomains, opts)
    local resolvedSessionId = TrimText(sessionId)
    local resolvedProfileName = TrimText(profileName)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if resolvedSessionId == "" or resolvedProfileName == "" or resolvedMemberKey == "" then
      return "", ""
    end
    local memberState = select(1, FindSessionMember(activeSession, resolvedMemberKey))
    local targetSignature = TrimText(type(opts) == "table" and opts.liveTargetSignature or "")
    if targetSignature == "" then
      local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
      targetSignature = BuildLiveSyncTargetSignature(activeSession, selfKey, nil)
    end
    local transportSignature = table.concat({
      BuildLocalRepairRevisionSignature(activeSession, resolvedProfileName, syncCandidate, TrimText(localRepairRevisionSignature)),
      BuildSessionMemberRepairStateSignature(memberState),
      TrimText(type(detail) == "table" and detail.repairMode or ""),
      type(detail) == "table" and detail.forceFullSnapshot == true and "1" or "0",
      TrimText(type(opts) == "table" and opts.mode or ""),
      BuildNormalizedRepairListSignature(repairDomains),
      BuildNormalizedRepairListSignature(repairSubdomains),
      targetSignature,
    }, "\31")
    return BuildProfileCheckpointStateKey(resolvedSessionId, resolvedProfileName) .. "|" .. string.lower(resolvedMemberKey), transportSignature
  end

  profileSyncMetaOps.rememberAutomaticHostRepairTransportState = function(transportStateKey, transportSignature, queuedCount)
    if transportStateKey == "" or transportSignature == "" or type(profileSyncMetaOps.recentAutomaticHostRepairRequestStates) ~= "table" then
      return
    end
    profileSyncMetaOps.recentAutomaticHostRepairRequestStates[transportStateKey] = {
      transportSignature = transportSignature,
      queuedCount = math.max(0, tonumber(queuedCount) or 0),
      queuedAt = GetProfileCheckpointSyncTime(),
    }
  end

  profileSyncMetaOps.trySuppressUnchangedAutomaticHostRepair = function(sessionId, profileName, memberKey, mode, reason, detail, repairDomains, repairSubdomains, transportStateKey, transportSignature)
    PruneAgedSessionRuntimeTracking(GetProfileCheckpointSyncTime())
    local recentRepairState = type(profileSyncMetaOps.recentAutomaticHostRepairRequestStates) == "table"
      and profileSyncMetaOps.recentAutomaticHostRepairRequestStates[transportStateKey]
      or nil
    if transportStateKey ~= "" and type(recentRepairState) == "table" then
      local recentQueuedAt = math.max(0, tonumber(recentRepairState.queuedAt) or 0)
      if recentQueuedAt <= 0
        or (GetProfileCheckpointSyncTime() - recentQueuedAt) >= sessionConfig.automaticHostRepairRequestRetentionSeconds
      then
        profileSyncMetaOps.recentAutomaticHostRepairRequestStates[transportStateKey] = nil
        recentRepairState = nil
      end
    end
    if transportSignature == ""
      or type(recentRepairState) ~= "table"
      or recentRepairState.transportSignature ~= transportSignature
    then
      return false
    end
    detail.suppressedUnchanged = true
    detail.skippedNoOp = true
    if detail.repairMode == "same" then
      detail.skippedAligned = true
    elseif detail.repairMode == "member_newer" then
      detail.skippedMemberNewer = true
    end
    if type(RecordProfileSyncDecision) == "function" then
      RecordProfileSyncDecision("queue_automatic_host_repair", {
        action = "suppressed_unchanged",
        sessionId = TrimText(sessionId),
        profileName = TrimText(profileName),
        mode = TrimText(mode),
        reason = TrimText(reason),
        target = NormalizeCharacterKey(memberKey),
        targetCount = NormalizeCharacterKey(memberKey) ~= "" and 1 or 0,
        queuedCount = 0,
        requestedScope = TrimText(type(detail) == "table" and detail.requestedScope or ""),
        requestedDomains = CloneCheckpointDomainList(repairDomains),
        requestedSubdomains = CloneCheckpointSubdomainList(repairSubdomains),
        fullSnapshotFallback = type(detail) == "table" and detail.forceFullSnapshot == true,
      })
    end
    return true
  end

  profileSyncMetaOps.persistDisplayedSessionMemberRepairOutcome = function(activeSession, profileName, sessionId, memberKey, queuedCount, detail, repairError, opts)
    if type(profileSyncMetaOps.persistSessionMemberRepairOutcome) ~= "function" then
      return false, nil, nil
    end
    opts = type(opts) == "table" and opts or {}
    local resolvedProfileName = TrimText(profileName)
    local resolvedSessionId = TrimText(sessionId)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    local existingMember = FindSessionMember(activeSession, resolvedMemberKey)
    local currentSessionDisplayContext = nil
    local previousCurrentSessionDisplay = nil
    if type(existingMember) == "table" then
      currentSessionDisplayContext = type(opts.currentSessionDisplayBaseContext) == "table"
        and INTERNAL_API.LIDCOUNCIL_BuildHostCurrentSessionDisplayContextFromBase(
          activeSession,
          resolvedProfileName,
          resolvedMemberKey,
          opts.currentSessionDisplayBaseContext,
          type(opts.syncCandidateSnapshot) == "table" and opts.syncCandidateSnapshot or nil
        )
        or INTERNAL_API.LIDCOUNCIL_BuildHostCurrentSessionDisplayContext(
          activeSession,
          resolvedProfileName,
          resolvedMemberKey,
          {
            syncCandidateSnapshot = type(opts.syncCandidateSnapshot) == "table" and opts.syncCandidateSnapshot or nil,
          }
        )
      previousCurrentSessionDisplay = INTERNAL_API.LIDCOUNCIL_BuildHostCurrentSessionMemberDisplayState(
        activeSession,
        resolvedProfileName,
        resolvedMemberKey,
        existingMember,
        currentSessionDisplayContext
      )
    end
    local ok, member, persistResult = profileSyncMetaOps.persistSessionMemberRepairOutcome(
      activeSession,
      resolvedProfileName,
      resolvedSessionId,
      resolvedMemberKey,
      queuedCount,
      detail,
      repairError,
      {
        sourceLabel = TrimText(opts.sourceLabel),
        currentSessionDisplayContext = currentSessionDisplayContext,
        previousCurrentSessionDisplay = previousCurrentSessionDisplay,
        syncCandidateSnapshot = type(opts.syncCandidateSnapshot) == "table" and opts.syncCandidateSnapshot or nil,
        rowPatchTransfers = opts.rowPatchTransfers,
        requestedDomains = opts.requestedDomains,
        requestedSubdomains = opts.requestedSubdomains,
        refreshEditor = opts.refreshEditor == true,
      }
    )
    if type(detail) == "table" and type(persistResult) == "table" and persistResult.stamped == true then
      detail.outcomePersisted = true
      detail.currentSectionChanged = persistResult.currentSectionChanged == true
    end
    return ok, member, persistResult
  end

  profileSyncMetaOps.persistAutomaticHostRepairOutcome = function(activeSession, profileName, sessionId, memberKey, queuedCount, detail, repairError, sourceLabel, syncCandidateSnapshot, opts)
    return profileSyncMetaOps.persistDisplayedSessionMemberRepairOutcome(
      activeSession,
      profileName,
      sessionId,
      memberKey,
      queuedCount,
      detail,
      repairError,
      {
        sourceLabel = sourceLabel,
        syncCandidateSnapshot = syncCandidateSnapshot,
        currentSessionDisplayBaseContext = type(opts) == "table" and opts.currentSessionDisplayBaseContext or nil,
        refreshEditor = type(opts) == "table" and opts.refreshEditor == true,
      }
    )
  end

  profileSyncMetaOps.recordRepairHistoryIfSupported = function(entry)
    if type(profileSyncMetaOps.recordRepairHistory) == "function" and type(entry) == "table" then
      profileSyncMetaOps.recordRepairHistory(entry)
    end
  end

  profileSyncMetaOps.recordStandardRepairHistory = function(kind, summary, opts)
    opts = type(opts) == "table" and opts or {}
    local resolvedKind = TrimText(kind)
    local resolvedSummary = TrimText(summary)
    if resolvedKind == "" or resolvedSummary == "" then
      return false
    end
    profileSyncMetaOps.recordRepairHistoryIfSupported({
      profileName = TrimText(opts.profileName),
      sessionId = TrimText(opts.sessionId),
      memberKey = TrimText(opts.memberKey),
      kind = resolvedKind,
      summary = resolvedSummary,
      createdAt = math.max(0, tonumber(opts.createdAt) or tonumber(time and time() or 0) or 0),
      skipIfRecentSame = opts.skipIfRecentSame ~= false,
      dedupeWindowSeconds = math.max(0, tonumber(opts.dedupeWindowSeconds) or 0),
    })
    return true
  end

  profileSyncMetaOps.applyPreparedLiveRepairDetailToAutomaticHostRepair = function(detail, repairDetail)
    if type(detail) ~= "table" or type(repairDetail) ~= "table" then
      return
    end
    detail.patchTransfers = math.max(0, tonumber(repairDetail.patchTransfers) or 0)
    detail.patchSubdomains = math.max(0, tonumber(repairDetail.patchSubdomains) or 0)
    detail.snapshotTransfers = math.max(0, tonumber(repairDetail.snapshotTransfers) or 0)
    detail.snapshotSubdomains = math.max(0, tonumber(repairDetail.snapshotSubdomains) or 0)
    detail.transferKinds = CloneDecisionTextList(repairDetail.transferKinds)
    detail.patchTransferSubdomains = CloneCheckpointSubdomainList(repairDetail.patchTransferSubdomains)
    detail.snapshotFallbackSubdomains = CloneCheckpointSubdomainList(repairDetail.snapshotFallbackSubdomains)
    detail.fallbackReasons = CloneDecisionTextList(repairDetail.fallbackReasons)
    detail.skippedNoOp = repairDetail.skippedNoOp == true
    detail.deferredPatchState = repairDetail.deferredPatchState == true
    detail.requestedScope = TrimText(repairDetail.requestedScope) ~= ""
      and TrimText(repairDetail.requestedScope)
      or detail.requestedScope
    detail.requestedDomains = CloneCheckpointDomainList(repairDetail.requestedDomains)
    detail.requestedSubdomains = CloneCheckpointSubdomainList(repairDetail.requestedSubdomains)
    detail.effectiveDomains = CloneCheckpointDomainList(repairDetail.effectiveDomains)
    detail.effectiveSubdomains = CloneCheckpointSubdomainList(repairDetail.effectiveSubdomains)
    detail.duplicatePreparedTransfers = math.max(0, tonumber(repairDetail.duplicatePreparedTransfers) or 0)
    detail.dedupedTransferCount = math.max(0, tonumber(repairDetail.dedupedTransferCount) or 0)
    detail.duplicateQueueSteps = math.max(0, tonumber(repairDetail.duplicateQueueSteps) or 0)
    detail.dedupedQueueStepCount = math.max(0, tonumber(repairDetail.dedupedQueueStepCount) or 0)
    detail.queueMergeCount = math.max(0, tonumber(repairDetail.queueMergeCount) or 0)
    detail.queueExactDuplicateCount = math.max(0, tonumber(repairDetail.queueExactDuplicateCount) or 0)
    detail.scopeEscalated = repairDetail.scopeEscalated == true
    detail.fullSnapshotFallback = repairDetail.fullSnapshotFallback == true
    detail.scopeEscalationKinds = CloneDecisionTextList(repairDetail.scopeEscalationKinds)
    detail.coalescedExistingRepair = repairDetail.coalescedExistingRepair == true
    detail.coalescedRepairReason = TrimText(repairDetail.coalescedRepairReason)
  end

  profileSyncMetaOps.queueAutomaticHostRepairForMember = function(activeSession, profileName, sessionId, memberKey, opts)
    opts = type(opts) == "table" and opts or {}
    local resolvedProfileName = TrimText(profileName)
    local resolvedSessionId = TrimText(sessionId)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    local mode = TrimText(opts.mode) ~= "" and TrimText(opts.mode) or "LIVE"
    local reason = TrimText(opts.reason) ~= "" and TrimText(opts.reason) or "repair"
    local sourceLabel = TrimText(opts.sourceLabelOverride)
    if sourceLabel == "" then
      sourceLabel = reason == "duplicate_join_recovery" and "duplicate JOIN recovery" or "host repair"
    end
    local explicitDomains = CloneCheckpointDomainList(opts.domains)
    local explicitSubdomains = CloneCheckpointSubdomainList(opts.subdomains)
    local explicitScopeSelected = #explicitDomains > 0 or #explicitSubdomains > 0
    local prebuiltLocalRepairRevisionSignature = TrimText(opts.localRepairRevisionSignature)
    local syncCandidateSnapshot = type(opts.syncCandidateSnapshot) == "table" and opts.syncCandidateSnapshot or nil
    local syncCandidate = type(opts.syncCandidate) == "table" and opts.syncCandidate or nil
    if syncCandidate == nil or prebuiltLocalRepairRevisionSignature == "" then
      local contextCandidate, contextLocalRepairRevisionSignature = GetActiveSyncCandidateContextFromSnapshot(
        resolvedMemberKey,
        syncCandidateSnapshot
      )
      if syncCandidate == nil then
        syncCandidate = contextCandidate
      end
      if prebuiltLocalRepairRevisionSignature == "" then
        prebuiltLocalRepairRevisionSignature = contextLocalRepairRevisionSignature
      end
    end

    local detail = {
      repairMode = "",
      forceFullSnapshot = false,
      patchTransfers = 0,
      patchSubdomains = 0,
      snapshotTransfers = 0,
      snapshotSubdomains = 0,
      transferKinds = {},
      patchTransferSubdomains = {},
      snapshotFallbackSubdomains = {},
      fallbackReasons = {},
      duplicatePreparedTransfers = 0,
      dedupedTransferCount = 0,
      duplicateQueueSteps = 0,
      dedupedQueueStepCount = 0,
      queueMergeCount = 0,
      queueExactDuplicateCount = 0,
      skippedAligned = false,
      skippedMemberNewer = false,
      skippedNoOp = false,
      deferredPatchState = false,
      suppressedUnchanged = false,
      requestedScope = "",
      requestedDomains = {},
      requestedSubdomains = {},
      effectiveDomains = {},
      effectiveSubdomains = {},
      scopeEscalated = false,
      fullSnapshotFallback = false,
      scopeEscalationKinds = {},
      coalescedExistingRepair = false,
      coalescedRepairReason = "",
      outcomePersisted = false,
      currentSectionChanged = false,
    }

    local repairDomains, repairSubdomains, forceFullSnapshot, repairMode
    if opts.forceFullSnapshot == true then
      repairDomains = {}
      repairSubdomains = {}
      forceFullSnapshot = true
      repairMode = "full"
    elseif explicitScopeSelected then
      repairDomains = explicitDomains
      repairSubdomains = explicitSubdomains
      forceFullSnapshot = opts.forceFullSnapshot == true
      repairMode = #repairSubdomains > 0 and "precise" or (#repairDomains > 0 and "targeted" or "full")
    else
      repairDomains, repairSubdomains, forceFullSnapshot, repairMode = BuildHostRepairDomainsForMember(resolvedMemberKey, syncCandidate)
    end

    detail.repairMode = TrimText(repairMode)
    detail.forceFullSnapshot = forceFullSnapshot == true or detail.repairMode == "full"
    detail.requestedScope = ClassifyRequestedRepairScope(repairDomains, repairSubdomains, detail.repairMode)
    detail.requestedDomains = CloneCheckpointDomainList(repairDomains)
    detail.requestedSubdomains = CloneCheckpointSubdomainList(repairSubdomains)
    detail.effectiveDomains = CloneCheckpointDomainList(repairDomains)
    detail.effectiveSubdomains = CloneCheckpointSubdomainList(repairSubdomains)
    local repairTransportStateKey, repairTransportSignature = profileSyncMetaOps.buildAutomaticHostRepairTransportState(
      activeSession,
      resolvedProfileName,
      resolvedSessionId,
      resolvedMemberKey,
      detail,
      syncCandidate,
      prebuiltLocalRepairRevisionSignature,
      repairDomains,
      repairSubdomains,
      {
        mode = mode,
        liveTargetSignature = opts.liveTargetSignature,
      }
    )
    if TrimText(opts.authoritativeArchiveScope) == ""
      and opts.suppressUnchanged == true
      and profileSyncMetaOps.trySuppressUnchangedAutomaticHostRepair(
      resolvedSessionId,
      resolvedProfileName,
      resolvedMemberKey,
      mode,
      reason,
      detail,
      repairDomains,
      repairSubdomains,
      repairTransportStateKey,
      repairTransportSignature
    ) then
      return true, 0, nil, detail
    end
    if detail.repairMode == "same" then
      detail.skippedAligned = true
      detail.skippedNoOp = true
      profileSyncMetaOps.rememberAutomaticHostRepairTransportState(repairTransportStateKey, repairTransportSignature, 0)
      profileSyncMetaOps.persistAutomaticHostRepairOutcome(
        activeSession,
        resolvedProfileName,
        resolvedSessionId,
        resolvedMemberKey,
        0,
        detail,
        nil,
        sourceLabel,
        syncCandidateSnapshot,
        opts
      )
      return true, 0, nil, detail
    elseif detail.repairMode == "member_newer" then
      detail.skippedMemberNewer = true
      profileSyncMetaOps.rememberAutomaticHostRepairTransportState(repairTransportStateKey, repairTransportSignature, 0)
      profileSyncMetaOps.persistAutomaticHostRepairOutcome(
        activeSession,
        resolvedProfileName,
        resolvedSessionId,
        resolvedMemberKey,
        0,
        detail,
        nil,
        sourceLabel,
        syncCandidateSnapshot,
        opts
      )
      return true, 0, nil, detail
    end

    if detail.forceFullSnapshot then
      local coalesceExistingRepair, fullSnapshotRequestState, ignoredRepairState, coalescedRepairReason
      if opts.forceAuthoritativeOverride ~= true then
        coalesceExistingRepair, fullSnapshotRequestState, ignoredRepairState, coalescedRepairReason = EvaluateRecentMemberRepairRequest(
          activeSession,
          resolvedProfileName,
          resolvedSessionId,
          resolvedMemberKey,
          {},
          {},
          {
            mode = mode,
            forceFullSnapshot = true,
            syncCandidate = syncCandidate,
            localRepairRevisionSignature = prebuiltLocalRepairRevisionSignature,
          }
        )
      end
      if coalesceExistingRepair then
        detail.skippedNoOp = true
        detail.coalescedExistingRepair = true
        detail.coalescedRepairReason = TrimText(coalescedRepairReason)
        if type(RecordProfileSyncDecision) == "function" then
          RecordProfileSyncDecision("queue_automatic_host_repair", {
            action = "coalesced_existing_repair",
            sessionId = resolvedSessionId,
            profileName = resolvedProfileName,
            mode = mode,
            reason = reason,
            target = resolvedMemberKey,
            targetCount = 1,
            queuedCount = 0,
            requestedScope = detail.requestedScope,
            requestedDomains = CloneCheckpointDomainList(repairDomains),
            requestedSubdomains = CloneCheckpointSubdomainList(repairSubdomains),
            fullSnapshotFallback = detail.forceFullSnapshot == true,
            coalescedReason = TrimText(coalescedRepairReason),
          })
        end
        profileSyncMetaOps.rememberAutomaticHostRepairTransportState(repairTransportStateKey, repairTransportSignature, 0)
        profileSyncMetaOps.persistAutomaticHostRepairOutcome(
          activeSession,
          resolvedProfileName,
          resolvedSessionId,
          resolvedMemberKey,
          0,
          detail,
          nil,
          sourceLabel,
          syncCandidateSnapshot,
          opts
        )
        return true, 0, nil, detail
      end
      local queuedSnapshot, queueSnapshotResult, queueBatchDetail = QueueProfileSnapshotForMember(
        resolvedProfileName,
        resolvedSessionId,
        resolvedMemberKey,
        {
          mode = mode,
          reason = reason,
        }
      )
      if queuedSnapshot then
        detail.snapshotTransfers = math.max(1, tonumber(queueSnapshotResult) or 1)
        detail.transferKinds = { "FULL" }
        profileSyncMetaOps.applyOutboundQueueStatsToRepairDetail(detail, queueBatchDetail)
        RememberRecentMemberRepairRequestState(resolvedSessionId, resolvedMemberKey, fullSnapshotRequestState)
        profileSyncMetaOps.rememberAutomaticHostRepairTransportState(repairTransportStateKey, repairTransportSignature, detail.snapshotTransfers)
        profileSyncMetaOps.persistAutomaticHostRepairOutcome(
          activeSession,
          resolvedProfileName,
          resolvedSessionId,
          resolvedMemberKey,
          detail.snapshotTransfers,
          detail,
          nil,
          sourceLabel,
          syncCandidateSnapshot,
          opts
        )
        return true, detail.snapshotTransfers, nil, detail
      end
      profileSyncMetaOps.persistAutomaticHostRepairOutcome(
        activeSession,
        resolvedProfileName,
        resolvedSessionId,
        resolvedMemberKey,
        0,
        detail,
        queueSnapshotResult,
        sourceLabel,
        syncCandidateSnapshot,
        opts
      )
      return false, 0, queueSnapshotResult, detail
    end

    local queuedRepair, queuedCount, repairError, repairDetail = QueueLiveFirstRepairTransfersForMember(
      activeSession,
      resolvedProfileName,
      resolvedSessionId,
      resolvedMemberKey,
      {
        mode = mode,
        reason = reason,
        domains = repairDomains,
        subdomains = repairSubdomains,
        skipScopePrune = opts.skipScopePrune == true,
        authoritativeArchiveScope = opts.authoritativeArchiveScope,
        syncCandidate = syncCandidate,
        localRepairRevisionSignature = prebuiltLocalRepairRevisionSignature,
      }
    )
    if type(repairDetail) == "table" then
      profileSyncMetaOps.applyPreparedLiveRepairDetailToAutomaticHostRepair(detail, repairDetail)
    end
    if queuedRepair then
      local resolvedQueuedCount = math.max(0, tonumber(queuedCount) or 0)
      profileSyncMetaOps.rememberAutomaticHostRepairTransportState(repairTransportStateKey, repairTransportSignature, resolvedQueuedCount)
      profileSyncMetaOps.persistAutomaticHostRepairOutcome(
        activeSession,
        resolvedProfileName,
        resolvedSessionId,
        resolvedMemberKey,
        resolvedQueuedCount,
        detail,
        nil,
        sourceLabel,
        syncCandidateSnapshot,
        opts
      )
      return true, resolvedQueuedCount, nil, detail
    end
    profileSyncMetaOps.persistAutomaticHostRepairOutcome(
      activeSession,
      resolvedProfileName,
      resolvedSessionId,
      resolvedMemberKey,
      0,
      detail,
      repairError,
      sourceLabel,
      syncCandidateSnapshot,
      opts
    )
    return false, 0, repairError, detail
  end

  profileSyncMetaOps.getUndispatchedAckTimeoutRevalidationDomains = function(domains, dispatchedDomains)
    local dispatchedLookup = {}
    for _, domain in ipairs(CloneCheckpointDomainList(dispatchedDomains)) do
      dispatchedLookup[domain] = true
    end
    local undispatched = {}
    for _, domain in ipairs(CloneCheckpointDomainList(domains)) do
      if not dispatchedLookup[domain] then
        undispatched[#undispatched + 1] = domain
      end
    end
    return undispatched
  end

  profileSyncMetaOps.shouldScheduleAckTimeoutRevalidationRecovery = function(pendingRevalidation)
    return type(pendingRevalidation) == "table" and pendingRevalidation.recoveryScheduled ~= true
  end

  profileSyncMetaOps.getAckTimeoutRevalidationStats = function(sessionId)
    local stats = type(sessionRuntime.ackTimeoutRevalidationStats) == "table"
      and sessionRuntime.ackTimeoutRevalidationStats
      or {}
    local requestedSessionId = TrimText(sessionId)
    if requestedSessionId ~= "" and requestedSessionId ~= TrimText(stats.sessionId) then
      return {
        sessionId = requestedSessionId,
        suppressedDomainTotal = 0,
        coalescedRecoveryCallbackTotal = 0,
        sharedRecoveryBatchTotal = 0,
        sharedRecoveryTransferTotal = 0,
        lastSuppressedDomainCount = 0,
        lastSharedRecoveryTransferCount = 0,
      }
    end
    return {
      sessionId = TrimText(stats.sessionId),
      suppressedDomainTotal = math.max(0, tonumber(stats.suppressedDomainTotal) or 0),
      coalescedRecoveryCallbackTotal = math.max(0, tonumber(stats.coalescedRecoveryCallbackTotal) or 0),
      sharedRecoveryBatchTotal = math.max(0, tonumber(stats.sharedRecoveryBatchTotal) or 0),
      sharedRecoveryTransferTotal = math.max(0, tonumber(stats.sharedRecoveryTransferTotal) or 0),
      lastSuppressedDomainCount = math.max(0, tonumber(stats.lastSuppressedDomainCount) or 0),
      lastSharedRecoveryTransferCount = math.max(0, tonumber(stats.lastSharedRecoveryTransferCount) or 0),
    }
  end

  profileSyncMetaOps.reconcileOutboundProfileAckTimeout = function(transfer)
    transfer = type(transfer) == "table" and transfer or {}
    local sessionId = TrimText(transfer.sessionId)
    local profileName = TrimText(transfer.profileName)
    local memberKey = NormalizeCharacterKey(transfer.target)
    local transferId = TrimText(transfer.transferId)
    if sessionId == "" or profileName == "" or memberKey == "" or transferId == "" then
      return false, { outcome = "invalid_transfer", error = "Timed-out snapshot transfer is missing its identity." }
    end
    local revalidationStats = type(sessionRuntime.ackTimeoutRevalidationStats) == "table"
      and sessionRuntime.ackTimeoutRevalidationStats
      or {}
    if TrimText(revalidationStats.sessionId) ~= sessionId then
      revalidationStats = {
        sessionId = sessionId,
        suppressedDomainTotal = 0,
        coalescedRecoveryCallbackTotal = 0,
        sharedRecoveryBatchTotal = 0,
        sharedRecoveryTransferTotal = 0,
        lastSuppressedDomainCount = 0,
        lastSharedRecoveryTransferCount = 0,
      }
      sessionRuntime.ackTimeoutRevalidationStats = revalidationStats
    end
    local function FinishRecovery(recoveryReason)
      if TrimText(transfer.state) ~= "ack_timeout" then
        return true, { outcome = "no_longer_timed_out" }
      end

      local activeSession, activeProfileName = GetActiveLootSession()
      local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
      if not DoesActiveSessionMatch(activeSession, activeProfileName, sessionId, profileName) then
        return false, { outcome = "session_changed", error = "The timed-out transfer no longer belongs to the active session." }
      end
      if selfKey == "" or not AreCharacterKeysSame(activeSession.host or "", selfKey) then
        return false, { outcome = "not_host", error = "Only the active host can reconcile a timed-out transfer." }
      end
      if not IsJoinedSessionCharacter(activeSession, memberKey) then
        return false, { outcome = "member_not_joined", error = "The timed-out transfer target is no longer joined." }
      end

      local queued, queuedCount, repairError, repairDetail = profileSyncMetaOps.queueAutomaticHostRepairForMember(
        activeSession,
        profileName,
        sessionId,
        memberKey,
        {
          mode = TrimText(transfer.mode) ~= "" and TrimText(transfer.mode) or "LIVE",
          reason = recoveryReason,
          sourceLabelOverride = "acknowledgement timeout recovery",
          domains = CloneCheckpointDomainList(transfer.scopeDomains),
          subdomains = CloneCheckpointSubdomainList(transfer.scopeSubdomains),
          forceAuthoritativeOverride = transfer.hostAuthoritativeOverride == true,
          forceFullSnapshot = transfer.hostAuthoritativeOverride == true
            and string.upper(TrimText(transfer.transferKind)) == "FULL",
          skipScopePrune = transfer.hostAuthoritativeOverride == true
            or TrimText(transfer.authoritativeArchiveScope) ~= "",
          authoritativeArchiveScope = TrimText(transfer.authoritativeArchiveScope),
          suppressUnchanged = transfer.hostAuthoritativeOverride ~= true
            and TrimText(transfer.authoritativeArchiveScope) == "",
          refreshEditor = false,
        }
      )
      local resolvedQueuedCount = math.max(0, tonumber(queuedCount) or 0)
      local outcome = "failed"
      if queued then
        if resolvedQueuedCount > 0 then
          outcome = "queued"
        elseif type(repairDetail) == "table" and repairDetail.deferredPatchState == true then
          outcome = "deferred"
        elseif type(repairDetail) == "table" and repairDetail.skippedAligned == true then
          outcome = "already_aligned"
        elseif type(repairDetail) == "table" and repairDetail.skippedMemberNewer == true then
          outcome = "member_newer"
        else
          outcome = "no_transfer_needed"
        end
      end
      transfer.ackTimeoutRecoverySucceeded = queued == true
      transfer.ackTimeoutRecoveryOutcome = outcome
      transfer.ackTimeoutRecoveryQueuedCount = resolvedQueuedCount
      transfer.ackTimeoutRecoveryError = TrimText(repairError)
      if type(profileSyncMetaOps.reconcileMemberArchiveTransactions) == "function" then
        profileSyncMetaOps.reconcileMemberArchiveTransactions(activeSession, memberKey)
      end
      if type(profileSyncMetaOps.markArchiveTransferState) == "function" then
        if outcome == "queued" or outcome == "deferred" then
          profileSyncMetaOps.markArchiveTransferState(transfer, "retrying", {
            error = TrimText(repairError),
          })
        elseif outcome ~= "already_aligned" and outcome ~= "no_transfer_needed" then
          profileSyncMetaOps.markArchiveTransferState(transfer, "failed", {
            error = FirstNonEmptyText(repairError, "Acknowledgement-timeout recovery did not queue a replacement transfer."),
          })
        end
      end
      if type(RecordProfileSyncDecision) == "function" then
        RecordProfileSyncDecision("reconcile_outbound_ack_timeout", {
          action = outcome,
          sessionId = sessionId,
          profileName = profileName,
          mode = "LIVE",
          reason = recoveryReason,
          target = memberKey,
          targetCount = 1,
          queuedCount = resolvedQueuedCount,
          transferKind = TrimText(transfer.transferKind),
          requestedDomains = CloneCheckpointDomainList(transfer.ackTimeoutRevalidationDomains),
          error = TrimText(repairError),
        })
      end
      if outcome == "queued" or outcome == "deferred" then
        profileSyncMetaOps.recordStandardRepairHistory("ack_timeout_recovery", "Queued acknowledgement-timeout recovery for " .. memberKey .. ".", {
          profileName = profileName,
          sessionId = sessionId,
          memberKey = memberKey,
          dedupeWindowSeconds = 20,
        })
      end
      return queued == true, {
        outcome = outcome,
        queuedCount = resolvedQueuedCount,
        error = TrimText(repairError),
        currentSectionChanged = type(repairDetail) == "table" and repairDetail.currentSectionChanged == true,
      }
    end

    local activeSession, activeProfileName = GetActiveLootSession()
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if not DoesActiveSessionMatch(activeSession, activeProfileName, sessionId, profileName) then
      return false, { outcome = "session_changed", error = "The timed-out transfer no longer belongs to the active session." }
    end
    if selfKey == "" or not AreCharacterKeysSame(activeSession.host or "", selfKey) then
      return false, { outcome = "not_host", error = "Only the active host can reconcile a timed-out transfer." }
    end
    if not IsJoinedSessionCharacter(activeSession, memberKey) then
      return false, { outcome = "member_not_joined", error = "The timed-out transfer target is no longer joined." }
    end
    if type(profileSyncMetaOps.canRetryArchiveTransfer) == "function" then
      local retryAllowed, retryReason = profileSyncMetaOps.canRetryArchiveTransfer(transfer)
      if retryAllowed == false then
        return false, {
          outcome = "retry_exhausted",
          error = retryReason == "archive_retry_exhausted"
            and "The archive scope reached its bounded retry limit."
            or "The archive scope cannot be retried.",
        }
      end
    end
    if type(profileSyncMetaOps.markArchiveTransferState) == "function" then
      profileSyncMetaOps.markArchiveTransferState(transfer, "retrying", {
        error = "Profile snapshot acknowledgement timed out; checksum revalidation and bounded repair started.",
      })
    end

    local revalidationDomains = CloneCheckpointDomainList(type(transfer.scopeDomains) == "table" and transfer.scopeDomains or nil)
    if #revalidationDomains == 0 and type(transfer.scopeSubdomains) == "table" then
      for _, subdomain in ipairs(transfer.scopeSubdomains) do
        local parentDomain = type(profileSyncMetaOps.getSubdomainParentDomain) == "function"
          and string.lower(TrimText(profileSyncMetaOps.getSubdomainParentDomain(subdomain)))
          or ""
        if parentDomain ~= "" and not HasComparedDomain(revalidationDomains, parentDomain) then
          revalidationDomains[#revalidationDomains + 1] = parentDomain
        end
      end
    end
    if #revalidationDomains == 0 or type(profileSyncMetaOps.sendSubchecksumRequests) ~= "function" then
      return FinishRecovery("outbound_ack_timeout_reconcile")
    end

    local revalidationNow = GetProfileCheckpointSyncTime()
    local revalidationDelaySeconds = math.max(0.1, tonumber(sessionConfig.ackTimeoutRevalidationDelaySeconds) or 1.5)
    PruneAgedSessionRuntimeTracking(revalidationNow)
    local revalidationKey = "ack_timeout_revalidation|" .. string.lower(sessionId) .. "|" .. string.lower(memberKey)
    local pendingRevalidation = sessionRuntime.pendingAckTimeoutRevalidations[revalidationKey]
    local revalidationCoalesced = type(pendingRevalidation) == "table"
    if not revalidationCoalesced then
      pendingRevalidation = {
        sessionId = sessionId,
        profileName = profileName,
        memberKey = memberKey,
        domains = CloneCheckpointDomainList(revalidationDomains),
        dispatchedDomains = {},
        requestedAt = revalidationNow,
        updatedAt = revalidationNow,
        lastDispatchAt = 0,
        recoveryDueAt = 0,
        transfers = {},
      }
      sessionRuntime.pendingAckTimeoutRevalidations[revalidationKey] = pendingRevalidation
    else
      pendingRevalidation.domains = MergeComparedDomains(pendingRevalidation.domains, revalidationDomains)
      pendingRevalidation.updatedAt = revalidationNow
    end
    pendingRevalidation.transfers = type(pendingRevalidation.transfers) == "table" and pendingRevalidation.transfers or {}
    pendingRevalidation.transfers[transferId] = transfer
    local requestedDomains = CloneCheckpointDomainList(pendingRevalidation.domains)
    pendingRevalidation.dispatchedDomains = CloneCheckpointDomainList(pendingRevalidation.dispatchedDomains)
    local dispatchDomains = profileSyncMetaOps.getUndispatchedAckTimeoutRevalidationDomains(
      requestedDomains,
      pendingRevalidation.dispatchedDomains
    )
    local suppressedDomainCount = math.max(0, #requestedDomains - #dispatchDomains)
    revalidationStats.lastSuppressedDomainCount = suppressedDomainCount
    if suppressedDomainCount > 0 then
      revalidationStats.suppressedDomainTotal = math.max(0, tonumber(revalidationStats.suppressedDomainTotal) or 0)
        + suppressedDomainCount
    end
    local requestedCount = 0
    if #dispatchDomains > 0 then
      requestedCount = profileSyncMetaOps.sendSubchecksumRequests(memberKey, dispatchDomains, {
        force = true,
        auto = true,
      })
      if math.max(0, tonumber(requestedCount) or 0) > 0 then
        pendingRevalidation.dispatchedDomains = MergeComparedDomains(
          pendingRevalidation.dispatchedDomains,
          dispatchDomains
        )
        pendingRevalidation.lastDispatchAt = revalidationNow
        pendingRevalidation.recoveryDueAt = revalidationNow + revalidationDelaySeconds
      end
    end
    if math.max(0, tonumber(requestedCount) or 0) <= 0 and not revalidationCoalesced then
      sessionRuntime.pendingAckTimeoutRevalidations[revalidationKey] = nil
      return FinishRecovery("outbound_ack_timeout_reconcile")
    end

    for _, pendingTransfer in pairs(pendingRevalidation.transfers) do
      if type(pendingTransfer) == "table" and TrimText(pendingTransfer.state) == "ack_timeout" then
        pendingTransfer.ackTimeoutRevalidationRequestedAt = math.max(0, tonumber(pendingRevalidation.lastDispatchAt) or 0)
        pendingTransfer.ackTimeoutRevalidationDueAt = math.max(0, tonumber(pendingRevalidation.recoveryDueAt) or 0)
        pendingTransfer.ackTimeoutRevalidationDomains = CloneCheckpointDomainList(requestedDomains)
        pendingTransfer.ackTimeoutRevalidationKey = revalidationKey
        pendingTransfer.ackTimeoutRevalidationCoalesced = revalidationCoalesced == true
        pendingTransfer.ackTimeoutRecoverySucceeded = true
        pendingTransfer.ackTimeoutRecoveryOutcome = "revalidation_pending"
        pendingTransfer.ackTimeoutRecoveryQueuedCount = 0
        pendingTransfer.ackTimeoutRecoveryError = ""
      end
    end
    if type(RecordProfileSyncDecision) == "function" then
      RecordProfileSyncDecision("reconcile_outbound_ack_timeout", {
        action = revalidationCoalesced and "revalidation_coalesced" or "revalidation_requested",
        sessionId = sessionId,
        profileName = profileName,
        mode = "LIVE",
        reason = "outbound_ack_timeout_revalidate",
        target = memberKey,
        targetCount = 1,
        queuedCount = math.max(0, tonumber(requestedCount) or 0),
        transferKind = TrimText(transfer.transferKind),
        requestedDomains = CloneCheckpointDomainList(dispatchDomains),
      })
    end

    local function ClearCompletedRevalidation()
      if sessionRuntime.pendingAckTimeoutRevalidations[revalidationKey] == pendingRevalidation then
        sessionRuntime.pendingAckTimeoutRevalidations[revalidationKey] = nil
      end
    end

    local function ForEachTimedOutPendingTransfer(callback)
      for _, pendingTransfer in pairs(pendingRevalidation.transfers) do
        if type(pendingTransfer) == "table" and TrimText(pendingTransfer.state) == "ack_timeout" then
          callback(pendingTransfer)
        end
      end
    end

    local function MirrorSharedRecoveryOutcome(sourceTransfer)
      ForEachTimedOutPendingTransfer(function(pendingTransfer)
        if pendingTransfer ~= sourceTransfer then
          pendingTransfer.ackTimeoutRecoverySucceeded = sourceTransfer.ackTimeoutRecoverySucceeded == true
          pendingTransfer.ackTimeoutRecoveryOutcome = TrimText(sourceTransfer.ackTimeoutRecoveryOutcome)
          pendingTransfer.ackTimeoutRecoveryQueuedCount = math.max(0, tonumber(sourceTransfer.ackTimeoutRecoveryQueuedCount) or 0)
          pendingTransfer.ackTimeoutRecoveryError = TrimText(sourceTransfer.ackTimeoutRecoveryError)
          pendingTransfer.ackTimeoutRevalidationFresh = sourceTransfer.ackTimeoutRevalidationFresh
          pendingTransfer.ackTimeoutRevalidationLoadedCount = math.max(0, tonumber(sourceTransfer.ackTimeoutRevalidationLoadedCount) or 0)
          pendingTransfer.ackTimeoutRevalidationFreshCount = math.max(0, tonumber(sourceTransfer.ackTimeoutRevalidationFreshCount) or 0)
        end
      end)
    end

    local function MarkSharedRecoveryError(message)
      ForEachTimedOutPendingTransfer(function(pendingTransfer)
        pendingTransfer.ackTimeoutRecoverySucceeded = false
        pendingTransfer.ackTimeoutRecoveryOutcome = "recovery_error"
        pendingTransfer.ackTimeoutRecoveryQueuedCount = 0
        pendingTransfer.ackTimeoutRecoveryError = tostring(message or "Acknowledgement timeout callback failed.")
      end)
    end

    local function RunRevalidatedRecovery()
      local freshness = nil
      if type(profileSyncMetaOps.getMemberSubchecksumFreshness) == "function" then
        local freshnessOk, freshnessResult = pcall(
          profileSyncMetaOps.getMemberSubchecksumFreshness,
          sessionId,
          memberKey,
          transfer.ackTimeoutRevalidationDomains,
          transfer.ackTimeoutRevalidationRequestedAt
        )
        if freshnessOk and type(freshnessResult) == "table" then
          freshness = freshnessResult
        elseif not freshnessOk and TrimText(transfer.state) == "ack_timeout" then
          transfer.ackTimeoutRevalidationFresh = false
          transfer.ackTimeoutRecoveryError = "Checksum freshness check failed: " .. tostring(freshnessResult or "unknown error")
        end
      end
      if type(freshness) == "table" then
        transfer.ackTimeoutRevalidationFresh = freshness.fresh == true
        transfer.ackTimeoutRevalidationLoadedCount = math.max(0, tonumber(freshness.loadedCount) or 0)
        transfer.ackTimeoutRevalidationFreshCount = math.max(0, tonumber(freshness.freshCount) or 0)
      end
      if type(RecordProfileSyncDecision) == "function" and type(freshness) == "table" and freshness.fresh ~= true then
        RecordProfileSyncDecision("reconcile_outbound_ack_timeout", {
          action = "revalidation_unconfirmed",
          sessionId = sessionId,
          profileName = profileName,
          mode = "LIVE",
          reason = "outbound_ack_timeout_revalidate",
          target = memberKey,
          targetCount = 1,
          queuedCount = 0,
          transferKind = TrimText(transfer.transferKind),
          requestedDomains = CloneCheckpointDomainList(transfer.ackTimeoutRevalidationDomains),
          error = "Checksum revalidation did not receive a fresh response before recovery.",
        })
      end
      local recovered, queued, detail = pcall(FinishRecovery, "outbound_ack_timeout_reconcile")
      if recovered then
        return queued, detail
      end
      if TrimText(transfer.state) == "ack_timeout" then
        transfer.ackTimeoutRecoverySucceeded = false
        transfer.ackTimeoutRecoveryOutcome = "recovery_error"
        transfer.ackTimeoutRecoveryQueuedCount = 0
        transfer.ackTimeoutRecoveryError = tostring(queued or "Host reconciliation failed.")
      end
      return false, { outcome = "recovery_error", error = tostring(queued or "Host reconciliation failed.") }
    end

    local function RunCoalescedRevalidatedRecovery()
      local recoveryTransfer = nil
      local sharedTransferCount = 0
      ForEachTimedOutPendingTransfer(function(pendingTransfer)
        sharedTransferCount = sharedTransferCount + 1
        if recoveryTransfer == nil then
          recoveryTransfer = pendingTransfer
        end
      end)
      if recoveryTransfer == nil then
        return true, { outcome = "no_longer_timed_out" }
      end

      local originalTransfer = transfer
      transfer = recoveryTransfer
      local runOk, queued, detail = pcall(RunRevalidatedRecovery)
      transfer = originalTransfer
      if not runOk then
        error(queued)
      end
      MirrorSharedRecoveryOutcome(recoveryTransfer)
      revalidationStats.lastSharedRecoveryTransferCount = sharedTransferCount
      if sharedTransferCount > 1 then
        revalidationStats.sharedRecoveryBatchTotal = math.max(0, tonumber(revalidationStats.sharedRecoveryBatchTotal) or 0) + 1
        revalidationStats.sharedRecoveryTransferTotal = math.max(0, tonumber(revalidationStats.sharedRecoveryTransferTotal) or 0)
          + sharedTransferCount
        revalidationStats.lastSharedRecoveryTransferCount = sharedTransferCount
      end
      return queued, detail
    end

    if type(Compat) == "table" and type(Compat.After) == "function" then
      local scheduleRecovery = profileSyncMetaOps.shouldScheduleAckTimeoutRevalidationRecovery(pendingRevalidation)
      if scheduleRecovery then
        pendingRevalidation.recoveryScheduled = true
        local function RunScheduledRevalidationRecovery()
          local remainingDelay = math.max(0, tonumber(pendingRevalidation.recoveryDueAt) or 0) - GetProfileCheckpointSyncTime()
          if remainingDelay > 0.01 then
            Compat.After(math.max(0.01, remainingDelay), RunScheduledRevalidationRecovery)
            return
          end
          local callbackOk, callbackError = pcall(RunCoalescedRevalidatedRecovery)
          ClearCompletedRevalidation()
          if not callbackOk then
            MarkSharedRecoveryError(callbackError)
          end
        end
        Compat.After(revalidationDelaySeconds, RunScheduledRevalidationRecovery)
      else
        revalidationStats.coalescedRecoveryCallbackTotal = math.max(0, tonumber(revalidationStats.coalescedRecoveryCallbackTotal) or 0) + 1
      end
      return true, {
        outcome = "revalidation_pending",
        queuedCount = 0,
        requestedCount = math.max(0, tonumber(requestedCount) or 0),
        coalesced = revalidationCoalesced == true or not scheduleRecovery,
        recoveryCoalesced = not scheduleRecovery,
      }
    end
    local queued, detail = RunCoalescedRevalidatedRecovery()
    ClearCompletedRevalidation()
    return queued, detail
  end

  profileSyncMetaOps.buildMissingMemberBootstrapRequestState = function(profileName, sessionId, memberKey, currentSessionSubdomains, essentialLootSubdomains, deferredLootSubdomains, deferredSessionArchiveSubdomains)
    local resolvedSessionId = TrimText(sessionId)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    return string.lower(resolvedSessionId) .. "|" .. string.lower(resolvedMemberKey), table.concat({
      TrimText(profileName),
      table.concat(CloneCheckpointDomainList(sessionConfig.profileBootstrapDomains), "\30"),
      table.concat(CloneCheckpointSubdomainList(currentSessionSubdomains), "\30"),
      table.concat(CloneCheckpointSubdomainList(essentialLootSubdomains), "\30"),
      table.concat(CloneCheckpointSubdomainList(deferredLootSubdomains), "\30"),
      table.concat(CloneCheckpointSubdomainList(deferredSessionArchiveSubdomains), "\30"),
    }, "\31")
  end

  profileSyncMetaOps.getRecentMissingMemberBootstrapRequestState = function(bootstrapRequestKey, bootstrapRequestSignature, now)
    local recentBootstrapRequest = sessionRuntime.recentMissingMemberBootstrapRequests[bootstrapRequestKey]
    if type(recentBootstrapRequest) == "table" then
      local recentQueuedAt = math.max(0, tonumber(recentBootstrapRequest.queuedAt) or 0)
      if recentQueuedAt <= 0
        or (now - recentQueuedAt) >= sessionConfig.missingMemberBootstrapRetentionSeconds
      then
        sessionRuntime.recentMissingMemberBootstrapRequests[bootstrapRequestKey] = nil
        recentBootstrapRequest = nil
      end
    end
    if type(recentBootstrapRequest) == "table"
      and TrimText(recentBootstrapRequest.signature) == TrimText(bootstrapRequestSignature)
      and (now - math.max(0, tonumber(recentBootstrapRequest.queuedAt) or 0)) < sessionConfig.missingMemberBootstrapDedupeSeconds
    then
      return {
        deduped = true,
        queuedBackgroundAny = recentBootstrapRequest.queuedBackgroundAny == true,
      }
    end
    return nil
  end

  profileSyncMetaOps.rememberRecentMissingMemberBootstrapRequestState = function(bootstrapRequestKey, bootstrapRequestSignature, now, queuedBackgroundAny)
    sessionRuntime.recentMissingMemberBootstrapRequests[bootstrapRequestKey] = {
      signature = bootstrapRequestSignature,
      queuedAt = now,
      queuedBackgroundAny = queuedBackgroundAny == true,
    }
  end

  profileSyncMetaOps.splitDeferredMissingMemberLootSubdomains = function(deferredLootSubdomains)
    local deferredLootStatsSubdomains = {}
    local deferredLootArchiveSubdomains = {}
    for _, subdomain in ipairs(type(deferredLootSubdomains) == "table" and deferredLootSubdomains or {}) do
      local resolvedSubdomain = string.lower(TrimText(subdomain))
      if resolvedSubdomain == "lrsr"
        or resolvedSubdomain == "lrsv"
        or resolvedSubdomain:find("^lre:", 1, false)
        or resolvedSubdomain:find("^lve:", 1, false) then
        deferredLootStatsSubdomains[#deferredLootStatsSubdomains + 1] = subdomain
      else
        deferredLootArchiveSubdomains[#deferredLootArchiveSubdomains + 1] = subdomain
      end
    end
    return deferredLootStatsSubdomains, deferredLootArchiveSubdomains
  end

  profileSyncMetaOps.splitDeferredMissingMemberSessionSubdomains = function(deferredSessionSubdomains)
    local itemHistorySubdomains = {}
    local sessionHistorySubdomains = {}
    for _, subdomain in ipairs(type(deferredSessionSubdomains) == "table" and deferredSessionSubdomains or {}) do
      local resolvedSubdomain = string.lower(TrimText(subdomain))
      if resolvedSubdomain:find("^slb:", 1, false) then
        itemHistorySubdomains[#itemHistorySubdomains + 1] = subdomain
      elseif resolvedSubdomain:find("^ssr:", 1, false) then
        sessionHistorySubdomains[#sessionHistorySubdomains + 1] = subdomain
      end
    end
    return CloneCheckpointSubdomainList(itemHistorySubdomains), CloneCheckpointSubdomainList(sessionHistorySubdomains)
  end

  profileSyncMetaOps.resolveAuthoritativeArchiveScope = function(subdomains)
    local resolvedScope = ""
    local foundAny = false
    for _, subdomain in ipairs(type(subdomains) == "table" and subdomains or {}) do
      local value = string.lower(TrimText(subdomain))
      local scope = ""
      if value:find("^llr:", 1, false) or value:find("^lmr:", 1, false) then
        scope = "LOOT_LIST"
      elseif value:find("^ssr:", 1, false) then
        scope = "SESSION_HISTORY"
      elseif value == "lrsr" or value == "lrsv"
        or value:find("^lre:", 1, false) or value:find("^lve:", 1, false) then
        scope = "FUN_AWARDS"
      end
      if scope == "" or (resolvedScope ~= "" and resolvedScope ~= scope) then
        return ""
      end
      resolvedScope = scope
      foundAny = true
    end
    return foundAny and resolvedScope or ""
  end

  profileSyncMetaOps.queueMissingMemberBootstrapSnapshotScope = function(activeSession, profileName, sessionId, memberKey, mode, reason, domains, subdomains, opts)
    opts = type(opts) == "table" and opts or {}
    local resolvedSessionId = TrimText(TrimText(opts.resolvedSessionId) ~= "" and opts.resolvedSessionId or sessionId)
    local resolvedMemberKey = NormalizeCharacterKey(TrimText(opts.resolvedMemberKey) ~= "" and opts.resolvedMemberKey or memberKey)
    local requestedDomains = CloneCheckpointDomainList(domains)
    local requestedSubdomains = CloneCheckpointSubdomainList(subdomains)
    local authoritativeArchiveScope = string.upper(TrimText(opts.authoritativeArchiveScope))
    if authoritativeArchiveScope ~= "FUN_AWARDS" then
      authoritativeArchiveScope = ""
    end
    local requestedScope = ClassifyRequestedRepairScope(
      requestedDomains,
      requestedSubdomains,
      #requestedSubdomains > 0 and "precise" or (#requestedDomains > 0 and "targeted" or "same")
    )
    local coalesceExistingRepair, requestState, _, coalescedRepairReason
    if authoritativeArchiveScope == "" then
      coalesceExistingRepair, requestState, _, coalescedRepairReason = EvaluateRecentMemberRepairRequest(
        activeSession,
        profileName,
        sessionId,
        memberKey,
        requestedDomains,
        requestedSubdomains,
        {
          mode = mode,
        }
      )
    end
    if coalesceExistingRepair then
      if type(RecordProfileSyncDecision) == "function" then
        RecordProfileSyncDecision("queue_missing_member_bootstrap_scope", {
          action = "coalesced_existing_repair",
          sessionId = resolvedSessionId,
          profileName = TrimText(profileName),
          mode = mode,
          reason = reason,
          target = resolvedMemberKey,
          targetCount = resolvedMemberKey ~= "" and 1 or 0,
          queuedCount = 0,
          requestedDomains = CloneCheckpointDomainList(requestedDomains),
          requestedSubdomains = CloneCheckpointSubdomainList(requestedSubdomains),
          requestedScope = requestedScope,
          coalescedReason = TrimText(coalescedRepairReason),
        })
      end
      return true, 0, nil, {
        coalescedExistingRepair = true,
        coalescedRepairReason = TrimText(coalescedRepairReason),
      }
    end

    local preparedSnapshot, prepareError = PrepareProfileSnapshotTransfer(profileName, {
      domains = #requestedDomains > 0 and requestedDomains or nil,
      subdomains = #requestedSubdomains > 0 and requestedSubdomains or nil,
      authoritativeArchiveScope = authoritativeArchiveScope,
    })
    if type(preparedSnapshot) ~= "table" then
      if type(RecordProfileSyncDecision) == "function" then
        RecordProfileSyncDecision("queue_missing_member_bootstrap_scope", {
          action = "prepare_failed",
          sessionId = resolvedSessionId,
          profileName = TrimText(profileName),
          mode = mode,
          reason = reason,
          target = resolvedMemberKey,
          targetCount = resolvedMemberKey ~= "" and 1 or 0,
          queuedCount = 0,
          requestedDomains = CloneCheckpointDomainList(requestedDomains),
          requestedSubdomains = CloneCheckpointSubdomainList(requestedSubdomains),
          requestedScope = requestedScope,
          error = prepareError,
        })
      end
      return false, 0, prepareError
    end
    if opts.forbidFullSnapshotFallback == true and preparedSnapshot.fullSnapshotFallback == true then
      return false, 0, "precise_snapshot_unavailable"
    end
    if type(requestState) == "table" and preparedSnapshot.fullSnapshotFallback == true then
      requestState.forceFullSnapshot = true
      requestState.transportSignature = table.concat({
        TrimText(requestState.localRevisionSignature),
        TrimText(requestState.memberStateSignature),
        string.upper(TrimText(requestState.mode)),
        "1",
        BuildNormalizedRepairListSignature(requestState.domains),
        BuildNormalizedRepairListSignature(requestState.subdomains),
      }, "\31")
    end

    local queuedSnapshot, queuedCountOrError = QueueProfileSnapshotForMember(profileName, sessionId, memberKey, {
      mode = mode,
      reason = reason,
      domains = #requestedDomains > 0 and requestedDomains or nil,
      subdomains = #requestedSubdomains > 0 and requestedSubdomains or nil,
      preparedSnapshot = preparedSnapshot,
      authoritativeArchiveScope = authoritativeArchiveScope,
    })
    if not queuedSnapshot then
      if type(RecordProfileSyncDecision) == "function" then
        RecordProfileSyncDecision("queue_missing_member_bootstrap_scope", {
          action = "failed",
          sessionId = resolvedSessionId,
          profileName = TrimText(profileName),
          mode = mode,
          reason = reason,
          target = resolvedMemberKey,
          targetCount = resolvedMemberKey ~= "" and 1 or 0,
          queuedCount = 0,
          requestedDomains = CloneCheckpointDomainList(requestedDomains),
          requestedSubdomains = CloneCheckpointSubdomainList(requestedSubdomains),
          requestedScope = requestedScope,
          error = queuedCountOrError,
        })
      end
      return false, 0, queuedCountOrError
    end

    local resolvedQueuedCount = math.max(1, tonumber(queuedCountOrError) or 1)
    RememberRecentMemberRepairRequestState(resolvedSessionId, resolvedMemberKey, requestState)
    if type(RecordProfileSyncDecision) == "function" then
      RecordProfileSyncDecision("queue_missing_member_bootstrap_scope", {
        action = "queued",
        sessionId = resolvedSessionId,
        profileName = TrimText(profileName),
        mode = mode,
        reason = reason,
        target = resolvedMemberKey,
        targetCount = resolvedMemberKey ~= "" and 1 or 0,
        queuedCount = resolvedQueuedCount,
        requestedDomains = CloneCheckpointDomainList(requestedDomains),
        requestedSubdomains = CloneCheckpointSubdomainList(requestedSubdomains),
        requestedScope = requestedScope,
        fullSnapshotFallback = preparedSnapshot.fullSnapshotFallback == true,
      })
    end
    return true, resolvedQueuedCount, nil, {
      coalescedExistingRepair = false,
      fullSnapshotFallback = preparedSnapshot.fullSnapshotFallback == true,
    }
  end

  profileSyncMetaOps.queueLatestSessionHistoryCatchup = function(
    activeSession,
    profileName,
    sessionId,
    memberKey,
    member,
    reason,
    opts
  )
    opts = type(opts) == "table" and opts or {}
    if type(activeSession) ~= "table" or type(member) ~= "table" then
      return false, 0, "invalid_context"
    end
    local resolvedSessionId = TrimText(sessionId)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    local expectedChecksums = profileSyncMetaOps.buildSessionArchiveScopeChecksums(profileName, activeSession)
    local expectedChecksum = TrimText(type(expectedChecksums) == "table" and expectedChecksums.sessionHistory or "")
    local memberChecksum = TrimText(member.sessionHistoryArchiveChecksum)
    local latestSubdomain, latestSession = profileSyncMetaOps.buildLatestCompletedSessionHistorySubdomain(
      profileName,
      activeSession
    )
    local latestSessionId = TrimText(type(latestSession) == "table" and latestSession.id or "")
    local catchupKey = string.lower(resolvedSessionId)
      .. "|" .. string.lower(resolvedMemberKey)
      .. "|" .. string.lower(latestSessionId)
      .. "|" .. string.lower(expectedChecksum)
    local previousState = catchupKey ~= "|||" and sessionRuntime.latestSessionHistoryCatchups[catchupKey] or nil
    local action = INTERNAL_API.LIDCOUNCIL_ResolveLatestSessionHistoryCatchupAttempt_Impl({
      expectedChecksum = expectedChecksum,
      memberChecksum = memberChecksum,
      latestSessionId = latestSessionId,
      attempts = type(previousState) == "table" and previousState.attempts or 0,
      startRetry = opts.startRetry == true,
    })
    if action == "aligned" or action == "missing_proof" then
      return false, 0, action
    end
    if action == "no_completed_session" then
      return true, 0, action
    end
    if action == "suppress_duplicate" or action == "suppress_exhausted" then
      return true, 0, action
    end
    if latestSubdomain == "" or resolvedSessionId == "" or resolvedMemberKey == "" then
      return false, 0, "missing_latest_session_identity"
    end

    local queued, queuedCount, queueError = profileSyncMetaOps.queueMissingMemberBootstrapSnapshotScope(
      activeSession,
      profileName,
      resolvedSessionId,
      resolvedMemberKey,
      "BACKGROUND",
      FirstNonEmptyText(reason, "latest_session_history_catchup"),
      nil,
      { latestSubdomain },
      {
        resolvedSessionId = resolvedSessionId,
        resolvedMemberKey = resolvedMemberKey,
        forbidFullSnapshotFallback = true,
      }
    )
    if not queued then
      -- A known Session History mismatch must remain yellow/manual if its one
      -- exact leaf cannot be prepared; never broaden this policy into an
      -- automatic domain or full-profile transfer.
      return true, 0, queueError or "queue_failed"
    end
    sessionRuntime.latestSessionHistoryCatchups[catchupKey] = {
      attempts = math.max(0, tonumber(type(previousState) == "table" and previousState.attempts or 0) or 0) + 1,
      latestSessionId = latestSessionId,
      latestSubdomain = latestSubdomain,
      expectedChecksum = expectedChecksum,
      memberChecksum = memberChecksum,
      queuedAt = GetProfileCheckpointSyncTime(),
      action = action,
    }
    if type(RecordProfileSyncDecision) == "function" then
      RecordProfileSyncDecision("latest_session_history_catchup", {
        action = action,
        sessionId = resolvedSessionId,
        profileName = TrimText(profileName),
        mode = "BACKGROUND",
        reason = FirstNonEmptyText(reason, "latest_session_history_catchup"),
        target = resolvedMemberKey,
        targetCount = 1,
        queuedCount = math.max(0, tonumber(queuedCount) or 0),
        requestedSubdomains = { latestSubdomain },
        requestedScope = "precise",
      })
    end
    return true, math.max(0, tonumber(queuedCount) or 0), action
  end

  local function QueueMissingMemberBootstrapSync(profileName, sessionId, memberKey)
    local resolvedSessionId = TrimText(sessionId)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    PruneAgedSessionRuntimeTracking(GetProfileCheckpointSyncTime())
    local activeSession, activeProfileName = GetActiveLootSession()
    if not DoesActiveSessionMatch(activeSession, activeProfileName, resolvedSessionId, profileName) then
      activeSession = nil
    end
    local currentSessionSubdomains = profileSyncMetaOps.buildCurrentSessionCheckpointSubdomains(resolvedSessionId)
    local essentialLootSubdomains, deferredLootSubdomains = profileSyncMetaOps.buildFreshMemberLootSubdomainPlan(
      profileName,
      activeSession
    )
    local deferredSessionArchiveSubdomains = profileSyncMetaOps.buildFreshMemberSessionArchiveSubdomains(
      profileName,
      resolvedSessionId
    )
    local bootstrapRequestKey, bootstrapRequestSignature = profileSyncMetaOps.buildMissingMemberBootstrapRequestState(
      profileName,
      resolvedSessionId,
      resolvedMemberKey,
      currentSessionSubdomains,
      essentialLootSubdomains,
      deferredLootSubdomains,
      deferredSessionArchiveSubdomains
    )
    local now = GetProfileCheckpointSyncTime()
    local recentBootstrapDetail = profileSyncMetaOps.getRecentMissingMemberBootstrapRequestState(
      bootstrapRequestKey,
      bootstrapRequestSignature,
      now
    )
    if type(recentBootstrapDetail) == "table" then
      return true, recentBootstrapDetail.queuedBackgroundAny == true, nil, recentBootstrapDetail
    end

    local queuedTransferCount = 0
    local coalescedAny = false
    local queuedBootstrap, queuedBootstrapCount, queueBootstrapError, bootstrapQueueDetail = profileSyncMetaOps.queueMissingMemberBootstrapSnapshotScope(
      activeSession,
      profileName,
      resolvedSessionId,
      resolvedMemberKey,
      "LIVE",
      "missing_member_bootstrap",
      sessionConfig.profileBootstrapDomains,
      nil,
      {
        resolvedSessionId = resolvedSessionId,
        resolvedMemberKey = resolvedMemberKey,
      }
    )
    queuedTransferCount = queuedTransferCount + math.max(0, tonumber(queuedBootstrapCount) or 0)
    coalescedAny = coalescedAny or (type(bootstrapQueueDetail) == "table" and bootstrapQueueDetail.coalescedExistingRepair == true)
    if not queuedBootstrap then
      return false, false, queueBootstrapError
    end

    local queuedBackgroundAny = false
    local lastBackgroundError = nil
    if #currentSessionSubdomains > 0 then
      local queuedSessionBackground, queuedSessionBackgroundCount, queueSessionBackgroundError, sessionBackgroundDetail = profileSyncMetaOps.queueMissingMemberBootstrapSnapshotScope(
        activeSession,
        profileName,
        resolvedSessionId,
        resolvedMemberKey,
        "BACKGROUND",
        "missing_member_current_session_sync",
        { "session" },
        currentSessionSubdomains,
        {
          resolvedSessionId = resolvedSessionId,
          resolvedMemberKey = resolvedMemberKey,
        }
      )
      queuedTransferCount = queuedTransferCount + math.max(0, tonumber(queuedSessionBackgroundCount) or 0)
      coalescedAny = coalescedAny or (type(sessionBackgroundDetail) == "table" and sessionBackgroundDetail.coalescedExistingRepair == true)
      if queuedSessionBackground then
        queuedBackgroundAny = true
      else
        lastBackgroundError = queueSessionBackgroundError
      end
    end

    if #essentialLootSubdomains > 0 then
      local queuedEssentialLoot, queuedEssentialLootCount, queueEssentialLootError, essentialLootDetail = profileSyncMetaOps.queueMissingMemberBootstrapSnapshotScope(
        activeSession,
        profileName,
        resolvedSessionId,
        resolvedMemberKey,
        "LIVE",
        "missing_member_loot_bootstrap",
        { "loot" },
        essentialLootSubdomains,
        {
          resolvedSessionId = resolvedSessionId,
          resolvedMemberKey = resolvedMemberKey,
        }
      )
      queuedTransferCount = queuedTransferCount + math.max(0, tonumber(queuedEssentialLootCount) or 0)
      coalescedAny = coalescedAny or (type(essentialLootDetail) == "table" and essentialLootDetail.coalescedExistingRepair == true)
      if queuedEssentialLoot then
        queuedBackgroundAny = true
      else
        lastBackgroundError = queueEssentialLootError
      end
    end

    local deferredLootStatsSubdomains, deferredLootArchiveSubdomains = profileSyncMetaOps.splitDeferredMissingMemberLootSubdomains(
      deferredLootSubdomains
    )
    local deferredItemHistorySubdomains, deferredSessionHistorySubdomains = profileSyncMetaOps.splitDeferredMissingMemberSessionSubdomains(
      deferredSessionArchiveSubdomains
    )
    local archiveScopePlans = {
      { scope = "lootList", subdomains = deferredLootArchiveSubdomains },
      { scope = "itemHistory", subdomains = deferredItemHistorySubdomains },
      { scope = "sessionHistory", subdomains = deferredSessionHistorySubdomains },
      { scope = "funAwards", subdomains = deferredLootStatsSubdomains },
    }
    for _, scopePlan in ipairs(archiveScopePlans) do
      if #scopePlan.subdomains > 0 or scopePlan.scope == "funAwards" then
        local scheduledScope, scheduleScopeError = ScheduleDeferredMissingMemberArchiveScope(
          profileName,
          sessionId,
          memberKey,
          scopePlan.scope,
          scopePlan.subdomains
        )
        if scheduledScope then
          queuedBackgroundAny = true
        elseif TrimText(scheduleScopeError) ~= "" then
          lastBackgroundError = scheduleScopeError
        end
      end
    end

    profileSyncMetaOps.rememberRecentMissingMemberBootstrapRequestState(
      bootstrapRequestKey,
      bootstrapRequestSignature,
      now,
      queuedBackgroundAny
    )
    return true, queuedBackgroundAny, lastBackgroundError, {
      deduped = queuedTransferCount <= 0
        and coalescedAny == true
        and TrimText(lastBackgroundError) == "",
      queuedBackgroundAny = queuedBackgroundAny == true,
      coalescedExistingRepair = coalescedAny == true
        or (type(bootstrapQueueDetail) == "table" and bootstrapQueueDetail.coalescedExistingRepair == true),
      queuedTransferCount = queuedTransferCount,
    }
  end

  local function BuildStartSessionSyncWarning(candidates)
    local summary = {
      joined = 0,
      aligned = 0,
      rollReady = 0,
      bootstrapPending = 0,
      bootstrapReview = 0,
      lineageMismatch = 0,
      notAligned = 0,
    }

    for _, candidate in ipairs(type(candidates) == "table" and candidates or {}) do
      summary.joined = summary.joined + 1
      local comparison = string.lower(TrimText(candidate.effectiveComparison ~= "" and candidate.effectiveComparison or candidate.comparison))
      local bootstrapState = string.lower(TrimText(candidate.bootstrapState))
      if comparison == "same" then
        summary.aligned = summary.aligned + 1
      else
        summary.notAligned = summary.notAligned + 1
      end
      if bootstrapState == "ready" then
        summary.rollReady = summary.rollReady + 1
      elseif bootstrapState == "review" then
        summary.bootstrapReview = summary.bootstrapReview + 1
      elseif bootstrapState == "lineage" then
        summary.bootstrapReview = summary.bootstrapReview + 1
        summary.lineageMismatch = summary.lineageMismatch + 1
      else
        summary.bootstrapPending = summary.bootstrapPending + 1
      end
    end

    local lines = {}
    local requiresBootstrapWait = summary.bootstrapPending > 0 or summary.bootstrapReview > 0
    if summary.joined > 0 and requiresBootstrapWait then
      lines[#lines + 1] = "Roll-ready joined members: "
        .. tostring(summary.rollReady) .. " / " .. tostring(summary.joined) .. "."
      if summary.bootstrapPending > 0 then
        lines[#lines + 1] = tostring(summary.bootstrapPending)
          .. " joined member bootstrap cop" .. (summary.bootstrapPending == 1 and "y is" or "ies are")
          .. " still pending. Those players may not receive the roll popup yet."
      end
      if summary.bootstrapReview > 0 then
        lines[#lines + 1] = tostring(summary.bootstrapReview)
          .. " joined member bootstrap cop" .. (summary.bootstrapReview == 1 and "y needs" or "ies need")
          .. " review before trusting roll choices."
      end
      if summary.notAligned > 0 then
        lines[#lines + 1] = tostring(summary.notAligned)
          .. " joined member profile cop" .. (summary.notAligned == 1 and "y is" or "ies are")
          .. " still not fully aligned. Remaining loot and session history can keep syncing in the background after Start Session."
      end
    end

    return summary, lines
  end

  local function ExtendProfileSnapshotJoinGrace(sessionId, profileName, seconds, reason)
    if type(profileSyncMetaOps.delaySnapshotBatchForJoins) ~= "function" then
      return false
    end
    return profileSyncMetaOps.delaySnapshotBatchForJoins(sessionId, seconds, reason, profileName)
  end

  INTERNAL_API.LIDCOUNCIL_HasJoinedActiveLootSession_Impl = function()
    local activeSession, profileName = GetActiveLootSession()
    if not activeSession or not profileName then
      return false, nil, nil
    end
    if not IsLiveSession(activeSession) then
      return false, nil, nil
    end
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if selfKey == "" then
      return false, nil, nil
    end
    if not IsJoinedSessionCharacter(activeSession, selfKey) then
      return false, nil, nil
    end
    return true, activeSession, profileName
  end

  INTERNAL_API.LIDCOUNCIL_StartLootSessionFlow_Impl = function(profileName)
    local blocked, blockedMessage = RejectCombatLockedAction("Prepare Session")
    if blocked then
      return false, blockedMessage
    end

    -- Create the host member record with Auto Pass already disabled.
    SetLocalAutoPassEnabled(false)
    local session, err = deps.StartLootSession(profileName)
    if not session then
      if err then
        Print(tostring(err))
      end
      return false, err
    end

    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if selfKey ~= "" then
      UpsertLootSessionMember(session.profileName, session.id, selfKey, {
        localAutoPassEnabled = false,
      })
      RefreshHostSessionMemberState(session.profileName, session.id, {
        suppressCheckpoint = true,
      })
    end
    ExtendProfileSnapshotJoinGrace(session.id, session.profileName, sessionConfig.prepareJoinGraceSeconds, "prepare_session")
    optionalApiOps.beginProfileSnapshotDiagnosticsForSession(session.id, session.startedAt)

    optionalApiOps.clearLiveLootRuntime()
    local distribution = deps.GetGroupDistribution()
    if distribution then
      local inviteTargets = {}
      for _, memberKey in ipairs(deps.CollectGroupCharacterKeys()) do
        if memberKey ~= "" and not AreCharacterKeysSame(memberKey, selfKey) then
          inviteTargets[#inviteTargets + 1] = memberKey
        end
      end
      local queued, sendError = SendComm(
        "START",
        distribution,
        nil,
        session.id,
        session.profileName,
        TrimText(select(1, deps.GetLootProfileId(session.profileName)) or ""),
        session.host,
        session.startedAt,
        deps.GetLootProfileMaster(session.profileName),
        GetCommProtocolMarker(),
        session.status or "PREPARING"
      )
      for _, memberKey in ipairs(inviteTargets) do
        sessionLifecycleOps.beginInviteDelivery(session, memberKey, queued, sendError)
      end
      if queued == true and #inviteTargets > 0 then
        Print(sessionLifecycleOps.buildFlowNoticeText("invite_broadcast_queued", {
          targetCount = #inviteTargets,
        }))
      elseif queued ~= true and #inviteTargets > 0 then
        Print("Could not queue the session announcement: " .. tostring(sendError or "unknown send error") .. ".")
      end
    end
    sessionLifecycleOps.emitTransitionStateNotice(session.id, session.profileName, "prepared", {
      profileName = session.profileName,
      hasDistribution = distribution ~= nil,
      sender = selfKey,
      refreshEditor = false,
    })
    Print("As session host, your personal Auto Pass starts OFF by default. Joined members start with personal Auto Pass ON and can change it any time in Session -> Auto Pass Setting.")
    sessionUiOps.refreshPanelsAndLiveBoard()
    return true, session
  end

  INTERNAL_API.LIDCOUNCIL_SendActiveSessionInviteFlow_Impl = function()
    local activeSession, profileName = GetActiveLootSession()
    if not activeSession or not profileName then
      Print("No active loot session.")
      return false, "No active session."
    end

    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if not AreCharacterKeysSame(activeSession.host or "", selfKey) then
      Print("Only the loot session host can send session invites.")
      return false, "Only the host can send session invites."
    end

    local blocked, blockedMessage = RejectCombatLockedAction("Send Session Invite")
    if blocked then
      return false, blockedMessage
    end

    local distribution = deps.GetGroupDistribution()
    if not distribution then
      Print(sessionLifecycleOps.buildFlowNoticeText("invite_no_channel"))
      return false, sessionLifecycleOps.buildFlowNoticeText("invite_no_channel")
    end

    local inviteTargets = {}
    for _, memberKey in ipairs(deps.CollectGroupCharacterKeys()) do
      local existingMember = FindSessionMember(activeSession, memberKey)
      local existingStatus = string.upper(TrimText(type(existingMember) == "table" and existingMember.status or ""))
      if memberKey ~= "" and not AreCharacterKeysSame(memberKey, selfKey) and (not existingMember or existingStatus ~= "JOINED") then
        inviteTargets[#inviteTargets + 1] = memberKey
      end
    end

    if #inviteTargets == 0 then
      Print(sessionLifecycleOps.buildFlowNoticeText("invite_no_new_targets"))
      return true, 0
    end

    ExtendProfileSnapshotJoinGrace(activeSession.id, activeSession.profileName or profileName, sessionConfig.inviteJoinGraceSeconds, "manual_invite")
    local sentCount = 0
    for _, memberKey in ipairs(inviteTargets) do
      local sent, sendError = SendComm(
        "START",
        "WHISPER",
        memberKey,
        activeSession.id,
        activeSession.profileName,
        TrimText(select(1, deps.GetLootProfileId(activeSession.profileName)) or ""),
        activeSession.host,
        activeSession.startedAt,
        deps.GetLootProfileMaster(activeSession.profileName),
        GetCommProtocolMarker(),
        activeSession.status or "PREPARING"
      )
      sessionLifecycleOps.beginInviteDelivery(activeSession, memberKey, sent, sendError)
      if sent then
        sentCount = sentCount + 1
      end
    end

    if sentCount > 0 then
      Print(sessionLifecycleOps.buildFlowNoticeText("invite_sent_count", {
        sentCount = sentCount,
      }))
    else
      Print(sessionLifecycleOps.buildFlowNoticeText("invite_sent_none"))
    end
    return sentCount > 0, sentCount
  end

  INTERNAL_API.LIDCOUNCIL_RequestActiveProfileSubchecksumFlow_Impl = function(targetMemberKey)
    local activeSession, profileName = GetActiveLootSession()
    if not activeSession or not profileName then
      Print("No active loot session.")
      return false, "No active session."
    end

    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if not AreCharacterKeysSame(activeSession.host or "", selfKey) then
      Print("Only the loot session host can request detailed shared-profile comparisons.")
      return false, "Only the host can request detailed shared-profile comparisons."
    end

    local blocked, blockedMessage = RejectCombatLockedAction("Check Differences")
    if blocked then
      return false, blockedMessage
    end

    local requestedTarget = NormalizeCharacterKey(targetMemberKey)
    local targets = {}
    if requestedTarget ~= "" then
      targets[1] = requestedTarget
    else
      local syncCandidateSnapshot = BuildActiveSyncCandidateSnapshot()
      for _, candidate in ipairs(type(syncCandidateSnapshot.list) == "table" and syncCandidateSnapshot.list or {}) do
        local memberKey = NormalizeCharacterKey(type(candidate) == "table" and candidate.memberKey or "")
        if memberKey ~= "" then
          targets[#targets + 1] = memberKey
        end
      end
    end

    local requestedCount, skippedAligned, skippedLoaded, skippedPending = SendDetailedComparisonRequests(targets, {
      force = true,
    })

    if requestedCount > 0 then
      local message = "Requested detailed checksum scopes from " .. tostring(requestedCount) .. " joined member"
        .. (requestedCount == 1 and "" or "s") .. "."
      if skippedAligned > 0 then
        message = message .. " Already aligned or full-fallback members skipped: " .. tostring(skippedAligned) .. "."
      end
      if skippedLoaded > 0 then
        message = message .. " Already loaded: " .. tostring(skippedLoaded) .. "."
      end
      if skippedPending > 0 then
        message = message .. " Pending deferred repair requests: " .. tostring(skippedPending) .. "."
      end
      sessionLifecycleOps.emitSyncRuntimeState(activeSession.id, profileName, "subchecks_requested", "info", message, {
        sender = selfKey,
        skipIfSame = true,
        noticeText = message,
        refreshSyncManagement = true,
        coalesceWindowSeconds = 1.5,
        coalesceKey = "subchecks_requested|" .. string.lower(TrimText(selfKey)),
        coalesceSignature = "subchecks_requested",
      })
    elseif skippedAligned > 0 or skippedLoaded > 0 or skippedPending > 0 then
      Print("No additional detailed checksum request was needed for the selected members.")
    else
      Print("No joined member comparison targets are available.")
    end
    return requestedCount > 0, requestedCount
  end

  INTERNAL_API.LIDCOUNCIL_HandleReadinessProofUpdated_Impl = function(sessionId, memberKey)
    local resolvedSessionId = TrimText(sessionId)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if resolvedSessionId == "" or resolvedMemberKey == "" then
      return false
    end

    local published = profileSyncMetaOps.publishJoinManifestValidationState(resolvedSessionId, resolvedMemberKey)
    if published then
      sessionUiOps.refreshCurrentSection({ defer = true })
    end
    return published == true
  end

  INTERNAL_API.LIDCOUNCIL_RefreshActiveSessionReadinessFlow_Impl = function()
    local activeSession, profileName = GetActiveLootSession()
    if type(activeSession) ~= "table" or TrimText(profileName) == "" then
      Print("No active loot session.")
      return false, "No active session."
    end

    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if selfKey == "" or not AreCharacterKeysSame(activeSession.host or "", selfKey) then
      Print("Only the loot session host can refresh readiness.")
      return false, "Only the host can refresh readiness."
    end

    local resolvedSessionId = TrimText(activeSession.id)
    if resolvedSessionId == "" then
      Print("The active loot session has no valid session ID.")
      return false, "The active session has no valid session ID."
    end
    local now = GetProfileCheckpointSyncTime()
    if resolvedSessionId ~= ""
      and sessionRuntime.lastReadinessRefreshSessionId == resolvedSessionId
      and (now - math.max(0, tonumber(sessionRuntime.lastReadinessRefreshAt) or 0)) < sessionConfig.readinessRefreshCooldownSeconds
    then
      Print("Readiness refresh is already in progress. Please wait a few seconds.")
      return false, "Readiness refresh is already in progress."
    end

    local targets = {}
    for storedMemberKey, member in pairs(type(activeSession.members) == "table" and activeSession.members or {}) do
      local memberKey = NormalizeCharacterKey(type(member) == "table" and member.memberKey or storedMemberKey)
      if memberKey ~= ""
        and not AreCharacterKeysSame(memberKey, selfKey)
        and string.upper(TrimText(type(member) == "table" and member.status or "JOINED")) == "JOINED"
      then
        targets[#targets + 1] = memberKey
      end
    end
    table.sort(targets, function(left, right)
      return string.lower(left) < string.lower(right)
    end)

    if #targets == 0 then
      Print("No joined members are available for a readiness refresh.")
      return false, "No joined members are available."
    end

    sessionRuntime.lastReadinessRefreshSessionId = resolvedSessionId
    sessionRuntime.lastReadinessRefreshAt = now
    -- Manual readiness refresh is also the explicit P2 rearm.  Rebuild the
    -- host's active-session cache first, then republish the host proof to every
    -- joined member before asking for their compact checksums.
    RefreshActiveSessionProfileCache(activeSession, profileName)
    local requestedCount = 0
    for _, memberKey in ipairs(targets) do
      RefreshHostSessionMemberState(profileName, resolvedSessionId, {
        channel = "WHISPER",
        target = memberKey,
        forceBroadcast = true,
        suppressCheckpoint = true,
      })
      local proofRearmState = type(profileSyncMetaOps.takeJoinManifestProofRearmState) == "function"
        and profileSyncMetaOps.takeJoinManifestProofRearmState(resolvedSessionId, memberKey)
        or nil
      local proofRearmed = false
      if type(proofRearmState) == "table"
        and (#(proofRearmState.domains or {}) > 0 or #(proofRearmState.subdomains or {}) > 0)
      then
        proofRearmed = ScheduleDeferredJoinManifestRepair(
          profileName,
          resolvedSessionId,
          memberKey,
          proofRearmState.domains,
          proofRearmState.subdomains,
          {
            requirePreciseProof = true,
            maxPreciseProofAttempts = proofRearmState.maxPreciseProofAttempts,
            manualRearm = true,
            mode = "MANUAL",
          }
        ) == true
        if proofRearmed then
          requestedCount = requestedCount + 1
        end
      end
      profileSyncMetaOps.publishJoinManifestValidationState(resolvedSessionId, memberKey, {
        manualRefresh = true,
      })
      if not proofRearmed and type(profileSyncMetaOps.sendSubchecksumRequests) == "function" then
        requestedCount = requestedCount + math.max(0, tonumber(profileSyncMetaOps.sendSubchecksumRequests(
          memberKey,
          { "settings", "permissions", "loot", "session" },
          { force = true }
        )) or 0)
      end
    end

    sessionUiOps.refreshCurrentSection({ defer = true })
    if requestedCount > 0 then
      Print("Readiness refresh requested fresh compact proof from " .. tostring(#targets) .. " joined member"
        .. (#targets == 1 and "." or "s."))
      return true, #targets
    end

    Print("The current readiness matrix was republished, but no fresh proof request was queued.")
    return true, 0
  end

  INTERNAL_API.LIDCOUNCIL_PushActiveProfileSnapshotFlow_Impl = function(targetMemberKey, options)
    local activeSession, profileName = GetActiveLootSession()
    if not activeSession or not profileName then
      Print("No active loot session.")
      return false, "No active session."
    end
    options = type(options) == "table" and options or {}

    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if not AreCharacterKeysSame(activeSession.host or "", selfKey) then
      Print("Only the loot session host can push a shared profile update.")
      return false, "Only the host can push a shared profile update."
    end

    local blocked, blockedMessage = RejectCombatLockedAction("Push Host Repair")
    if blocked then
      return false, blockedMessage
    end

    local explicitDomains = type(options.domains) == "table" and options.domains or nil
    local explicitSubdomains = type(options.subdomains) == "table" and options.subdomains or nil
    if options.currentSessionOnly == true then
      explicitDomains = {}
      explicitSubdomains = profileSyncMetaOps.buildCurrentSessionCheckpointSubdomains(activeSession.id)
      if #explicitSubdomains == 0 then
        return false, "Current session state is unavailable."
      end
    end
    local forceAuthoritativeOverride = options.forceAuthoritativeOverride == true
    local forceFullSnapshot = forceAuthoritativeOverride and options.forceFullSnapshot == true
    local explicitScopeSelected = (type(explicitDomains) == "table" and #explicitDomains > 0)
      or (type(explicitSubdomains) == "table" and #explicitSubdomains > 0)
      or forceFullSnapshot
    local authoritativeArchiveScope = string.upper(TrimText(options.authoritativeArchiveScope))
    if not forceAuthoritativeOverride
      or (authoritativeArchiveScope ~= "LOOT_LIST"
        and authoritativeArchiveScope ~= "SESSION_HISTORY"
        and authoritativeArchiveScope ~= "FUN_AWARDS")
    then
      authoritativeArchiveScope = explicitScopeSelected
        and profileSyncMetaOps.resolveAuthoritativeArchiveScope(explicitSubdomains)
        or ""
    end

    local targets = {}
    local requestedTarget = NormalizeCharacterKey(targetMemberKey)
    if forceAuthoritativeOverride and requestedTarget == "" then
      Print("Select one joined member for the host-authoritative override.")
      return false, "Host override requires one joined member."
    end
    if explicitScopeSelected and requestedTarget == "" then
      Print("Select one joined member when pushing only selected leaf scopes.")
      return false, "Leaf scope push requires a selected member."
    end
    if requestedTarget ~= "" then
      if AreCharacterKeysSame(requestedTarget, selfKey) then
        Print("The host does not need to push the shared profile to themselves.")
        return false, "Target must be another joined member."
      end
      if not IsJoinedSessionCharacter(activeSession, requestedTarget) then
        Print("That character is not currently joined to the active loot session.")
        return false, "Target is not joined."
      end
      targets[1] = requestedTarget
    else
      for memberKey, member in pairs(activeSession.members or {}) do
        local resolvedKey = NormalizeCharacterKey(memberKey)
        if resolvedKey ~= "" and not AreCharacterKeysSame(resolvedKey, selfKey) and type(member) == "table" and tostring(member.status or "JOINED") == "JOINED" then
          targets[#targets + 1] = resolvedKey
        end
      end
      table.sort(targets)
    end

    if #targets == 0 then
      Print("No joined session members are available to receive a shared profile update.")
      return false, "No joined session members."
    end

    RefreshHostSessionMemberState(profileName, activeSession.id, {
      suppressCheckpoint = true,
    })
    local syncCandidateSnapshot = not explicitScopeSelected and BuildActiveSyncCandidateSnapshot() or nil
    local syncCandidateLookup = type(syncCandidateSnapshot) == "table" and type(syncCandidateSnapshot.lookup) == "table"
      and syncCandidateSnapshot.lookup
      or {}
    local hostRepairDisplaySnapshot = type(syncCandidateSnapshot) == "table"
      and syncCandidateSnapshot
      or BuildActiveSyncCandidateSnapshot()
    local localRepairRevisionSignature = TrimText(type(hostRepairDisplaySnapshot) == "table" and hostRepairDisplaySnapshot.localRevisionSignature)
    local liveTargetSignature = BuildLiveSyncTargetSignature(activeSession, selfKey, targetMemberKey)
    local hostRepairDisplayBaseContext = INTERNAL_API.LIDCOUNCIL_BuildHostCurrentSessionDisplayContext(
      activeSession,
      profileName,
      nil,
      {
        syncCandidateSnapshot = hostRepairDisplaySnapshot,
      }
    )
    local hostPushCurrentSectionProbe = INTERNAL_API.LIDCOUNCIL_BuildHostCurrentSectionDisplayProbe(
      activeSession,
      profileName,
      {
        hostCurrentSessionDisplayBaseContext = hostRepairDisplayBaseContext,
        syncCandidateSnapshot = hostRepairDisplaySnapshot,
      }
    )

    local sentCount = 0
    local repairMetricsState = sessionLifecycleOps.createRepairMetricsState()
    local lastSendError = nil
    local repairRefreshState = {}
    local requestedMode = string.upper(TrimText(options.mode))
    local repairMode = authoritativeArchiveScope ~= ""
        and "BACKGROUND"
      or (requestedMode == "BACKGROUND" and "BACKGROUND" or "LIVE")
    local requestedReason = TrimText(options.reason)
    local repairReason = requestedReason ~= ""
      and requestedReason
      or (explicitScopeSelected and "host_push_selected_scope" or "host_push_repair")
    local repairSourceLabel = forceAuthoritativeOverride
      and "host-authoritative override"
      or (explicitScopeSelected and "selected-scope host repair" or "host repair")
    for _, memberKey in ipairs(targets) do
      local syncCandidate = syncCandidateLookup[string.lower(memberKey)]
      local queuedRepair, queuedCount, repairError, repairDetail = profileSyncMetaOps.queueAutomaticHostRepairForMember(
        activeSession,
        profileName,
        activeSession.id,
        memberKey,
        {
          mode = repairMode,
          reason = repairReason,
          domains = explicitDomains,
          subdomains = explicitSubdomains,
          forceFullSnapshot = forceFullSnapshot,
          forceAuthoritativeOverride = forceAuthoritativeOverride,
          skipScopePrune = forceAuthoritativeOverride or explicitScopeSelected,
          authoritativeArchiveScope = authoritativeArchiveScope,
          suppressUnchanged = not forceAuthoritativeOverride,
          sourceLabelOverride = repairSourceLabel,
          syncCandidate = syncCandidate,
          syncCandidateSnapshot = hostRepairDisplaySnapshot,
          currentSessionDisplayBaseContext = hostRepairDisplayBaseContext,
          localRepairRevisionSignature = localRepairRevisionSignature,
          liveTargetSignature = liveTargetSignature,
          refreshEditor = false,
        }
      )

      repairRefreshState = sessionUiOps.mergeRepairOutcomeRefreshState(
        repairRefreshState,
        type(repairDetail) == "table" and repairDetail.outcomePersisted == true,
        type(repairDetail) == "table" and repairDetail.currentSectionChanged == true
      )

      local resolvedQueuedCount = math.max(0, tonumber(queuedCount) or 0)
      if queuedRepair then
        if resolvedQueuedCount > 0 then
          sentCount = sentCount + resolvedQueuedCount
          sessionLifecycleOps.accumulateQueuedRepairMetrics(repairMetricsState, resolvedQueuedCount, repairDetail, {
            forceFullSnapshot = type(repairDetail) == "table" and repairDetail.forceFullSnapshot == true,
            precise = TrimText(type(repairDetail) == "table" and repairDetail.requestedScope or "") == "precise",
          })
        else
          sessionLifecycleOps.accumulateSkippedRepairMetrics(repairMetricsState, repairDetail, {
            includeSuppressed = true,
          })
        end
      elseif TrimText(repairError) ~= "" then
        lastSendError = repairError
      end
    end

    sessionUiOps.applyRepairOutcomeRefreshState(repairRefreshState, {
      activeSession = activeSession,
      profileName = profileName,
      previousHostCurrentSectionProbe = hostPushCurrentSectionProbe,
      hostCurrentSessionDisplayBaseContext = hostRepairDisplayBaseContext,
      syncCandidateSnapshot = hostRepairDisplaySnapshot,
      fallbackScope = "CURRENT_AND_SYNC",
    })

    if sentCount > 0 or repairMetricsState.deferredPatchStateCount > 0 then
      local message = sessionLifecycleOps.buildHostPushRepairDispatchMessage(sentCount, repairMetricsState, {
        includeSnapshotTransfers = true,
        includeSuppressed = true,
        includeSkippedAligned = true,
        includeSkippedMemberNewer = true,
      })
      sessionLifecycleOps.emitRepairRuntimeState(activeSession.id, profileName, "host_pushed", sentCount > 0 and "success" or "info", message, {
        sender = selfKey,
        noticeText = message,
        printWhenChangedOnly = true,
      })
      profileSyncMetaOps.recordStandardRepairHistory("host_push", message, {
        profileName = profileName,
        sessionId = activeSession.id,
        memberKey = targetMemberKey,
        dedupeWindowSeconds = 10,
      })
    elseif (repairMetricsState.suppressedRepeatCount > 0 or repairMetricsState.skippedAlignedCount > 0 or repairMetricsState.skippedMemberNewerCount > 0)
      and TrimText(lastSendError) == ""
    then
      local message = sessionLifecycleOps.buildRepairIdleStatusMessage("No host repair was queued.", repairMetricsState, {
        includeSuppressed = true,
        includeSkippedAligned = true,
        includeSkippedMemberNewer = true,
        memberNewerText = "Member newer or mixed-difference copies should be reviewed first",
      })
      sessionLifecycleOps.emitRepairRuntimeState(activeSession.id, profileName, "host_pushed", "info", message, {
        sender = selfKey,
        noticeText = message,
        printWhenChangedOnly = true,
      })
    else
      Print("No shared profile updates could be sent." .. (lastSendError and (" " .. tostring(lastSendError)) or ""))
    end
    return sentCount > 0 or repairMetricsState.deferredPatchStateCount > 0, sentCount
  end

  INTERNAL_API.LIDCOUNCIL_PushProfileHostOverrideFlow_Impl = function(targetMemberKey, requestedScopes)
    local contract = type(INTERNAL_API) == "table" and INTERNAL_API.LIDCOUNCIL_ProfileHostOverrideContract or nil
    local executePlan = type(contract) == "table" and contract.ExecutePlan or nil
    if type(executePlan) ~= "function" then
      return false, { error = "Host override contract is unavailable." }
    end
    return executePlan(targetMemberKey, requestedScopes, function(target, transport)
      return INTERNAL_API.LIDCOUNCIL_PushActiveProfileSnapshotFlow_Impl(target, transport)
    end)
  end

  INTERNAL_API.LIDCOUNCIL_BroadcastActiveProfileSnapshotFlow_Impl = function(profileName, reason, targetMemberKey)
    local activeSession, activeProfileName = GetActiveLootSession()
    if not activeSession or not activeProfileName then
      return false, "No active session."
    end

    local requestedProfileName = TrimText(profileName)
    if requestedProfileName ~= "" and not DoesActiveSessionMatch(activeSession, activeProfileName, activeSession.id, requestedProfileName) then
      return false, "No matching active session profile."
    end

    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if selfKey == "" or not IsJoinedSessionCharacter(activeSession, selfKey) then
      return false, "You are not joined to the active session."
    end

    local targets = CollectLiveSyncTargets(activeSession, selfKey, targetMemberKey)
    if #targets == 0 then
      return false, "No joined session members."
    end

    local syncCandidateSnapshot = BuildActiveSyncCandidateSnapshot()
    local previousCurrentSectionProbe = INTERNAL_API.LIDCOUNCIL_BuildHostCurrentSectionDisplayProbe(
      activeSession,
      activeProfileName,
      {
        syncCandidateSnapshot = syncCandidateSnapshot,
      }
    )
    local sourceProfile = type(deps.GetLootProfile) == "function" and select(1, deps.GetLootProfile(activeProfileName)) or nil
    if type(sourceProfile) == "table" and type(deps.NormalizeLootRollOptions) == "function" then
      activeSession.rollOptions = deps.NormalizeLootRollOptions(sourceProfile.settings and sourceProfile.settings.rollOptions)
    end
    if type(activeSession.members) == "table" then
      for memberKey, member in pairs(activeSession.members) do
        if type(member) == "table" then
          member.profileMaster = deps.GetLootProfileMaster(activeProfileName)
          member.role = deps.GetLootProfileRole(activeProfileName, memberKey)
        end
      end
    end
    local syncCandidateLookup = type(syncCandidateSnapshot.lookup) == "table" and syncCandidateSnapshot.lookup or {}
    local localRepairRevisionSignature = TrimText(syncCandidateSnapshot.localRevisionSignature)
    local liveTargetSignature = BuildLiveSyncTargetSignature(activeSession, selfKey, targetMemberKey)
    local automaticRepairDisplayBaseContext = INTERNAL_API.LIDCOUNCIL_BuildHostCurrentSessionDisplayContext(
      activeSession,
      activeProfileName,
      nil,
      {
        syncCandidateSnapshot = syncCandidateSnapshot,
      }
    )

    local sentCount = 0
    local repairMetricsState = sessionLifecycleOps.createRepairMetricsState()
    local lastQueueError = nil
    local broadcastReason = TrimText(reason) ~= "" and TrimText(reason) or "broadcast_repair"
    local forceProfileDeltaFallback = profileSyncMetaOps.isProfileDeltaSnapshotFallbackReason(broadcastReason)
    local repairRefreshState = {}
    for _, memberKey in ipairs(targets) do
      local syncCandidate = syncCandidateLookup[string.lower(memberKey)]
      local queuedRepair, queuedCount, queueError, repairDetail = profileSyncMetaOps.queueAutomaticHostRepairForMember(
        activeSession,
        activeProfileName,
        activeSession.id,
        memberKey,
        {
          mode = "LIVE",
          reason = broadcastReason,
          refreshEditor = false,
          syncCandidate = syncCandidate,
          syncCandidateSnapshot = syncCandidateSnapshot,
          currentSessionDisplayBaseContext = automaticRepairDisplayBaseContext,
          localRepairRevisionSignature = localRepairRevisionSignature,
          liveTargetSignature = liveTargetSignature,
          forceFullSnapshot = forceProfileDeltaFallback,
          -- A profile delta fallback is already proof that the compact delivery
          -- did not occur. It must not be suppressed by a candidate snapshot
          -- that still contains optimistic or otherwise stale comparison data.
          suppressUnchanged = not forceProfileDeltaFallback,
        }
      )
      repairRefreshState = sessionUiOps.mergeRepairOutcomeRefreshState(
        repairRefreshState,
        type(repairDetail) == "table" and repairDetail.outcomePersisted == true,
        type(repairDetail) == "table" and repairDetail.currentSectionChanged == true
      )
      if queuedRepair then
        local queuedTransfers = math.max(0, tonumber(queuedCount) or 0)
        if queuedTransfers > 0 then
          sentCount = sentCount + queuedTransfers
          sessionLifecycleOps.accumulateQueuedRepairMetrics(repairMetricsState, queuedTransfers, repairDetail)
        else
          sessionLifecycleOps.accumulateSkippedRepairMetrics(repairMetricsState, repairDetail, {
            includeSuppressed = true,
          })
        end
      elseif TrimText(queueError) ~= "" then
        lastQueueError = queueError
      end
    end

    sessionUiOps.applyRepairOutcomeRefreshState(repairRefreshState, {
      activeSession = activeSession,
      profileName = activeProfileName,
      previousHostCurrentSectionProbe = previousCurrentSectionProbe,
      hostCurrentSessionDisplayBaseContext = automaticRepairDisplayBaseContext,
      syncCandidateSnapshot = syncCandidateSnapshot,
      fallbackScope = "CURRENT",
    })

    if sentCount > 0 or repairMetricsState.deferredPatchStateCount > 0 then
      local broadcastMessage = sessionLifecycleOps.buildLiveBroadcastRepairDispatchMessage(sentCount, repairMetricsState, {
          includeSnapshotTransfers = true,
          includeSuppressed = true,
          includeSkippedAligned = true,
          includeSkippedMemberNewer = true,
        })
      sessionLifecycleOps.emitRepairRuntimeState(activeSession.id, activeProfileName, "live_broadcast", sentCount > 0 and "success" or "info",
        broadcastMessage, {
          sender = selfKey,
          printNotice = false,
        })
      return true, sentCount
    end
    if (repairMetricsState.suppressedRepeatCount > 0 or repairMetricsState.skippedAlignedCount > 0 or repairMetricsState.skippedMemberNewerCount > 0) and TrimText(lastQueueError) == "" then
      sessionLifecycleOps.emitRepairRuntimeState(activeSession.id, activeProfileName, "live_broadcast", "info",
        sessionLifecycleOps.buildRepairIdleStatusMessage("No live broadcast repair was queued.", repairMetricsState, {
          includeSuppressed = true,
          includeSkippedAligned = true,
          includeSkippedMemberNewer = true,
        }), {
          sender = selfKey,
          printNotice = false,
        })
      return true, 0
    end
    return false, lastQueueError or "No live shared profile update could be queued."
  end

  INTERNAL_API.LIDCOUNCIL_BroadcastActiveProfileDeltaFlow_Impl = function(profileName, reason, change)
    local activeSession, activeProfileName = GetActiveLootSession()
    if not activeSession or not activeProfileName then
      return false, "No active session."
    end

    local requestedProfileName = TrimText(profileName)
    if requestedProfileName ~= "" and not DoesActiveSessionMatch(activeSession, activeProfileName, activeSession.id, requestedProfileName) then
      return false, "No matching active session profile."
    end
    if type(change) ~= "table" or TrimText(change.action) == "" then
      return false, "Profile delta is missing."
    end

    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if selfKey == "" or not IsJoinedSessionCharacter(activeSession, selfKey) then
      return false, "You are not joined to the active session."
    end

    local profileId = TrimText(select(1, deps.GetLootProfileId(activeProfileName)) or "")
    local delta = {
      profileId = profileId,
      changeId = BuildProfileDeltaId(),
      actor = selfKey,
      domain = TrimText(change.domain) ~= "" and TrimText(change.domain) or TrimText(reason),
      action = TrimText(change.action),
      args = type(change.args) == "table" and change.args or {},
    }
    MarkProfileDeltaSeen(delta.changeId, delta.sessionId)

    RefreshActiveSessionProfileCache(activeSession, activeProfileName)
    local revisionSummary = GetLootProfileRevisionSummary(activeProfileName)
    if AreCharacterKeysSame(activeSession.host or "", selfKey) then
      RefreshHostSessionMemberState(activeProfileName, activeSession.id, {
        suppressCheckpoint = true,
      })
      local distribution = deps.GetGroupDistribution()
      if not distribution then
        return false, "No group channel."
      end
      local sent, err = SendProfileDelta("PDELTA", distribution, nil, activeSession, activeProfileName, delta, revisionSummary)
      local deliveryPolicy = profileSyncMetaOps.buildProfileDeltaDeliveryPolicy(sent, err)
      if deliveryPolicy.trackAcks then
        TrackProfileDeltaAcks(activeSession, activeProfileName, delta, revisionSummary)
      elseif deliveryPolicy.forceSnapshotFallback
        and type(INTERNAL_API.LIDCOUNCIL_BroadcastActiveProfileSnapshotFlow_Impl) == "function"
      then
        return INTERNAL_API.LIDCOUNCIL_BroadcastActiveProfileSnapshotFlow_Impl(activeProfileName, "delta_payload_fallback")
      end
      return sent, err
    end

    local hostKey = NormalizeCharacterKey(activeSession.host)
    if hostKey == "" then
      return false, "No session host."
    end
    return SendProfileDelta("PDELTA_REQ", "WHISPER", hostKey, activeSession, activeProfileName, delta, revisionSummary)
  end

  INTERNAL_API.LIDCOUNCIL_HandleProfileDeltaRequest_Impl = function(fields, sender)
    local delta, payloadError = profileSyncMetaOps.parseInboundProfileDeltaPayload(fields)
    if type(delta) ~= "table" then
      profileSyncMetaOps.recordInboundPayloadReject("PDELTA_REQ", sender, fields, payloadError)
      return
    end
    if HasProfileDeltaSeen(delta.changeId) then
      return
    end

    local activeSession, activeProfileName = GetActiveLootSession()
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if not DoesActiveSessionMatch(activeSession, activeProfileName, delta.sessionId, delta.profileName) then
      return
    end
    if not AreCharacterKeysSame(activeSession.host or "", selfKey) then
      return
    end
    if not IsClaimedActorSenderMatch(sender, delta.actor) then
      return
    end
    if not IsJoinedSessionCharacter(activeSession, delta.actor) then
      return
    end

    local localProfileName = TrimText(activeProfileName) ~= "" and activeProfileName or delta.profileName
    if delta.profileId ~= "" and TrimText(select(1, deps.GetLootProfileId(localProfileName)) or "") ~= delta.profileId then
      return
    end
    if profileSyncMetaOps.stageInboundProfileDeltaIfCombat(
      "PDELTA_REQ",
      fields,
      sender,
      delta,
      activeSession,
      localProfileName
    ) then
      return
    end
    local currentSectionProbeMemberKeys = {}
    local hostMemberKey = NormalizeCharacterKey(activeSession.host or "")
    local deltaActorKey = NormalizeCharacterKey(delta.actor)
    if hostMemberKey ~= "" then
      currentSectionProbeMemberKeys[#currentSectionProbeMemberKeys + 1] = hostMemberKey
    end
    if deltaActorKey ~= "" then
      currentSectionProbeMemberKeys[#currentSectionProbeMemberKeys + 1] = deltaActorKey
    end
    local previousCurrentSectionState = INTERNAL_API.LIDCOUNCIL_BuildCurrentSectionStateSignature(activeSession)
    local previousCurrentSectionProbe = INTERNAL_API.LIDCOUNCIL_BuildCurrentSectionChangeProbe(
      activeSession,
      currentSectionProbeMemberKeys
    )

    if type(deps.ApplyIncomingLootProfileDelta) ~= "function" then
      return
    end
    local ok = deps.ApplyIncomingLootProfileDelta(localProfileName, delta.domain, delta.action, delta.args, {
      actor = delta.actor,
      source = "request",
    })
    if not ok then
      return
    end
    MarkProfileDeltaSeen(delta.changeId, delta.sessionId)
    RefreshActiveSessionProfileCache(activeSession, localProfileName)

    local revisionSummary = GetLootProfileRevisionSummary(localProfileName)
    RefreshHostSessionMemberState(localProfileName, activeSession.id, {
      suppressCheckpoint = true,
    })

    local distribution = deps.GetGroupDistribution()
    if distribution then
      local sent, sendError = SendProfileDelta("PDELTA", distribution, nil, activeSession, localProfileName, delta, revisionSummary)
      local deliveryPolicy = profileSyncMetaOps.buildProfileDeltaDeliveryPolicy(sent, sendError)
      if deliveryPolicy.forceSnapshotFallback then
        INTERNAL_API.LIDCOUNCIL_BroadcastActiveProfileSnapshotFlow_Impl(localProfileName, "delta_fallback")
      elseif deliveryPolicy.trackAcks then
        TrackProfileDeltaAcks(activeSession, localProfileName, delta, revisionSummary)
      end
    end
    local currentSectionChanged = INTERNAL_API.LIDCOUNCIL_GetCurrentSectionChangeFromProbe(
      activeSession,
      previousCurrentSectionState,
      previousCurrentSectionProbe,
      currentSectionProbeMemberKeys,
      function()
        return INTERNAL_API.LIDCOUNCIL_BuildCurrentSectionStateSignature(activeSession)
      end
    )
    sessionUiOps.refreshCurrentAndSyncSections(currentSectionChanged)
  end

  INTERNAL_API.LIDCOUNCIL_HandleProfileDelta_Impl = function(fields, sender)
    local delta, payloadError = profileSyncMetaOps.parseInboundProfileDeltaPayload(fields)
    if type(delta) ~= "table" then
      profileSyncMetaOps.recordInboundPayloadReject("PDELTA", sender, fields, payloadError)
      return
    end

    local activeSession, activeProfileName = GetActiveLootSession()
    if not DoesActiveSessionMatch(activeSession, activeProfileName, delta.sessionId, delta.profileName) then
      return
    end
    if not deps.IsActiveSessionHostSender(activeSession, sender) then
      return
    end
    if not IsJoinedSessionCharacter(activeSession, delta.actor) then
      return
    end

    local localProfileName = TrimText(activeProfileName) ~= "" and activeProfileName or delta.profileName
    if delta.profileId ~= "" and TrimText(select(1, deps.GetLootProfileId(localProfileName)) or "") ~= delta.profileId then
      return
    end
    if profileSyncMetaOps.stageInboundProfileDeltaIfCombat(
      "PDELTA",
      fields,
      sender,
      delta,
      activeSession,
      localProfileName
    ) then
      return
    end
    local function BuildCurrentSessionDisplaySignature(displayOpts)
      displayOpts = type(displayOpts) == "table" and displayOpts or {}
      local selfMemberKey = NormalizeCharacterKey(GetCharacterKey() or "")
      local sessionHost = NormalizeCharacterKey(activeSession.host or "")
      local isHostView = selfMemberKey ~= "" and sessionHost ~= "" and selfMemberKey == sessionHost
      local syncCandidateSnapshot = type(displayOpts.syncCandidateSnapshot) == "table"
        and displayOpts.syncCandidateSnapshot
        or BuildActiveSyncCandidateSnapshot()
      local hostCurrentSessionDisplayBaseContext = type(displayOpts.hostCurrentSessionDisplayBaseContext) == "table"
        and displayOpts.hostCurrentSessionDisplayBaseContext
        or INTERNAL_API.LIDCOUNCIL_BuildHostCurrentSessionDisplayContext(
          activeSession,
          localProfileName,
          nil,
          {
            syncCandidateSnapshot = syncCandidateSnapshot,
          }
        )
      local localProfileId = hostCurrentSessionDisplayBaseContext.localProfileId
      local localSummary = hostCurrentSessionDisplayBaseContext.localSummary
      local localLiveLootChecksum = hostCurrentSessionDisplayBaseContext.localLiveLootChecksum
      local rosterLookup = hostCurrentSessionDisplayBaseContext.rosterLookup
      local candidateEntries = type(displayOpts.candidateEntries) == "table" and displayOpts.candidateEntries or nil
      local candidateSyncStateByMemberKey = type(displayOpts.candidateSyncStateByMemberKey) == "table"
        and displayOpts.candidateSyncStateByMemberKey
        or nil
      if type(candidateEntries) ~= "table" or type(candidateSyncStateByMemberKey) ~= "table" then
        candidateEntries, candidateSyncStateByMemberKey = BuildActiveSyncCandidateStateEntries(
          syncCandidateSnapshot,
          rosterLookup
        )
      end

      local signatureParts = {
        activeSession.sharedProfileReady == false and "0" or "1",
      }
      local inputSignatureParts = {
        activeSession.sharedProfileReady == false and "0" or "1",
        selfMemberKey,
        sessionHost,
        localProfileId,
        tostring(math.max(0, tonumber(type(localSummary) == "table" and localSummary.settings) or 0)),
        tostring(math.max(0, tonumber(type(localSummary) == "table" and localSummary.permissions) or 0)),
        tostring(math.max(0, tonumber(type(localSummary) == "table" and localSummary.operational) or 0)),
        tostring(math.max(0, tonumber(type(localSummary) == "table" and localSummary.loot) or 0)),
        TrimText(type(localSummary) == "table" and localSummary.settingsChecksum or ""),
        TrimText(type(localSummary) == "table" and localSummary.permissionsChecksum or ""),
        TrimText(type(localSummary) == "table" and localSummary.operationalChecksum or ""),
        TrimText(type(localSummary) == "table" and localSummary.lootChecksum or ""),
        localLiveLootChecksum,
      }
      table.sort(candidateEntries)
      for _, entry in ipairs(candidateEntries) do
        inputSignatureParts[#inputSignatureParts + 1] = entry
      end
      local memberEntries = {}
      local inputMemberEntries = {}
      if isHostView then
        for memberKey, member in pairs(type(activeSession.members) == "table" and activeSession.members or {}) do
          if type(member) == "table" then
            local resolvedKey = NormalizeCharacterKey(memberKey ~= "" and memberKey or member.name or "")
            if resolvedKey ~= "" and IsSessionMemberVisibleForCurrentState(member) then
              local memberVisibleStateSignature = BuildSessionVisibleMemberStateSignature(member)
              memberEntries[#memberEntries + 1] = resolvedKey
                .. "\30"
                .. INTERNAL_API.LIDCOUNCIL_BuildHostCurrentSessionMemberDisplayState(
                  activeSession,
                  localProfileName,
                  resolvedKey,
                  member,
                  {
                    localProfileId = localProfileId,
                    localSummary = localSummary,
                    localLiveLootChecksum = localLiveLootChecksum,
                    rosterLookup = rosterLookup,
                    candidateState = candidateSyncStateByMemberKey[resolvedKey],
                  }
                )
              inputMemberEntries[#inputMemberEntries + 1] = resolvedKey .. "\30" .. memberVisibleStateSignature
            end
          end
        end
      else
        local memberCurrentSessionDisplayContext = INTERNAL_API.LIDCOUNCIL_BuildMemberCurrentSessionDisplayContext(
          activeSession,
          localProfileName,
          selfMemberKey,
          {
            sessionHost = sessionHost,
            localProfileId = localProfileId,
            localSummary = localSummary,
            localLiveLootChecksum = localLiveLootChecksum,
            rosterLookup = rosterLookup,
            candidateSyncStateByMemberKey = candidateSyncStateByMemberKey,
            syncCandidateSnapshot = syncCandidateSnapshot,
          }
        )
        for memberKey, member in pairs(type(activeSession.members) == "table" and activeSession.members or {}) do
          if type(member) == "table" then
            local resolvedKey = NormalizeCharacterKey(memberKey ~= "" and memberKey or member.name or "")
            if resolvedKey ~= "" and IsSessionMemberVisibleForCurrentState(member) then
              local memberVisibleStateSignature = BuildSessionVisibleMemberStateSignature(member)
              memberEntries[#memberEntries + 1] = resolvedKey
                .. "\30"
                .. INTERNAL_API.LIDCOUNCIL_BuildMemberCurrentSessionMemberDisplayState(
                  activeSession,
                  localProfileName,
                  resolvedKey,
                  member,
                  memberCurrentSessionDisplayContext
                )
              inputMemberEntries[#inputMemberEntries + 1] = resolvedKey .. "\30" .. memberVisibleStateSignature
            end
          end
        end
      end
      table.sort(memberEntries)
      table.sort(inputMemberEntries)
      for _, entry in ipairs(memberEntries) do
        signatureParts[#signatureParts + 1] = entry
      end
      for _, entry in ipairs(inputMemberEntries) do
        inputSignatureParts[#inputSignatureParts + 1] = entry
      end
      return table.concat(signatureParts, "\31"), table.concat(inputSignatureParts, "\31")
    end
    if type(deps.ApplyIncomingLootProfileDelta) ~= "function" then
      return
    end

    if HasProfileDeltaSeen(delta.changeId) then
      RememberProfileDeltaSequence(delta)
      -- The profile delta can update canonical roll options.  P2 is derived from
      -- the active-session cache, so refresh that cache before validating or
      -- acknowledging a replayed delta as well.
      RefreshActiveSessionProfileCache(activeSession, localProfileName)
      local aligned = IsLocalProfileAlignedWithDelta(localProfileName, delta)
      if not aligned then
        RequestProfileDeltaRecovery(activeSession, localProfileName, delta, "checksum_mismatch")
        return
      end
      SendProfileDeltaAck(activeSession, localProfileName, delta, GetLootProfileRevisionSummary(localProfileName))
      if INTERNAL_API.LIDCOUNCIL_ShouldPublishProfileDeltaStateProof_Impl(delta.domain)
        and type(profileSyncMetaOps.scheduleDelayedLocalProfileStateSend) == "function"
      then
        profileSyncMetaOps.scheduleDelayedLocalProfileStateSend(
          activeSession.id,
          delta.profileName,
          localProfileName
        )
      end
      return
    end
    if IsProfileDeltaSequenceStale(delta) then
      RequestProfileDeltaRecovery(activeSession, localProfileName, delta, "stale_sequence")
      sessionLifecycleOps.emitSyncRuntimeState(delta.sessionId, localProfileName, "delta_stale_recovery", "warn",
        "An older profile update arrived after a newer one. Requested a host profile repair.", {
          sender = NormalizeSenderKey(sender),
          skipIfSame = true,
          printNotice = false,
          refreshSyncManagement = true,
          coalesceWindowSeconds = 2.5,
          coalesceKey = "delta_recovery|" .. string.lower(TrimText(NormalizeSenderKey(sender))),
          coalesceSignature = "delta_recovery",
        })
      return
    end
    if IsProfileDeltaSequenceGap(delta) then
      RequestProfileDeltaRecovery(activeSession, localProfileName, delta, "sequence_gap")
      sessionLifecycleOps.emitSyncRuntimeState(delta.sessionId, localProfileName, "delta_gap_recovery", "warn",
        "A profile update was missed. Requested a host profile repair.", {
          sender = NormalizeSenderKey(sender),
          skipIfSame = true,
          printNotice = false,
          refreshSyncManagement = true,
          coalesceWindowSeconds = 2.5,
          coalesceKey = "delta_recovery|" .. string.lower(TrimText(NormalizeSenderKey(sender))),
          coalesceSignature = "delta_recovery",
        })
      return
    end

    local previousCurrentSectionDisplaySnapshot = BuildActiveSyncCandidateSnapshot()
    local previousCurrentSectionDisplay, previousCurrentSectionDisplayInputs = BuildCurrentSessionDisplaySignature({
      syncCandidateSnapshot = previousCurrentSectionDisplaySnapshot,
    })
    local ok = deps.ApplyIncomingLootProfileDelta(localProfileName, delta.domain, delta.action, delta.args, {
      actor = delta.actor,
      source = "host",
      skipAccessCheck = true,
    })
    if not ok then
      RequestProfileDeltaRecovery(activeSession, localProfileName, delta, "apply_failed")
      return
    end
    -- Refresh the session copy before computing the delta checksum/ACK.  Doing
    -- this after the ACK advertised the previous roll-option checksum and left
    -- the member on P2 Proof unknown until the next lobby was opened.
    RefreshActiveSessionProfileCache(activeSession, localProfileName)
    local aligned = IsLocalProfileAlignedWithDelta(localProfileName, delta)
    if not aligned then
      RequestProfileDeltaRecovery(activeSession, localProfileName, delta, "checksum_mismatch")
      sessionLifecycleOps.emitSyncRuntimeState(delta.sessionId, localProfileName, "delta_checksum_recovery", "warn",
        "A profile update did not match the host checksum. Requested a host profile repair.", {
          sender = NormalizeSenderKey(sender),
          skipIfSame = true,
          printNotice = false,
          refreshSyncManagement = true,
          coalesceWindowSeconds = 2.5,
          coalesceKey = "delta_recovery|" .. string.lower(TrimText(NormalizeSenderKey(sender))),
          coalesceSignature = "delta_recovery",
        })
      return
    end
    MarkProfileDeltaSeen(delta.changeId, delta.sessionId)
    RememberProfileDeltaSequence(delta)
    SendProfileDeltaAck(activeSession, localProfileName, delta, GetLootProfileRevisionSummary(localProfileName))
    if INTERNAL_API.LIDCOUNCIL_ShouldPublishProfileDeltaStateProof_Impl(delta.domain)
      and type(profileSyncMetaOps.scheduleDelayedLocalProfileStateSend) == "function"
    then
      profileSyncMetaOps.scheduleDelayedLocalProfileStateSend(
        activeSession.id,
        delta.profileName,
        localProfileName
      )
    end
    local currentSectionDisplaySnapshot = BuildActiveSyncCandidateSnapshot()
    local currentSectionDisplayBaseContext = INTERNAL_API.LIDCOUNCIL_BuildHostCurrentSessionDisplayContext(
      activeSession,
      localProfileName,
      nil,
      {
        syncCandidateSnapshot = currentSectionDisplaySnapshot,
      }
    )
    local currentSectionCandidateEntries, currentSectionCandidateSyncStateByMemberKey = BuildActiveSyncCandidateStateEntries(
      currentSectionDisplaySnapshot,
      currentSectionDisplayBaseContext.rosterLookup
    )
    local currentSectionChanged = INTERNAL_API.LIDCOUNCIL_GetCurrentSectionChangeFromDisplayInputs(
      activeSession,
      localProfileName,
      previousCurrentSectionDisplay,
      previousCurrentSectionDisplayInputs,
      BuildCurrentSessionDisplaySignature,
      {
        hostCurrentSessionDisplayBaseContext = currentSectionDisplayBaseContext,
        syncCandidateSnapshot = currentSectionDisplaySnapshot,
        candidateEntries = currentSectionCandidateEntries,
        candidateSyncStateByMemberKey = currentSectionCandidateSyncStateByMemberKey,
      }
    )
    sessionUiOps.refreshCurrentAndSyncSections(currentSectionChanged)
  end

  INTERNAL_API.LIDCOUNCIL_HandleProfileDeltaAck_Impl = function(fields, sender)
    local payload, payloadError = profileSyncMetaOps.parseInboundProfileDeltaAckPayload(fields, sender)
    if type(payload) ~= "table" then
      profileSyncMetaOps.recordInboundPayloadReject("PDELTA_ACK", sender, fields, payloadError)
      return
    end
    PruneAgedSessionRuntimeTracking(GetProfileCheckpointSyncTime())

    local activeSession, activeProfileName = GetActiveLootSession()
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if not DoesActiveSessionMatch(activeSession, activeProfileName, payload.sessionId, payload.profileName) then
      return
    end
    if not AreCharacterKeysSame(activeSession.host or "", selfKey) then
      return
    end
    if not IsClaimedActorSenderMatch(sender, payload.memberKey) then
      return
    end

    local pending = sessionRuntime.pendingProfileDeltaAcks[payload.changeId]
    local responseAllowed, responseReason = profileSyncMetaOps.validatePendingProfileDeltaResponse(pending, payload)
    if not responseAllowed then
      profileSyncMetaOps.recordInboundPayloadReject("PDELTA_ACK", sender, fields, responseReason)
      return
    end
    local existingMember = FindSessionMember(activeSession, payload.memberKey)
    if payload.ackPhase == "QUEUED" then
      pending.queued = type(pending.queued) == "table" and pending.queued or {}
      pending.queued[payload.memberKey] = GetProfileCheckpointSyncTime()
      if type(existingMember) == "table" then
        existingMember.profileApplyAckPhase = "QUEUED"
        existingMember.profileApplyQueuedAt = GetProfileCheckpointSyncTime()
        existingMember.profileApplyPendingId = payload.changeId
        existingMember.profileApplyPendingKind = "DELTA"
      end
      sessionUiOps.refreshCurrentAndSyncSections(true, {
        defer = false,
        forceImmediate = true,
      })
      return
    end
    pending.missing[payload.memberKey] = nil
    if type(pending.queued) == "table" then
      pending.queued[payload.memberKey] = nil
    end
    if not next(pending.missing) then
      sessionRuntime.pendingProfileDeltaAcks[payload.changeId] = nil
    else
      pending.updatedAt = GetProfileCheckpointSyncTime()
    end

    if type(existingMember) == "table" then
      existingMember.profileApplyAckPhase = nil
      existingMember.profileApplyQueuedAt = nil
      existingMember.profileApplyPendingId = nil
      existingMember.profileApplyPendingKind = nil
    end
    local incomingAckState = {
      sharedProfileId = FirstNonEmptyText(
        type(existingMember) == "table" and existingMember.sharedProfileId or nil,
        type(existingMember) == "table" and existingMember.profileId or nil
      ),
      settingsRevision = payload.settingsRevision,
      permissionsRevision = payload.permissionsRevision,
      operationalRevision = payload.operationalRevision,
      lootRevision = payload.lootRevision,
      sessionRevision = payload.sessionRevision,
      profileUpdatedAt = payload.profileUpdatedAt,
      settingsChecksum = payload.settingsChecksum,
      permissionsChecksum = payload.permissionsChecksum,
      operationalChecksum = payload.operationalChecksum,
      lootChecksum = payload.lootChecksum,
      sessionChecksum = payload.sessionChecksum,
      liveLootChecksum = type(existingMember) == "table" and TrimText(existingMember.liveLootChecksum) or "",
      archiveLootChecksum = type(existingMember) == "table" and TrimText(existingMember.archiveLootChecksum) or "",
    }
    local inboundAckGate = profileSyncMetaOps.evaluateInboundStampedStateWrite(
      existingMember,
      incomingAckState,
      {
        stateKind = "profile",
      }
    )
    if inboundAckGate.shouldSkip then
      if type(existingMember) == "table" then
        existingMember.lastProfileDeltaAck = math.max(
          tonumber(existingMember.lastProfileDeltaAck) or 0,
          tonumber(payload.sequence) or 0
        )
      end
      return
    end
    local previousVisibleState = BuildSessionVisibleMemberStateSignature(existingMember)
    local previousCurrentSessionDisplayContext = nil
    local previousCurrentSessionDisplay = nil
    if type(existingMember) == "table" then
      previousCurrentSessionDisplayContext = INTERNAL_API.LIDCOUNCIL_BuildHostCurrentSessionDisplayContext(
        activeSession,
        payload.profileName,
        payload.memberKey
      )
      previousCurrentSessionDisplay = INTERNAL_API.LIDCOUNCIL_BuildHostCurrentSessionMemberDisplayState(
        activeSession,
        payload.profileName,
        payload.memberKey,
        existingMember,
        previousCurrentSessionDisplayContext
      )
    end
    local ok, member = UpsertLootSessionMember(payload.profileName, payload.sessionId, payload.memberKey, {
      settingsRevision = payload.settingsRevision,
      permissionsRevision = payload.permissionsRevision,
      operationalRevision = payload.operationalRevision,
      lootRevision = payload.lootRevision,
      sessionRevision = payload.sessionRevision,
      settingsChecksum = payload.settingsChecksum,
      permissionsChecksum = payload.permissionsChecksum,
      operationalChecksum = payload.operationalChecksum,
      lootChecksum = payload.lootChecksum,
      sessionChecksum = payload.sessionChecksum,
      profileUpdatedAt = payload.profileUpdatedAt,
      lastSyncAt = time and time() or 0,
      suppressProfileTouch = true,
    })
    if ok and type(member) == "table" then
      member.lastProfileDeltaAck = math.max(tonumber(member.lastProfileDeltaAck) or 0, payload.sequence)
    end
    local updatedSyncCandidateSnapshot = previousCurrentSessionDisplay ~= nil and BuildActiveSyncCandidateSnapshot() or nil
    local updatedCurrentSessionDisplayContext = previousCurrentSessionDisplay ~= nil
      and INTERNAL_API.LIDCOUNCIL_BuildHostCurrentSessionDisplayContextFromBase(
        activeSession,
        payload.profileName,
        payload.memberKey,
        previousCurrentSessionDisplayContext,
        updatedSyncCandidateSnapshot
      )
      or nil
    INTERNAL_API.LIDCOUNCIL_HandleHostMemberPostUpdate(
      activeSession,
      payload.profileName,
      payload.sessionId,
      payload.memberKey,
      existingMember,
      ok and type(member) == "table" and member or nil,
      {
        previousVisibleState = previousVisibleState,
        previousCurrentSessionDisplay = previousCurrentSessionDisplay,
        currentSessionDisplayContext = previousCurrentSessionDisplayContext,
        updatedCurrentSessionDisplayContext = updatedCurrentSessionDisplayContext,
        flushDeferredJoinRows = ok and type(member) == "table",
        broadcastVisibleStateChange = ok and type(member) == "table",
        syncCandidateSnapshot = updatedSyncCandidateSnapshot,
        skipRefreshWhenUnchanged = true,
        refreshSyncManagementWhenUnchanged = true,
        defer = false,
        forceImmediate = true,
      }
    )
  end

  INTERNAL_API.LIDCOUNCIL_HandleProfileDeltaNack_Impl = function(fields, sender)
    local payload, payloadError = profileSyncMetaOps.parseInboundProfileDeltaNackPayload(fields, sender)
    if type(payload) ~= "table" then
      profileSyncMetaOps.recordInboundPayloadReject("PDELTA_NACK", sender, fields, payloadError)
      return
    end
    PruneAgedSessionRuntimeTracking(GetProfileCheckpointSyncTime())

    local activeSession, activeProfileName = GetActiveLootSession()
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if not DoesActiveSessionMatch(activeSession, activeProfileName, payload.sessionId, payload.profileName) then
      return
    end
    if not AreCharacterKeysSame(activeSession.host or "", selfKey) then
      return
    end
    if not IsClaimedActorSenderMatch(sender, payload.memberKey) then
      return
    end

    local pending = sessionRuntime.pendingProfileDeltaAcks[payload.changeId]
    local responseAllowed, responseReason = profileSyncMetaOps.validatePendingProfileDeltaResponse(pending, payload)
    if not responseAllowed then
      local recoveryAllowed, recoveryReason = profileSyncMetaOps.allowSupersededProfileDeltaRecoveryRequest(
        activeSession,
        payload
      )
      if not recoveryAllowed then
        profileSyncMetaOps.recordInboundPayloadReject(
          "PDELTA_NACK",
          sender,
          fields,
          recoveryReason or responseReason
        )
        return
      end
      if recoveryReason == "coalesced_superseded_recovery" then
        return
      end
    end
    if responseAllowed then
      pending.missing[payload.memberKey] = nil
      if not next(pending.missing) then
        sessionRuntime.pendingProfileDeltaAcks[payload.changeId] = nil
      else
        pending.updatedAt = GetProfileCheckpointSyncTime()
      end
    end
    local snapshotRecoveryReason = payload.reason ~= "" and payload.reason or "delta_recovery"
    local recoveryDelta = type(pending) == "table" and type(pending.delta) == "table"
      and pending.delta
      or profileSyncMetaOps.getProfileDeltaRecoverySource(payload)
    local syncCandidateSnapshot = BuildActiveSyncCandidateSnapshot()
    local queuedRecovery, queueRecoveryResult, recoveryError, recoveryKind, recoveryDetail = QueueTargetedDeltaRecoveryForMember(
      activeSession,
      payload.profileName,
      payload.sessionId,
      payload.memberKey,
      recoveryDelta,
      {
        mode = "LIVE",
        reason = snapshotRecoveryReason,
        syncCandidateSnapshot = syncCandidateSnapshot,
      }
    )
    local recoveryTransferKind = TrimText(type(recoveryDetail) == "table" and recoveryDetail.transferKind or "")
    local recoveryTransferKinds = CloneDecisionTextList(type(recoveryDetail) == "table" and recoveryDetail.transferKinds or {})
    local recoveryFallback = type(recoveryDetail) == "table" and recoveryDetail.fallback == true or recoveryKind == "full"
    local recoveryFallbackReason = TrimText(type(recoveryDetail) == "table" and recoveryDetail.fallbackReason or "")
    local recoveryFallbackReasons = CloneDecisionTextList(type(recoveryDetail) == "table" and recoveryDetail.fallbackReasons or {})
    local recoveryRequestedScope = TrimText(type(recoveryDetail) == "table" and recoveryDetail.requestedScope or "")
    local recoveryScopeEscalated = type(recoveryDetail) == "table" and recoveryDetail.scopeEscalated == true
    local recoveryFullSnapshotFallback = type(recoveryDetail) == "table" and recoveryDetail.fullSnapshotFallback == true
    local recoveryScopeEscalationKinds = CloneDecisionTextList(type(recoveryDetail) == "table" and recoveryDetail.scopeEscalationKinds or {})
    local recoveryCoalesced = type(recoveryDetail) == "table" and recoveryDetail.coalescedExistingRepair == true
    local recoveryQueuedCount = queuedRecovery and math.max(0, tonumber(queueRecoveryResult) or 0) or 0
    local recoveryState = queuedRecovery and (
      recoveryKind == "aligned" and "aligned"
      or (recoveryCoalesced and "coalesced")
      or (recoveryQueuedCount == 0 and type(recoveryDetail) == "table" and recoveryDetail.deferredPatchState == true and "deferred")
      or (recoveryFullSnapshotFallback and "full_fallback")
      or (recoveryScopeEscalated and "widened")
      or "recovered"
    ) or "failed"
    local recoverySummary = BuildDeltaRecoverySummary(
      payload.memberKey,
      recoveryKind,
      queuedRecovery and queueRecoveryResult or 0,
      recoveryDetail,
      queuedRecovery and nil or recoveryError
    )
    if type(RecordProfileSyncDecision) == "function" then
      RecordProfileSyncDecision("handle_delta_nack", {
        action = queuedRecovery and (
          recoveryKind == "aligned" and "skipped_aligned_recovery"
          or (recoveryCoalesced and "coalesced_existing_recovery")
          or (recoveryQueuedCount == 0 and type(recoveryDetail) == "table" and recoveryDetail.deferredPatchState == true and "deferred_patch_state_recovery")
          or (recoveryKind == "scoped_snapshot" and "queued_scoped_snapshot_recovery"
            or (recoveryKind == "full" and "queued_snapshot_recovery" or "queued_targeted_recovery"))
        )
          or "snapshot_recovery_failed",
        sessionId = payload.sessionId,
        profileName = payload.profileName,
        mode = "LIVE",
        reason = snapshotRecoveryReason,
        transferKind = recoveryTransferKind,
        transferKinds = recoveryTransferKinds,
        target = payload.memberKey,
        targetCount = 1,
        queuedCount = recoveryQueuedCount,
        requestedScope = recoveryRequestedScope,
        scopeEscalated = recoveryScopeEscalated,
        fullSnapshotFallback = recoveryFullSnapshotFallback,
        scopeEscalationKinds = recoveryScopeEscalationKinds,
        fallback = recoveryFallback,
        fallbackReason = recoveryFallbackReason,
        fallbackReasons = recoveryFallbackReasons,
        error = queuedRecovery and nil or recoveryError,
      })
    end
    local ok, member = profileSyncMetaOps.persistSessionMemberRepairOutcome(
      activeSession,
      payload.profileName,
      payload.sessionId,
      payload.memberKey,
      recoveryQueuedCount,
      recoveryDetail,
      queuedRecovery and nil or recoveryError,
      {
        sourceLabel = "delta recovery",
        state = recoveryState,
        repairKind = recoveryKind,
        requestedScope = recoveryRequestedScope,
        summary = recoverySummary,
        additionalFields = {
          lastSyncAt = time and time() or 0,
        },
      }
    )
    if ok and type(member) == "table" then
      member.lastProfileDeltaRecovery = math.max(tonumber(member.lastProfileDeltaRecovery) or 0, payload.sequence)
    end
    if TrimText(recoverySummary) ~= "" then
      local recoveryRuntimeLevel = "warn"
      if queuedRecovery then
        local queuedRecoveryCount = math.max(0, tonumber(queueRecoveryResult) or 0)
        if recoveryKind == "aligned"
          or recoveryCoalesced
          or (queuedRecoveryCount == 0 and type(recoveryDetail) == "table" and recoveryDetail.deferredPatchState == true)
        then
          recoveryRuntimeLevel = "info"
        else
          recoveryRuntimeLevel = "success"
        end
      end
      sessionLifecycleOps.emitRepairRuntimeState(activeSession.id, payload.profileName, "host_snapshot_sent",
        recoveryRuntimeLevel,
        recoverySummary, {
          sender = selfKey,
          noticeText = recoverySummary,
          printNotice = false,
          printWhenChangedOnly = true,
          refreshSyncManagement = true,
          coalesceWindowSeconds = 2.5,
          coalesceKey = "delta_recovery_dispatch|" .. string.lower(TrimText(payload.memberKey)),
          coalesceSignature = "delta_recovery_dispatch",
        })
      profileSyncMetaOps.recordStandardRepairHistory("delta_recovery", recoverySummary, {
        profileName = payload.profileName,
        sessionId = payload.sessionId,
        memberKey = payload.memberKey,
        dedupeWindowSeconds = 6,
      })
    end
  end

  INTERNAL_API.LIDCOUNCIL_ActivatePreparedLootSessionFlow_Impl = function(opts)
    opts = type(opts) == "table" and opts or {}
    local activeSession, profileName = GetActiveLootSession()
    if not activeSession or not profileName then
      Print(sessionLifecycleOps.buildFlowNoticeText("start_missing_prepared"))
      return false, "No prepared session."
    end

    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if not AreCharacterKeysSame(activeSession.host or "", selfKey) then
      Print(sessionLifecycleOps.buildFlowNoticeText("start_only_host"))
      return false, "Only the host can start the session."
    end

    local blocked, blockedMessage = RejectCombatLockedAction("Start Session")
    if blocked then
      return false, blockedMessage
    end

    if IsLiveSession(activeSession) then
      Print(sessionLifecycleOps.buildFlowNoticeText("start_already_active", {
        profileName = profileName,
      }))
      return true, activeSession
    end
    if not IsPreparedSession(activeSession) then
      Print(sessionLifecycleOps.buildFlowNoticeText("start_not_prepared"))
      return false, "Session is not prepared."
    end

    if opts.force ~= true then
      local warnings = {}
      local syncCandidateSnapshot = BuildActiveSyncCandidateSnapshot()
      local candidates = type(syncCandidateSnapshot.list) == "table" and syncCandidateSnapshot.list or {}
      local syncSummary, syncWarningLines = BuildStartSessionSyncWarning(candidates)
      local queueStatus = optionalApiOps.getSessionCommQueueStatus()
      if (tonumber(syncSummary.bootstrapPending) or 0) > 0 or (tonumber(syncSummary.bootstrapReview) or 0) > 0 then
        if type(queueStatus) == "table" and math.max(0, tonumber(queueStatus.pending) or 0) > 0 then
          warnings[#warnings + 1] = "The sync queue still has " .. tostring(math.max(0, tonumber(queueStatus.pending) or 0)) .. " pending addon message(s)."
        end
      end
      for _, line in ipairs(syncWarningLines) do
        warnings[#warnings + 1] = line
      end
      if #warnings > 0 then
        if type(StaticPopupDialogs) == "table" and not StaticPopupDialogs.LIDCOUNCIL_START_SESSION_WARNING then
          StaticPopupDialogs.LIDCOUNCIL_START_SESSION_WARNING = {
            text = "%s\n\nCancel and wait, or force start with the host profile as authoritative. Joined members that are already roll-ready can continue while the remaining shared history syncs in the background. Members still waiting on bootstrap may not receive the roll popup yet. Force Start does not queue another full profile push.",
            button1 = "Force Start",
            button2 = CANCEL,
            timeout = 0,
            whileDead = 1,
            hideOnEscape = 1,
            preferredIndex = 3,
            OnAccept = function()
              INTERNAL_API.LIDCOUNCIL_ActivatePreparedLootSessionFlow_Impl({ force = true })
            end,
          }
        end
        local warningText = table.concat(warnings, "\n")
        if type(StaticPopup_Show) == "function" then
          StaticPopup_Show("LIDCOUNCIL_START_SESSION_WARNING", warningText)
        else
          Print(sessionLifecycleOps.buildFlowNoticeText("start_warning_fallback", {
            warningText = warningText,
          }))
        end
        return false, "START_CONFIRM_REQUIRED", warningText
      end
    end

    local existingSelfMember = FindSessionMember(activeSession, selfKey)
    local previousLocalAutoPassEnabled = type(deps.GetLocalAutoPassEnabled) == "function"
      and (deps.GetLocalAutoPassEnabled() and true or false)
      or nil
    local previousMemberAutoPassEnabled = type(existingSelfMember) == "table"
      and (existingSelfMember.localAutoPassEnabled == true)
      or false

    SetLocalAutoPassEnabled(false)
    UpsertLootSessionMember(profileName, activeSession.id, selfKey, {
      localAutoPassEnabled = false,
      suppressProfileTouch = true,
    })

    local session, err = deps.ActivateLootSession(profileName, activeSession.id)
    if not session then
      if previousLocalAutoPassEnabled ~= nil then
        SetLocalAutoPassEnabled(previousLocalAutoPassEnabled)
      end
      if type(existingSelfMember) == "table" then
        UpsertLootSessionMember(profileName, activeSession.id, selfKey, {
          localAutoPassEnabled = previousMemberAutoPassEnabled,
          suppressProfileTouch = true,
        })
      end
      Print(sessionLifecycleOps.buildFlowNoticeText("start_prepared_failed", {
        error = err,
      }))
      sessionUiOps.refreshCurrentAndAutoPassSections()
      return false, err
    end

    RefreshHostSessionMemberState(session.profileName, session.id, {
      suppressCheckpoint = true,
    })
    optionalApiOps.beginProfileSnapshotDiagnosticsForSession(session.id, session.activatedAt)

    local distribution = deps.GetGroupDistribution()
    if distribution then
      SendComm(
        "BEGIN",
        distribution,
        nil,
        session.id,
        session.profileName,
        TrimText(select(1, deps.GetLootProfileId(session.profileName)) or ""),
        session.host,
        session.activatedAt or (time and time() or 0),
        deps.GetLootProfileMaster(session.profileName),
        GetCommProtocolMarker()
      )
    end

    -- Starting the next raid is the single automatic retry boundary for the
    -- newest completed history record. It remains P3/background work and does
    -- not delay the live session or broaden into a full Session History push.
    if type(profileSyncMetaOps.queueLatestSessionHistoryCatchup) == "function" then
      for memberKey, member in pairs(type(session.members) == "table" and session.members or {}) do
        local resolvedMemberKey = NormalizeCharacterKey(memberKey)
        if resolvedMemberKey ~= ""
          and not AreCharacterKeysSame(resolvedMemberKey, selfKey)
          and type(member) == "table"
          and string.upper(TrimText(member.status or "JOINED")) == "JOINED"
        then
          profileSyncMetaOps.queueLatestSessionHistoryCatchup(
            session,
            session.profileName,
            session.id,
            resolvedMemberKey,
            member,
            "latest_session_history_start_retry",
            { startRetry = true }
          )
        end
      end
    end

    sessionLifecycleOps.emitTransitionStateNotice(session.id, session.profileName, "host_started", {
      profileName = session.profileName,
      sender = selfKey,
      refreshEditor = false,
    })
    sessionUiOps.refreshPanelsAndLiveBoard()
    return true, session
  end

  INTERNAL_API.LIDCOUNCIL_RequestActiveProfileSnapshotFlow_Impl = function(targetMemberKey, options)
    options = type(options) == "table" and options or {}
    local activeSession, profileName = GetActiveLootSession()
    if not activeSession or not profileName then
      Print("No active loot session.")
      return false, "No active session."
    end

    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if not AreCharacterKeysSame(activeSession.host or "", selfKey) then
      Print("Only the loot session host can pull or preview a shared profile.")
      return false, "Only the host can pull or preview a shared profile."
    end

    local previewOnly = string.upper(TrimText(options.mode)) == "PREVIEW" or options.previewOnly == true
    local actionLabel = previewOnly and "Preview Member Repair" or "Pull Member Repair"
    local blocked, blockedMessage = RejectCombatLockedAction(actionLabel)
    if blocked then
      return false, blockedMessage
    end

    local resolvedTarget = NormalizeCharacterKey(targetMemberKey)
    if resolvedTarget == "" then
      Print("Select a joined session member first.")
      return false, "No target selected."
    end
    if AreCharacterKeysSame(resolvedTarget, selfKey) then
      Print("The host already has the local shared profile copy.")
      return false, "Target must be another joined member."
    end
    if not IsJoinedSessionCharacter(activeSession, resolvedTarget) then
      Print("That character is not currently joined to the active loot session.")
      return false, "Target is not joined."
    end

    local requestedDomains, requestedSubdomains, requestMode
    if type(options.domains) == "table" or type(options.subdomains) == "table" then
      requestedDomains = type(options.domains) == "table" and options.domains or nil
      requestedSubdomains = type(options.subdomains) == "table" and options.subdomains or nil
      requestMode = type(requestedSubdomains) == "table" and #requestedSubdomains > 0 and "precise" or "targeted"
    else
      requestedDomains, requestedSubdomains, requestMode = BuildMemberRepairRequestDomains(resolvedTarget, previewOnly)
    end
    if not previewOnly and type(requestedDomains) == "table" and #requestedDomains == 0 then
      Print("The selected member does not currently have newer shared-profile data to pull.")
      return false, "No member-newer scope."
    end
    local requestedDomainCsv = type(requestedDomains) == "table" and table.concat(requestedDomains, ",") or ""
    local requestedSubdomainCsv = type(requestedSubdomains) == "table" and #requestedSubdomains > 0
      and table.concat(requestedSubdomains, ",")
      or ""
    if #requestedSubdomainCsv > 80 then
      requestedSubdomainCsv = ""
      if requestMode == "precise" then
        requestMode = "targeted"
      end
    end

    local patchManifestAttempted = false
    local patchManifestSent, patchManifestTransfers, patchManifestToken = false, 0, ""
    if requestMode == "precise"
      and type(requestedSubdomains) == "table"
      and #requestedSubdomains > 0
      and type(profileSyncMetaOps.sendPatchManifest) == "function"
    then
      patchManifestAttempted = true
      patchManifestSent, patchManifestTransfers, patchManifestToken = profileSyncMetaOps.sendPatchManifest(profileName, activeSession.id, resolvedTarget, requestedSubdomains)
      patchManifestTransfers = math.max(0, tonumber(patchManifestTransfers) or 0)
    end
    local requestedPatchManifestToken = patchManifestSent and TrimText(patchManifestToken) or ""
    if patchManifestAttempted and requestedPatchManifestToken == "" then
      requestedPatchManifestToken = "MISS"
    end

    local sent = SendComm(
      "PSYNC_REQ",
      "WHISPER",
      resolvedTarget,
      activeSession.id,
      profileName,
      TrimText(select(1, deps.GetLootProfileId(profileName)) or ""),
      previewOnly and "PREVIEW" or "PULL",
      requestedDomainCsv,
      requestedSubdomainCsv,
      requestedPatchManifestToken
    )
    if sent then
      local runtimeStateMessage = (previewOnly and "Requested a member shared profile change preview from " or "Requested a member shared profile pull from ")
        .. tostring(resolvedTarget)
        .. (requestMode == "precise" and " using the loaded precise checksum scope." or ".")
        .. (patchManifestSent and (" Nested host patch manifests were shared first (" .. tostring(patchManifestTransfers) .. " transfer" .. (patchManifestTransfers == 1 and "" or "s") .. ").") or "")
      local noticeText = (previewOnly and "Requested a shared profile change preview from " or "Requested to pull shared profile data from ")
        .. tostring(resolvedTarget)
        .. (requestMode == "precise" and " using the loaded precise checksum scope." or ".")
        .. (patchManifestSent and " Host patch manifests were sent ahead of the request." or "")
      sessionLifecycleOps.emitSyncRuntimeState(activeSession.id, profileName, previewOnly and "preview_request_sent" or "request_sent", "warn", runtimeStateMessage, {
        sender = resolvedTarget,
        noticeText = noticeText,
        refreshSyncManagement = true,
        coalesceWindowSeconds = 1.5,
        coalesceKey = (previewOnly and "preview_request|" or "request_pull|") .. string.lower(TrimText(resolvedTarget)),
        coalesceSignature = previewOnly and "preview_request_sent" or "request_sent",
      })
    else
      Print((previewOnly and "Could not request a shared profile change preview from " or "Could not request shared profile pull from ") .. tostring(resolvedTarget) .. ".")
    end
    return sent, resolvedTarget
  end

  INTERNAL_API.LIDCOUNCIL_RemoveActiveSessionMemberFlow_Impl = function(targetMemberKey)
    local activeSession, profileName = GetActiveLootSession()
    if not activeSession or not profileName then
      Print("No active loot session.")
      return false, "No active session."
    end

    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if not AreCharacterKeysSame(activeSession.host or "", selfKey) then
      Print("Only the loot session host can remove joined members.")
      return false, "Only the host can remove joined members."
    end

    local blocked, blockedMessage = RejectCombatLockedAction("Remove Joined Member")
    if blocked then
      return false, blockedMessage
    end

    local resolvedTarget = NormalizeCharacterKey(targetMemberKey)
    if resolvedTarget == "" then
      Print("Select a joined session member first.")
      return false, "No target selected."
    end
    if AreCharacterKeysSame(resolvedTarget, selfKey) then
      Print("The session host cannot remove themselves.")
      return false, "Cannot remove host."
    end

    local member = FindSessionMember(activeSession, resolvedTarget)
    if type(member) ~= "table" then
      Print("That character is not currently in the joined member list.")
      return false, "Session member not found."
    end
    local currentSectionProbeMemberKeys = {
      NormalizeCharacterKey(activeSession.host or ""),
      resolvedTarget,
    }
    local previousCurrentSectionState = INTERNAL_API.LIDCOUNCIL_BuildCurrentSectionStateSignature(activeSession)
    local previousCurrentSectionProbe = INTERNAL_API.LIDCOUNCIL_BuildCurrentSectionChangeProbe(
      activeSession,
      currentSectionProbeMemberKeys
    )

    local removedMember = {}
    for key, value in pairs(member) do
      removedMember[key] = value
    end
    removedMember.status = "REMOVED"
    removedMember.leftAt = time and time() or 0

    local ok, result = deps.RemoveLootSessionMember(profileName, activeSession.id, resolvedTarget)
    if not ok then
      Print(tostring(result or "Could not remove joined member."))
      return false, result
    end
    ClearSessionMemberTargetedSyncRuntime(activeSession.id, profileName, resolvedTarget, activeSession)

    BroadcastMember(profileName, activeSession.id, resolvedTarget, type(result) == "table" and result or removedMember)
    RefreshHostSessionMemberState(profileName, activeSession.id, {
      suppressCheckpoint = true,
    })
    SendComm("STOP", "WHISPER", resolvedTarget, activeSession.id, profileName, activeSession.host, time and time() or 0)
    sessionLifecycleOps.emitMemberStateNotice(activeSession.id, profileName, "member_removed", {
      memberKey = resolvedTarget,
      sender = selfKey,
      refreshEditor = false,
    })
    local currentSectionChanged = INTERNAL_API.LIDCOUNCIL_GetCurrentSectionChangeFromProbe(
      activeSession,
      previousCurrentSectionState,
      previousCurrentSectionProbe,
      currentSectionProbeMemberKeys,
      function()
        return INTERNAL_API.LIDCOUNCIL_BuildCurrentSectionStateSignature(activeSession)
      end
    )
    sessionUiOps.refreshCurrentAndSyncSections(currentSectionChanged)
    return true
  end

  INTERNAL_API.LIDCOUNCIL_LeaveActiveSessionFlow_Impl = function()
    local activeSession, profileName = GetActiveLootSession()
    if not activeSession or not profileName then
      Print("No active loot session.")
      return false, "No active session."
    end

    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if selfKey == "" then
      Print("Could not resolve your Character-Realm key.")
      return false, "Character-Realm key unavailable."
    end
    if AreCharacterKeysSame(activeSession.host or "", selfKey) then
      Print("The loot session host must stop the current session instead of leaving it.")
      return false, "The host cannot leave the active session."
    end
    if not IsJoinedSessionCharacter(activeSession, selfKey) then
      Print("You are not currently joined to this session.")
      return false, "Local character is not joined."
    end

    local blocked, blockedMessage = RejectCombatLockedAction("Leave Session")
    if blocked then
      return false, blockedMessage
    end

    local leftAt = time and time() or 0
    local commProfileName = TrimText(activeSession.remoteProfileName) ~= "" and activeSession.remoteProfileName or profileName
    local existingSelfMember = FindSessionMember(activeSession, selfKey)
    local previousMemberStatus = type(existingSelfMember) == "table"
      and TrimText(existingSelfMember.status or "")
      or "JOINED"
    local previousMemberLeftAt = type(existingSelfMember) == "table"
      and existingSelfMember.leftAt
      or nil
    local currentSectionProbeMemberKeys = { selfKey }
    local previousCurrentSectionState = INTERNAL_API.LIDCOUNCIL_BuildCurrentSectionStateSignature(activeSession)
    local previousCurrentSectionProbe = INTERNAL_API.LIDCOUNCIL_BuildCurrentSectionChangeProbe(
      activeSession,
      currentSectionProbeMemberKeys
    )

    UpsertLootSessionMember(profileName, activeSession.id, selfKey, {
      status = "LEFT",
      leftAt = leftAt,
      suppressProfileTouch = true,
    })

    local ok, result = FinishLootSession(profileName, activeSession.id, leftAt, "LEFT")
    if not ok then
      if type(existingSelfMember) == "table" then
        UpsertLootSessionMember(profileName, activeSession.id, selfKey, {
          status = previousMemberStatus ~= "" and previousMemberStatus or "JOINED",
          leftAt = previousMemberLeftAt,
          suppressProfileTouch = true,
        })
      end
      if result then
        Print(tostring(result))
      end
      local currentSectionChanged = INTERNAL_API.LIDCOUNCIL_GetCurrentSectionChangeFromProbe(
        activeSession,
        previousCurrentSectionState,
        previousCurrentSectionProbe,
        currentSectionProbeMemberKeys,
        function()
          return INTERNAL_API.LIDCOUNCIL_BuildCurrentSectionStateSignature(activeSession)
        end
      )
      sessionUiOps.refreshCurrentAndSyncSections(currentSectionChanged)
      return false, result
    end
    local notifiedHost, notifyError = SendComm(
      "LEAVE",
      "WHISPER",
      activeSession.host,
      activeSession.id,
      commProfileName,
      selfKey,
      leftAt
    )
    sessionLifecycleOps.finalizeEndedSessionEvent(activeSession.id, profileName, "member_left", {
      profileName = profileName,
      sender = selfKey,
      activeSession = activeSession,
      notifiedHost = notifiedHost,
      notifyError = notifyError,
    })
    return true, result
  end

  function sessionLifecycleOps.getSessionFinalizationMissingCount(tracker)
    local count = 0
    for _, missing in pairs(type(tracker) == "table" and tracker.missing or {}) do
      if missing == true then
        count = count + 1
      end
    end
    return count
  end

  function sessionLifecycleOps.deferSessionFinalizationToP3(tracker)
    if type(tracker) ~= "table" then
      return false
    end
    tracker.state = "deferred_p3"
    tracker.unresolved = {}
    for memberKey, missing in pairs(tracker.missing or {}) do
      if missing == true then
        tracker.unresolved[memberKey] = true
      end
    end
    tracker.updatedAt = GetProfileCheckpointSyncTime()
    return true
  end

  function sessionLifecycleOps.sendSessionFinalizationStop(tracker, distribution)
    if type(tracker) ~= "table" then
      return false, "missing_session_finalization_tracker"
    end
    if TrimText(distribution) ~= "" then
      return SendComm(
        "STOP",
        distribution,
        nil,
        tracker.sessionId,
        tracker.profileName,
        tracker.host,
        tracker.endedAt,
        tracker.token
      )
    end
    local sentAny = false
    local lastError = nil
    for memberKey, missing in pairs(tracker.missing or {}) do
      if missing == true then
        local sent, sendError = SendComm(
          "STOP",
          "WHISPER",
          memberKey,
          tracker.sessionId,
          tracker.profileName,
          tracker.host,
          tracker.endedAt,
          tracker.token
        )
        sentAny = sentAny or sent == true
        if sent ~= true then
          lastError = sendError
        end
      end
    end
    return sentAny, lastError
  end

  function sessionLifecycleOps.checkSessionFinalizationReceipts(token)
    local tracker = sessionRuntime.pendingSessionFinalizations[TrimText(token)]
    if type(tracker) ~= "table" then
      return false, "missing_session_finalization_tracker"
    end
    local missingCount = sessionLifecycleOps.getSessionFinalizationMissingCount(tracker)
    local action = INTERNAL_API.LIDCOUNCIL_ResolveSessionFinalizationReceiptAction_Impl(
      missingCount,
      tracker.attempts,
      sessionConfig.sessionFinalizationMaxAttempts
    )
    tracker.updatedAt = GetProfileCheckpointSyncTime()
    if action == "complete" then
      tracker.state = "complete"
      return true
    end
    if action == "defer_p3" then
      sessionLifecycleOps.deferSessionFinalizationToP3(tracker)
      return false, "session_finalization_deferred_to_p3"
    end

    tracker.attempts = math.max(1, tonumber(tracker.attempts) or 1) + 1
    tracker.state = "retrying"
    sessionLifecycleOps.sendSessionFinalizationStop(tracker, nil)
    tracker.state = "waiting"
    if type(Compat) ~= "table" or type(Compat.After) ~= "function" then
      sessionLifecycleOps.deferSessionFinalizationToP3(tracker)
      return false, "session_finalization_timer_unavailable"
    end
    Compat.After(sessionConfig.sessionFinalizationAckTimeoutSeconds, function()
      sessionLifecycleOps.checkSessionFinalizationReceipts(token)
    end)
    return true
  end

  function sessionLifecycleOps.beginSessionFinalizationTransaction(activeSession, result, profileName, selfKey)
    if type(activeSession) ~= "table" or type(result) ~= "table" then
      return false, "missing_session_finalization_state"
    end
    local sessionId = TrimText(result.id or activeSession.id)
    local resolvedProfileName = TrimText(profileName or result.profileName)
    local host = NormalizeCharacterKey(result.host or activeSession.host or selfKey)
    if sessionId == "" or resolvedProfileName == "" or host == "" then
      return false, "missing_session_finalization_identity"
    end

    sessionRuntime.sessionFinalizationSequence = math.max(0, tonumber(sessionRuntime.sessionFinalizationSequence) or 0) + 1
    local endedAt = math.max(0, tonumber(result.endedAt) or tonumber(time and time() or 0) or 0)
    local token = "STP-" .. sessionId .. "-" .. tostring(math.floor(endedAt)) .. "-"
      .. tostring(sessionRuntime.sessionFinalizationSequence)
    local missing = {}
    local targets = {}
    for memberKey, member in pairs(activeSession.members or {}) do
      local resolvedMemberKey = NormalizeCharacterKey(memberKey)
      if resolvedMemberKey ~= ""
        and not AreCharacterKeysSame(resolvedMemberKey, selfKey)
        and type(member) == "table"
        and string.upper(TrimText(member.status or "JOINED")) == "JOINED"
      then
        missing[resolvedMemberKey] = true
        targets[resolvedMemberKey] = true
      end
    end

    local now = GetProfileCheckpointSyncTime()
    local tracker = {
      sessionId = sessionId,
      profileName = resolvedProfileName,
      host = host,
      endedAt = endedAt,
      token = token,
      targets = targets,
      missing = missing,
      receipts = {},
      attempts = 1,
      state = next(missing) and "waiting" or "complete",
      queuedAt = now,
      updatedAt = now,
    }
    if next(missing) then
      sessionRuntime.pendingSessionFinalizations[token] = tracker
    end

    if not next(missing) then
      return true, tracker
    end
    local distribution = deps.GetGroupDistribution()
    sessionLifecycleOps.sendSessionFinalizationStop(tracker, distribution)
    if type(Compat) ~= "table" or type(Compat.After) ~= "function" then
      sessionLifecycleOps.deferSessionFinalizationToP3(tracker)
      return true, tracker
    end
    Compat.After(sessionConfig.sessionFinalizationAckTimeoutSeconds, function()
      sessionLifecycleOps.checkSessionFinalizationReceipts(token)
    end)
    return true, tracker
  end

  function sessionLifecycleOps.sendSessionFinalizationReceipt(payload, receiptState)
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if type(payload) ~= "table" or selfKey == "" or TrimText(payload.token) == "" then
      return false, "missing_session_finalization_receipt_identity"
    end
    return SendComm(
      "STOP_ACK",
      "WHISPER",
      payload.host,
      payload.sessionId,
      payload.profileName,
      selfKey,
      payload.token,
      receiptState
    )
  end

  INTERNAL_API.LIDCOUNCIL_StopLootSessionFlow_Impl = function()
    local activeSession, profileName = GetActiveLootSession()
    if not activeSession then
      Print("No active loot session.")
      return false, "No active session."
    end
    local blocked, blockedMessage = RejectCombatLockedAction("Stop Session")
    if blocked then
      return false, blockedMessage
    end

    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if not AreCharacterKeysSame(activeSession.host or "", selfKey) then
      Print("Only the loot session host can stop the current session.")
      return false, "Only the host can stop the active session."
    end

    local finalizationSession = {
      id = activeSession.id,
      host = activeSession.host,
      members = {},
    }
    for memberKey, member in pairs(type(activeSession.members) == "table" and activeSession.members or {}) do
      finalizationSession.members[memberKey] = {
        status = type(member) == "table" and member.status or "JOINED",
      }
    end

    local ok, result = deps.StopLootSession()
    if not ok then
      if result then
        Print(tostring(result))
      end
      sessionUiOps.refreshPanelsAndLiveBoard()
      return false, result
    end

    sessionLifecycleOps.beginSessionFinalizationTransaction(
      finalizationSession,
      result,
      profileName or result.profileName,
      selfKey
    )
    sessionLifecycleOps.finalizeEndedSessionEvent(result.id, profileName or result.profileName or "", "host_stopped", {
      profileName = profileName or result.profileName or "Unknown",
      sender = selfKey,
      activeSession = activeSession,
    })
    return true, result
  end

  INTERNAL_API.LIDCOUNCIL_HandleGroupRosterChanged_Impl = function()
    PruneAgedSessionRuntimeTracking(GetProfileCheckpointSyncTime())
    local activeSession, profileName = GetActiveLootSession()
    if not activeSession or not profileName then
      return false, "No active session."
    end

    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if AreCharacterKeysSame(activeSession.host or "", selfKey) then
      local leftCount = 0
      local leftAt = time and time() or 0
      local currentSectionProbeMemberKeys = {
        NormalizeCharacterKey(activeSession.host or ""),
      }
      local previousCurrentSectionState = INTERNAL_API.LIDCOUNCIL_BuildCurrentSectionStateSignature(activeSession)
      local previousCurrentSectionProbe = INTERNAL_API.LIDCOUNCIL_BuildCurrentSectionChangeProbe(
        activeSession,
        currentSectionProbeMemberKeys
      )
      for memberKey, member in pairs(type(activeSession.members) == "table" and activeSession.members or {}) do
        local resolvedMemberKey = NormalizeCharacterKey(memberKey)
        local memberStatus = string.upper(TrimText(type(member) == "table" and member.status or "JOINED"))
        if resolvedMemberKey ~= "" and not AreCharacterKeysSame(resolvedMemberKey, selfKey) and memberStatus == "JOINED" and not IsCurrentGroupCharacter(resolvedMemberKey) then
          local ok, updatedMember = UpsertLootSessionMember(profileName, activeSession.id, resolvedMemberKey, {
            status = "LEFT",
            leftAt = leftAt,
            joinedAt = type(member) == "table" and member.joinedAt or nil,
          })
          if ok then
            ClearSessionMemberTargetedSyncRuntime(activeSession.id, profileName, resolvedMemberKey, activeSession)
            BroadcastMember(profileName, activeSession.id, resolvedMemberKey, updatedMember or member)
            leftCount = leftCount + 1
            currentSectionProbeMemberKeys[#currentSectionProbeMemberKeys + 1] = resolvedMemberKey
          end
        end
      end
      if leftCount > 0 then
        RefreshHostSessionMemberState(profileName, activeSession.id, {
          suppressCheckpoint = true,
        })
        local currentSectionChanged = INTERNAL_API.LIDCOUNCIL_GetCurrentSectionChangeFromProbe(
          activeSession,
          previousCurrentSectionState,
          previousCurrentSectionProbe,
          currentSectionProbeMemberKeys,
          function()
            return INTERNAL_API.LIDCOUNCIL_BuildCurrentSectionStateSignature(activeSession)
          end
        )
        sessionUiOps.refreshCurrentAndSyncSections(currentSectionChanged)
        return true, tostring(leftCount) .. " member(s) marked as left."
      end
      return false, "Local host session stays active."
    end

    local hostKey = NormalizeCharacterKey(activeSession.host or "")
    local shouldLeaveSession = deps.GetGroupDistribution() == nil
    if not shouldLeaveSession and hostKey ~= "" then
      shouldLeaveSession = not IsCurrentGroupCharacter(hostKey)
    end
    if not shouldLeaveSession then
      return false, "Session host is still in the current group."
    end

    local endedAt = time and time() or 0
    local ok = FinishLootSession(profileName, activeSession.id, endedAt, "FINISHED")
    if ok then
      sessionLifecycleOps.finalizeEndedSessionEvent(activeSession.id, profileName, "left_group", {
        profileName = profileName,
        sender = hostKey,
        activeSession = activeSession,
      })
      return true, activeSession
    end

    return false, "Could not end local session."
  end

  local function BroadcastAutoPassNotice(sessionId, profileName, memberKey, enabled, channel, target)
    local distribution = channel or deps.GetGroupDistribution()
    if not distribution then
      return false
    end
    local runtimeNow = GetProfileCheckpointSyncTime()
    PruneAgedSessionRuntimeTracking(runtimeNow)
    local stateKey = BuildRecentStatePacketSendKey(
      "APNOTICE",
      sessionId,
      profileName,
      memberKey,
      distribution,
      target
    )
    local stateSignature = enabled and "1" or "0"
    local recentState = GetRecentStatePacketSendInfo(stateKey, runtimeNow)
    local recentSentAt = math.max(0, tonumber(type(recentState) == "table" and recentState.sentAt or 0) or 0)
    if type(recentState) == "table"
      and recentState.signature == stateSignature
      and (runtimeNow - recentSentAt) < sessionConfig.statePacketSendDedupeSeconds
    then
      return true
    end
    local sent = SendComm(
      "APNOTICE",
      distribution,
      target,
      sessionId,
      profileName,
      memberKey,
      enabled and "1" or "0"
    )
    if sent then
      RememberRecentStatePacketSend(stateKey, stateSignature, runtimeNow)
    end
    return sent
  end

  INTERNAL_API.LIDCOUNCIL_NotifyLocalAutoPassChanged_Impl = function(enabled, suppressLocalPrint)
    local blocked, blockedMessage = RejectCombatLockedAction("Change Auto Pass")
    if blocked then
      return false, blockedMessage
    end
    local resolvedEnabled = enabled and true or false
    local activeSession, profileName = GetActiveLootSession()
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")

    if not suppressLocalPrint then
      if activeSession and profileName then
        Print(sessionLifecycleOps.buildMemberNoticeText("local_autopass_session", {
          profileName = profileName,
          enabled = resolvedEnabled,
        }))
      else
        Print(sessionLifecycleOps.buildMemberNoticeText("local_autopass_global", {
          enabled = resolvedEnabled,
        }))
      end
    end

    if not activeSession or not profileName or selfKey == "" then
      sessionUiOps.refreshAutoPassSection()
      return true, resolvedEnabled
    end

    local isHost = AreCharacterKeysSame(activeSession.host or "", selfKey)
    local isJoined = IsJoinedSessionCharacter(activeSession, selfKey)
    local existingSelfMember = FindSessionMember(activeSession, selfKey)
    local previousVisibleState = BuildSessionVisibleMemberStateSignature(existingSelfMember)
    local updatedSelfMember = existingSelfMember
    if isHost then
      local ok, member = UpsertLootSessionMember(profileName, activeSession.id, selfKey, {
        localAutoPassEnabled = resolvedEnabled,
        suppressProfileTouch = true,
      })
      if ok then
        updatedSelfMember = member or (type(activeSession.members) == "table" and activeSession.members[selfKey]) or existingSelfMember
        local broadcastData = member or (type(activeSession.members) == "table" and activeSession.members[selfKey]) or {
          name = selfKey,
          status = "JOINED",
          joinedAt = time and time() or 0,
          localAutoPassEnabled = resolvedEnabled,
        }
        BroadcastMember(profileName, activeSession.id, selfKey, broadcastData)
        BroadcastAutoPassNotice(activeSession.id, profileName, selfKey, resolvedEnabled)
      end
    elseif isJoined then
      UpsertLootSessionMember(profileName, activeSession.id, selfKey, {
        localAutoPassEnabled = resolvedEnabled,
        suppressProfileTouch = true,
      })
      updatedSelfMember = (type(activeSession.members) == "table" and activeSession.members[selfKey]) or existingSelfMember
      local commProfileName = TrimText(activeSession.remoteProfileName) ~= "" and activeSession.remoteProfileName or profileName
      local runtimeNow = GetProfileCheckpointSyncTime()
      PruneAgedSessionRuntimeTracking(runtimeNow)
      local stateKey = BuildRecentStatePacketSendKey(
        "LOCALAP",
        activeSession.id,
        commProfileName,
        selfKey,
        "WHISPER",
        activeSession.host
      )
      local stateSignature = resolvedEnabled and "1" or "0"
      local recentState = GetRecentStatePacketSendInfo(stateKey, runtimeNow)
      local recentSentAt = math.max(0, tonumber(type(recentState) == "table" and recentState.sentAt or 0) or 0)
      if not (
        type(recentState) == "table"
        and recentState.signature == stateSignature
        and (runtimeNow - recentSentAt) < sessionConfig.statePacketSendDedupeSeconds
      ) then
        local sent = SendComm(
          "LOCALAP",
          "WHISPER",
          activeSession.host,
          activeSession.id,
          commProfileName,
          selfKey,
          resolvedEnabled and "1" or "0"
        )
        if sent then
          RememberRecentStatePacketSend(stateKey, stateSignature, runtimeNow)
        end
      end
    end

    local currentSectionChanged = false
    if isHost or isJoined then
      local currentUpdate = INTERNAL_API.LIDCOUNCIL_HandleSessionMemberVisibleStateUpdate(
        activeSession,
        selfKey,
        existingSelfMember,
        updatedSelfMember,
        {
          previousVisibleState = previousVisibleState,
          refreshEditor = false,
        }
      )
      currentSectionChanged = type(currentUpdate) == "table" and currentUpdate.currentSectionChanged == true or false
    end
    if currentSectionChanged then
      sessionUiOps.refreshCurrentAndAutoPassSections()
    else
      sessionUiOps.refreshAutoPassSection()
    end
    return true, resolvedEnabled
  end

  INTERNAL_API.LIDCOUNCIL_HandleStartInvite_Impl = function(fields, sender)
    local payload, payloadError = profileSyncMetaOps.parseInboundStartInvitePayload(fields, sender)
    if type(payload) ~= "table" then
      profileSyncMetaOps.recordInboundPayloadReject("START", sender, fields, payloadError)
      Print(sessionLifecycleOps.buildFlowNoticeText("invite_rejected_payload", {
        host = NormalizeSenderKey(sender),
        reason = payloadError,
      }))
      return
    end
    local runtimeNow = GetProfileCheckpointSyncTime()
    PruneAgedSessionRuntimeTracking(runtimeNow)
    local sessionId = payload.sessionId
    local profileName = payload.profileName
    local profileId = payload.profileId
    local claimedHost = payload.claimedHost
    local host = payload.host
    local startedAt = payload.startedAt
    local profileMaster = payload.profileMaster
    local protocolVersion = payload.protocolVersion
    local rollFieldsStartIndex = payload.rollFieldsStartIndex
    local inviteStatus = payload.inviteStatus
    if profileMaster == "" then
      profileMaster = host
    end
    local rollOptions = deps.ParseRollOptionFields(fields, rollFieldsStartIndex)
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")

    local function SendInviteReceipt(receiptState, reason)
      if selfKey == "" or host == "" then
        return false
      end
      return SendComm("IACK", "WHISPER", host, sessionId, profileName, selfKey, receiptState, reason or "")
    end

    if AreCharacterKeysSame(host, selfKey) then
      return
    end
    if claimedHost ~= "" and not AreCharacterKeysSame(claimedHost, host) then
      SendInviteReceipt("REJECTED", "claimed_host_identity_mismatch")
      Print(sessionLifecycleOps.buildFlowNoticeText("invite_rejected_identity"))
      return
    end
    if not IsCurrentGroupCharacter(host) then
      SendInviteReceipt("REJECTED", "host_not_in_current_group")
      Print(sessionLifecycleOps.buildFlowNoticeText("invite_rejected_group"))
      return
    end

    local activeSession, activeProfileName = GetActiveLootSession()
    if DoesActiveSessionMatch(activeSession, activeProfileName, sessionId, profileName) then
      SendInviteReceipt("RECEIVED", "already_open")
      return
    end
    if activeSession then
      SendInviteReceipt("REJECTED", "different_session_open")
      Print(sessionLifecycleOps.buildFlowNoticeText("invite_ignored_existing_session", {
        host = host,
      }))
      return
    end

    local invite = {
      sessionId = sessionId,
      profileName = profileName,
      profileId = profileId,
      host = host,
      profileMaster = profileMaster,
      startedAt = startedAt,
      rollOptions = rollOptions,
      protocolVersion = protocolVersion,
      status = inviteStatus,
      receivedAt = runtimeNow,
    }
    if type(sessionRuntime.pendingJoinRequests[sessionId]) == "table" then
      sessionRuntime.pendingInvites[sessionId] = invite
      local pendingJoin = sessionRuntime.pendingJoinRequests[sessionId]
      pendingJoin.invite = invite
      pendingJoin.updatedAt = runtimeNow
      if pendingJoin.state == "TIMED_OUT" then
        pendingJoin.attempts = 0
        pendingJoin.queueAttempts = 0
        pendingJoin.state = "PENDING"
        pendingJoin.timedOutAt = 0
        pendingJoin.acceptLateAckUntil = 0
        pendingJoin.timeoutReason = ""
        pendingJoin.hardDeadlineAt = runtimeNow + sessionConfig.joinAckHardTimeoutSeconds
      end
      SendInviteReceipt("RECEIVED", "join_pending")
      sessionLifecycleOps.schedulePendingJoinRetryCheck(
        sessionId,
        sessionConfig.joinAckQueuePollSeconds,
        false
      )
      return
    end
    sessionRuntime.pendingInvites[sessionId] = invite
    local popupShown, popupError = ShowSessionInvite(invite)
    if popupShown then
      SendInviteReceipt("RECEIVED", "popup_shown")
      return
    end

    sessionRuntime.pendingInvites[sessionId] = nil
    local failureReason = TrimText(popupError)
    if failureReason == "" then
      failureReason = "popup_display_failed"
    end
    SendInviteReceipt("REJECTED", failureReason)
    Print("Received the LidCouncil session invite, but WoW could not show its confirmation popup ("
      .. failureReason .. "). Ask the host to send the invite again.")
  end

  INTERNAL_API.LIDCOUNCIL_HandleInviteAck_Impl = function(fields, sender)
    local payload, payloadError = profileSyncMetaOps.parseInboundInviteAckPayload(fields, sender)
    if type(payload) ~= "table" then
      profileSyncMetaOps.recordInboundPayloadReject("IACK", sender, fields, payloadError)
      return
    end

    local activeSession, activeProfileName = GetActiveLootSession()
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if type(activeSession) ~= "table"
      or not DoesActiveSessionMatch(activeSession, activeProfileName, payload.sessionId, payload.profileName)
      or not AreCharacterKeysSame(activeSession.host, selfKey)
      or not AreCharacterKeysSame(payload.memberKey, payload.sender)
      or not IsCurrentGroupCharacter(payload.memberKey)
    then
      return
    end

    sessionRuntime.inviteReceipts[payload.sessionId] = sessionRuntime.inviteReceipts[payload.sessionId] or {}
    sessionRuntime.inviteReceipts[payload.sessionId][payload.memberKey] = {
      state = payload.receiptState,
      reason = payload.reason,
      receivedAt = GetProfileCheckpointSyncTime(),
    }
    sessionLifecycleOps.resolveInviteDelivery(
      payload.sessionId,
      payload.memberKey,
      payload.receiptState,
      payload.reason
    )

    if payload.receiptState == "RECEIVED" then
      Print(sessionLifecycleOps.buildFlowNoticeText("invite_received", {
        memberKey = payload.memberKey,
        reason = payload.reason,
      }))
    else
      Print(sessionLifecycleOps.buildFlowNoticeText("invite_rejected", {
        memberKey = payload.memberKey,
        reason = payload.reason ~= "" and payload.reason or string.lower(payload.receiptState),
      }))
    end
  end

  INTERNAL_API.LIDCOUNCIL_HandleJoinAck_Impl = function(fields, sender)
    local payload, payloadError = profileSyncMetaOps.parseInboundJoinAckPayload(fields, sender)
    if type(payload) ~= "table" then
      profileSyncMetaOps.recordInboundPayloadReject("JACK", sender, fields, payloadError)
      return
    end
    PruneAgedSessionRuntimeTracking(GetProfileCheckpointSyncTime())
    local sessionId = payload.sessionId
    local profileName = payload.profileName
    local profileId = payload.profileId
    local claimedHost = payload.claimedHost
    local host = payload.host
    local profileMaster = payload.profileMaster
    local startedAt = payload.startedAt
    local ackStatus = payload.ackStatus
    local activatedAt = payload.activatedAt
    local protocolVersion = payload.protocolVersion
    local ackMemberKey = payload.ackMemberKey
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if selfKey == "" then
      return
    end
    if claimedHost ~= "" and not AreCharacterKeysSame(claimedHost, host) then
      return
    end
    if ackMemberKey ~= "" and not AreCharacterKeysSame(ackMemberKey, selfKey) then
      return
    end
    if protocolVersion ~= COMM_PROTOCOL_VERSION then
      Print(sessionLifecycleOps.buildFlowNoticeText("join_confirm_incompatible_build", {
        profileName = profileName,
      }))
      return
    end
    if profileMaster == "" then
      profileMaster = host
    end

    local pendingJoin = sessionRuntime.pendingJoinRequests[sessionId]
    local invite = type(pendingJoin) == "table" and type(pendingJoin.invite) == "table" and pendingJoin.invite or sessionRuntime.pendingInvites[sessionId]
    if type(invite) ~= "table" then
      return
    end
    if not AreCharacterKeysSame(invite.host, host) or TrimText(invite.profileName) ~= profileName then
      return
    end

    if type(pendingJoin) == "table" then
      pendingJoin.confirmed = true
      INTERNAL_API.LIDCOUNCIL_InvalidateJoinAckRetryTimer_Impl(pendingJoin)
    end
    sessionRuntime.pendingJoinRequests[sessionId] = nil
    sessionRuntime.pendingInvites[sessionId] = nil
    SetLocalAutoPassEnabled(true)

    local localProfileName = deps.ResolveLocalSharedProfileName(profileName, profileId, profileMaster)
    local existingSharedProfileName = TrimText(profileId ~= "" and deps.FindLootProfileNameById(profileId) or "")
    local sharedProfileReady = existingSharedProfileName ~= "" or TrimText(profileId) == ""
    local localProfile = type(deps.GetLootProfile) == "function" and select(1, deps.GetLootProfile(localProfileName)) or nil
    local joinedRollOptions = ResolveJoinedSessionRollOptions(
      type(localProfile) == "table" and type(localProfile.settings) == "table" and localProfile.settings.rollOptions or nil,
      invite.rollOptions,
      sharedProfileReady,
      deps.NormalizeLootRollOptions
    )
    if ackStatus ~= "ACTIVE" then
      ackStatus = "PREPARING"
    end
    local session, joinedProfileName = JoinLootSession(localProfileName, {
      id = sessionId,
      profileName = localProfileName,
      remoteProfileName = profileName,
      profileId = profileId,
      host = host,
      profileMaster = profileMaster,
      status = ackStatus,
      startedAt = startedAt,
      activatedAt = activatedAt,
      rollOptions = joinedRollOptions,
      sharedProfileReady = sharedProfileReady,
    }, "JACK")
    if not session then
      Print(sessionLifecycleOps.buildFlowNoticeText("join_confirm_failed", {
        error = joinedProfileName,
      }))
      return
    end
    if payload.hostAutoPassEnabled ~= nil then
      UpsertLootSessionMember(joinedProfileName, sessionId, host, {
        status = "JOINED",
        joinedAt = startedAt,
        profileMaster = profileMaster,
        localAutoPassEnabled = payload.hostAutoPassEnabled,
        suppressProfileTouch = true,
      })
    end
    optionalApiOps.beginProfileSnapshotDiagnosticsForSession(sessionId, startedAt)
    if type(deps.RememberSharedReplicaPlaceholder) == "function" then
      deps.RememberSharedReplicaPlaceholder(joinedProfileName, profileName, profileId, profileMaster)
    end

    local payloadDetails = type(pendingJoin) == "table" and type(pendingJoin.payloadDetails) == "table" and pendingJoin.payloadDetails or deps.GetMemberPayloadDetails(nil, true)
    deps.SyncLootProfilePermissionState(joinedProfileName, profileMaster, selfKey, "RAIDER")
    UpsertLootSessionMember(joinedProfileName, sessionId, selfKey, {
      status = "JOINED",
      joinedAt = type(pendingJoin) == "table" and pendingJoin.joinedAt or (time and time() or 0),
      profileMaster = profileMaster,
      role = "RAIDER",
      addonVersion = payloadDetails.addonVersion,
      clientVersion = payloadDetails.clientVersion,
      className = payloadDetails.className,
      classFile = payloadDetails.classFile,
      specName = payloadDetails.specName,
      specIcon = payloadDetails.specIcon,
      localAutoPassEnabled = payloadDetails.localAutoPassEnabled,
      suppressProfileTouch = true,
    })
    deps.AddCharacterToList(selfKey)
    if session.sharedProfileReady ~= false and type(profileSyncMetaOps.sendLocalProfileStateToHost) == "function" then
      profileSyncMetaOps.sendLocalProfileStateToHost(sessionId, profileName, joinedProfileName)
      if type(profileSyncMetaOps.scheduleDelayedLocalProfileStateSend) == "function" then
        profileSyncMetaOps.scheduleDelayedLocalProfileStateSend(sessionId, profileName, joinedProfileName, {
          force = true,
        })
      end
    end

    if session.sharedProfileReady == false then
      session.__sharedProfilePendingNoticeShown = nil
      Print(sessionLifecycleOps.buildMemberNoticeText("join_confirmed_bootstrap_pending", {
        profileName = profileName,
      }))
    else
      Print(sessionLifecycleOps.buildMemberNoticeText("join_confirmed_ready", {
        profileName = profileName,
      }))
    end
    sessionUiOps.refreshPanelsAndLiveBoard()
  end

  INTERNAL_API.LIDCOUNCIL_HandleBegin_Impl = function(fields, sender)
    local payload, payloadError = profileSyncMetaOps.parseInboundBeginPayload(fields, sender)
    if type(payload) ~= "table" then
      profileSyncMetaOps.recordInboundPayloadReject("BEGIN", sender, fields, payloadError)
      return
    end
    PruneAgedSessionRuntimeTracking(GetProfileCheckpointSyncTime())
    local sessionId = payload.sessionId
    local profileName = payload.profileName
    local profileId = payload.profileId
    local claimedHost = payload.claimedHost
    local host = payload.host
    local activatedAt = payload.activatedAt
    local profileMaster = payload.profileMaster
    local protocolVersion = payload.protocolVersion
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if AreCharacterKeysSame(host, selfKey) then
      return
    end
    if claimedHost ~= "" and not AreCharacterKeysSame(claimedHost, host) then
      return
    end
    if not IsCurrentGroupCharacter(host) then
      return
    end
    if protocolVersion ~= COMM_PROTOCOL_VERSION then
      return
    end
    if profileMaster == "" then
      profileMaster = host
    end

    local activeSession, activeProfileName = GetActiveLootSession()
    if not DoesActiveSessionMatch(activeSession, activeProfileName, sessionId, profileName) then
      return
    end
    if not deps.IsActiveSessionHostSender(activeSession, sender) then
      return
    end

    if IsLiveSession(activeSession) then
      return
    end

    local localProfileName = TrimText(activeProfileName)
    if localProfileName == "" then
      localProfileName = deps.ResolveLocalSharedProfileName(profileName, profileId, profileMaster)
    end

    local session, err = JoinLootSession(localProfileName, {
      id = sessionId,
      profileName = localProfileName,
      remoteProfileName = profileName,
      profileId = profileId,
      host = host,
      profileMaster = profileMaster,
      status = "ACTIVE",
      startedAt = activeSession.startedAt,
      activatedAt = activatedAt,
      rollOptions = activeSession.rollOptions,
      sharedProfileReady = activeSession.sharedProfileReady ~= false,
    }, "BEGIN")
    if not session then
      Print(sessionLifecycleOps.buildFlowNoticeText("start_incoming_failed", {
        error = err,
      }))
      return
    end
    optionalApiOps.beginProfileSnapshotDiagnosticsForSession(sessionId, activatedAt)
    if session.sharedProfileReady ~= false and type(profileSyncMetaOps.sendLocalProfileStateToHost) == "function" then
      profileSyncMetaOps.sendLocalProfileStateToHost(sessionId, profileName, localProfileName)
      if type(profileSyncMetaOps.scheduleDelayedLocalProfileStateSend) == "function" then
        profileSyncMetaOps.scheduleDelayedLocalProfileStateSend(sessionId, profileName, localProfileName, {
          force = true,
        })
      end
    end

    sessionLifecycleOps.emitTransitionStateNotice(sessionId, localProfileName, "remote_started", {
      profileName = profileName,
      host = host,
      sender = host,
      refreshEditor = false,
    })
    sessionUiOps.refreshPanelsAndLiveBoard()
  end

  function sessionLifecycleOps.runAcceptedJoinFollowup(phase, sessionId, profileName, memberKey, callback, opts)
    opts = type(opts) == "table" and opts or {}
    if type(callback) ~= "function" then
      return false, "missing_join_followup"
    end

    local ok, result = pcall(callback)
    if ok then
      return true, result
    end

    local detail = TrimText(result)
    if detail == "" then
      detail = "unknown accepted JOIN follow-up error"
    end
    if opts.suppressDiagnostics ~= true then
      local logError = rawget(_G, "LIDCOUNCIL_LogError")
      if type(logError) == "function" then
        pcall(logError, "Accepted JOIN follow-up failed for " .. TrimText(memberKey)
          .. " (" .. FirstNonEmptyText(phase, "unknown") .. "): " .. detail)
      end
      if type(RecordProfileSyncDecision) == "function" then
        pcall(RecordProfileSyncDecision, "accepted_join_followup", {
          action = "failed",
          sessionId = sessionId,
          profileName = profileName,
          target = memberKey,
          reason = FirstNonEmptyText(phase, "unknown"),
          error = detail,
        })
      end
      pcall(
        sessionLifecycleOps.emitSyncRuntimeState,
        sessionId,
        profileName,
        "accepted_join_followup_failed",
        "warn",
        "The member was accepted, but optional " .. FirstNonEmptyText(phase, "JOIN")
          .. " recovery failed: " .. detail,
        {
          sender = memberKey,
          refreshSyncManagement = true,
          printNotice = false,
          skipIfSame = true,
        }
      )
    end
    return false, detail
  end
  INTERNAL_API.LIDCOUNCIL_RunAcceptedJoinFollowup_Impl = sessionLifecycleOps.runAcceptedJoinFollowup

  function sessionLifecycleOps.getAcceptedJoinBurstStatus()
    local stats = type(sessionRuntime.acceptedJoinBurstStats) == "table"
      and sessionRuntime.acceptedJoinBurstStats
      or {}
    local runtimeNow = GetProfileCheckpointSyncTime()
    return {
      sessionId = TrimText(sessionRuntime.acceptedJoinBurstSessionId),
      profileName = TrimText(sessionRuntime.acceptedJoinBurstProfileName),
      pending = #sessionRuntime.acceptedJoinFollowupQueue,
      timerArmed = sessionRuntime.acceptedJoinFollowupTimerArmed == true,
      quietRemaining = math.max(0,
        math.max(0, tonumber(sessionRuntime.acceptedJoinFollowupNotBeforeAt) or 0) - runtimeNow),
      acceptedTotal = math.max(0, tonumber(stats.acceptedTotal) or 0),
      coalescedTotal = math.max(0, tonumber(stats.coalescedTotal) or 0),
      processedTotal = math.max(0, tonumber(stats.processedTotal) or 0),
      failedTotal = math.max(0, tonumber(stats.failedTotal) or 0),
      commitTotal = math.max(0, tonumber(stats.commitTotal) or 0),
      committedMemberTotal = math.max(0, tonumber(stats.committedMemberTotal) or 0),
      uiRefreshRequestedTotal = math.max(0, tonumber(stats.uiRefreshRequestedTotal) or 0),
      lastQueuedAt = math.max(0, tonumber(stats.lastQueuedAt) or 0),
      lastProcessedAt = math.max(0, tonumber(stats.lastProcessedAt) or 0),
      lastDurationMs = math.max(0, tonumber(stats.lastDurationMs) or 0),
      maxDurationMs = math.max(0, tonumber(stats.maxDurationMs) or 0),
    }
  end

  function sessionLifecycleOps.clearAcceptedJoinFollowups()
    sessionRuntime.acceptedJoinFollowupQueue = {}
    sessionRuntime.acceptedJoinFollowupByKey = {}
    sessionRuntime.acceptedJoinBurstMembers = {}
    sessionRuntime.acceptedJoinBurstNeedsCommit = false
    sessionRuntime.acceptedJoinBurstSessionId = ""
    sessionRuntime.acceptedJoinBurstProfileName = ""
    sessionRuntime.acceptedJoinFollowupNotBeforeAt = 0
    sessionRuntime.acceptedJoinFollowupTimerToken =
      math.max(0, tonumber(sessionRuntime.acceptedJoinFollowupTimerToken) or 0) + 1
    sessionRuntime.acceptedJoinFollowupTimerArmed = false
  end

  function sessionLifecycleOps.commitAcceptedJoinBurst()
    if sessionRuntime.acceptedJoinBurstNeedsCommit ~= true then
      return true, 0
    end
    local sessionId = TrimText(sessionRuntime.acceptedJoinBurstSessionId)
    local profileName = TrimText(sessionRuntime.acceptedJoinBurstProfileName)
    local memberKeys = {}
    for _, memberKey in pairs(type(sessionRuntime.acceptedJoinBurstMembers) == "table"
      and sessionRuntime.acceptedJoinBurstMembers or {})
    do
      local resolvedMemberKey = NormalizeCharacterKey(memberKey)
      if resolvedMemberKey ~= "" then
        memberKeys[#memberKeys + 1] = resolvedMemberKey
      end
    end
    table.sort(memberKeys, function(left, right)
      return string.lower(left) < string.lower(right)
    end)
    sessionRuntime.acceptedJoinBurstMembers = {}
    sessionRuntime.acceptedJoinBurstNeedsCommit = false

    local activeSession, activeProfileName = GetActiveLootSession()
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if type(activeSession) ~= "table"
      or not DoesActiveSessionMatch(activeSession, activeProfileName, sessionId, profileName)
      or not AreCharacterKeysSame(activeSession.host or "", selfKey)
    then
      return false, "join_burst_session_changed"
    end

    local committed = 0
    local permissionsChanged = false
    for _, memberKey in ipairs(memberKeys) do
      deps.AddCharacterToList(memberKey)
      local roleOk, assignedRole, roleChanged = deps.EnsureLootProfileMemberRole(
        profileName,
        memberKey,
        "RAIDER",
        {
          suppressProfileTouch = true,
        }
      )
      if roleOk then
        UpsertLootSessionMember(profileName, sessionId, memberKey, {
          role = assignedRole or "RAIDER",
          suppressProfileTouch = true,
        })
        permissionsChanged = permissionsChanged or roleChanged == true
      end
      committed = committed + 1
    end
    if committed > 0 and type(deps.TouchLootProfileDomain) == "function" then
      local profile = select(1, deps.GetLootProfile(profileName))
      if type(profile) == "table" then
        deps.TouchLootProfileDomain(profile, "session")
        if permissionsChanged then
          deps.TouchLootProfileDomain(profile, "permissions")
        end
      end
    end
    local stats = sessionRuntime.acceptedJoinBurstStats
    stats.commitTotal = math.max(0, tonumber(stats.commitTotal) or 0) + 1
    stats.committedMemberTotal = math.max(0, tonumber(stats.committedMemberTotal) or 0) + committed
    return true, committed
  end

  function sessionLifecycleOps.scheduleAcceptedJoinFollowupDrain(delaySeconds)
    if sessionRuntime.acceptedJoinFollowupTimerArmed == true then
      return true
    end
    if type(Compat) ~= "table" or type(Compat.After) ~= "function" then
      return false, "timer_unavailable"
    end
    sessionRuntime.acceptedJoinFollowupTimerToken =
      math.max(0, tonumber(sessionRuntime.acceptedJoinFollowupTimerToken) or 0) + 1
    local token = sessionRuntime.acceptedJoinFollowupTimerToken
    sessionRuntime.acceptedJoinFollowupTimerArmed = true
    local scheduled, scheduleReason = Compat.After(math.max(0, tonumber(delaySeconds) or 0), function()
      if sessionRuntime.acceptedJoinFollowupTimerArmed ~= true
        or tonumber(sessionRuntime.acceptedJoinFollowupTimerToken) ~= tonumber(token)
      then
        return
      end
      sessionRuntime.acceptedJoinFollowupTimerArmed = false
      sessionLifecycleOps.drainAcceptedJoinFollowups()
    end)
    if scheduled == false then
      sessionRuntime.acceptedJoinFollowupTimerArmed = false
      return false, scheduleReason
    end
    return true
  end

  function sessionLifecycleOps.drainAcceptedJoinFollowups()
    local runtimeNow = GetProfileCheckpointSyncTime()
    local quietRemaining = math.max(0,
      math.max(0, tonumber(sessionRuntime.acceptedJoinFollowupNotBeforeAt) or 0) - runtimeNow)
    if quietRemaining > 0 then
      return sessionLifecycleOps.scheduleAcceptedJoinFollowupDrain(quietRemaining)
    end
    if #sessionRuntime.acceptedJoinFollowupQueue <= 0 then
      sessionUiOps.queueAcceptedJoinBurstRefresh()
      return true
    end

    local commitTraceToken = BeginRaidTestTracePhase("ACCEPTED_JOIN_BURST_COMMIT", "", {
      pending = #sessionRuntime.acceptedJoinFollowupQueue,
      session = TrimText(sessionRuntime.acceptedJoinBurstSessionId),
    })
    local committed, commitError = sessionLifecycleOps.commitAcceptedJoinBurst()
    EndRaidTestTracePhase(commitTraceToken, committed == true and "committed" or "failed", {
      success = committed == true,
      members = committed == true and math.max(0, tonumber(commitError) or 0) or 0,
      error = committed == true and "" or TrimText(commitError),
    })
    if committed ~= true then
      sessionLifecycleOps.clearAcceptedJoinFollowups()
      return false, commitError
    end

    local selectedIndex = 1
    for index = 2, #sessionRuntime.acceptedJoinFollowupQueue do
      local selected = sessionRuntime.acceptedJoinFollowupQueue[selectedIndex]
      local candidate = sessionRuntime.acceptedJoinFollowupQueue[index]
      if math.max(1, tonumber(type(candidate) == "table" and candidate.priority or 2) or 2)
        < math.max(1, tonumber(type(selected) == "table" and selected.priority or 2) or 2)
      then
        selectedIndex = index
      end
    end
    local item = table.remove(sessionRuntime.acceptedJoinFollowupQueue, selectedIndex)
    if type(item) ~= "table" then
      return sessionLifecycleOps.scheduleAcceptedJoinFollowupDrain(
        sessionConfig.acceptedJoinFollowupStepSeconds
      )
    end
    sessionRuntime.acceptedJoinFollowupByKey[item.key] = nil

    local followupTraceToken = BeginRaidTestTracePhase("ACCEPTED_JOIN_FOLLOWUP", item.phase, {
      member = item.memberKey,
      pending = #sessionRuntime.acceptedJoinFollowupQueue,
      priority = item.priority,
    })
    local profiler = rawget(_G, "debugprofilestop")
    local startedAt = type(profiler) == "function" and profiler() or 0
    local ok, detail = sessionLifecycleOps.runAcceptedJoinFollowup(
      item.phase,
      item.sessionId,
      item.profileName,
      item.memberKey,
      item.callback
    )
    local durationMs = type(profiler) == "function" and math.max(0, profiler() - startedAt) or 0
    EndRaidTestTracePhase(followupTraceToken, item.phase, {
      member = item.memberKey,
      success = ok == true,
      pending = #sessionRuntime.acceptedJoinFollowupQueue,
    })
    local stats = sessionRuntime.acceptedJoinBurstStats
    stats.processedTotal = math.max(0, tonumber(stats.processedTotal) or 0) + 1
    stats.lastProcessedAt = GetProfileCheckpointSyncTime()
    stats.lastDurationMs = durationMs
    stats.maxDurationMs = math.max(math.max(0, tonumber(stats.maxDurationMs) or 0), durationMs)
    if not ok then
      stats.failedTotal = math.max(0, tonumber(stats.failedTotal) or 0) + 1
    elseif durationMs >= sessionConfig.acceptedJoinFollowupSlowMilliseconds
      and type(RecordProfileSyncDecision) == "function"
    then
      RecordProfileSyncDecision("accepted_join_followup", {
        action = "slow",
        sessionId = item.sessionId,
        profileName = item.profileName,
        target = item.memberKey,
        reason = item.phase,
        durationMs = durationMs,
      })
    end

    if #sessionRuntime.acceptedJoinFollowupQueue > 0 then
      return sessionLifecycleOps.scheduleAcceptedJoinFollowupDrain(
        sessionConfig.acceptedJoinFollowupStepSeconds
      )
    end
    sessionUiOps.queueAcceptedJoinBurstRefresh()
    return true, detail
  end

  function sessionLifecycleOps.queueAcceptedJoinFollowup(sessionId, profileName, memberKey, phase, callback, opts)
    opts = type(opts) == "table" and opts or {}
    local resolvedSessionId = TrimText(sessionId)
    local resolvedProfileName = TrimText(profileName)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if resolvedSessionId == "" or resolvedProfileName == "" or resolvedMemberKey == ""
      or type(callback) ~= "function"
    then
      return false, "invalid_join_followup"
    end
    if TrimText(sessionRuntime.acceptedJoinBurstSessionId) ~= ""
      and TrimText(sessionRuntime.acceptedJoinBurstSessionId) ~= resolvedSessionId
    then
      sessionLifecycleOps.clearAcceptedJoinFollowups()
    end
    sessionRuntime.acceptedJoinBurstSessionId = resolvedSessionId
    sessionRuntime.acceptedJoinBurstProfileName = resolvedProfileName
    local key = string.lower(resolvedSessionId) .. "|" .. string.lower(resolvedMemberKey)
    local existing = sessionRuntime.acceptedJoinFollowupByKey[key]
    local runtimeNow = GetProfileCheckpointSyncTime()
    sessionRuntime.acceptedJoinFollowupNotBeforeAt = math.max(
      math.max(0, tonumber(sessionRuntime.acceptedJoinFollowupNotBeforeAt) or 0),
      runtimeNow + sessionConfig.acceptedJoinBurstQuietSeconds
    )
    local stats = sessionRuntime.acceptedJoinBurstStats
    stats.lastQueuedAt = runtimeNow
    if type(existing) == "table" then
      stats.coalescedTotal = math.max(0, tonumber(stats.coalescedTotal) or 0) + 1
      if opts.ensureRole == true then
        sessionRuntime.acceptedJoinBurstMembers[string.lower(resolvedMemberKey)] = resolvedMemberKey
        sessionRuntime.acceptedJoinBurstNeedsCommit = true
      end
      sessionUiOps.queueAcceptedJoinBurstRefresh()
      sessionLifecycleOps.scheduleAcceptedJoinFollowupDrain(
        sessionConfig.acceptedJoinBurstQuietSeconds
      )
      RecordRaidTestTraceEvent("JOIN_FOLLOWUP_COALESCED", FirstNonEmptyText(phase, "accepted JOIN follow-up"), {
        member = resolvedMemberKey,
        pending = #sessionRuntime.acceptedJoinFollowupQueue,
        quiet = sessionConfig.acceptedJoinBurstQuietSeconds,
      })
      return true, "coalesced"
    end
    local item = {
      key = key,
      sessionId = resolvedSessionId,
      profileName = resolvedProfileName,
      memberKey = resolvedMemberKey,
      phase = FirstNonEmptyText(phase, "accepted JOIN follow-up"),
      priority = math.max(1, tonumber(opts.priority) or 1),
      callback = callback,
      queuedAt = runtimeNow,
    }
    sessionRuntime.acceptedJoinFollowupByKey[key] = item
    sessionRuntime.acceptedJoinFollowupQueue[#sessionRuntime.acceptedJoinFollowupQueue + 1] = item
    if opts.ensureRole == true then
      sessionRuntime.acceptedJoinBurstMembers[string.lower(resolvedMemberKey)] = resolvedMemberKey
      sessionRuntime.acceptedJoinBurstNeedsCommit = true
    end
    stats.acceptedTotal = math.max(0, tonumber(stats.acceptedTotal) or 0) + 1
    RecordRaidTestTraceEvent("JOIN_FOLLOWUP_QUEUED", item.phase, {
      member = resolvedMemberKey,
      pending = #sessionRuntime.acceptedJoinFollowupQueue,
      priority = item.priority,
      quiet = sessionConfig.acceptedJoinBurstQuietSeconds,
    })
    sessionUiOps.queueAcceptedJoinBurstRefresh()
    local scheduled, scheduleError = sessionLifecycleOps.scheduleAcceptedJoinFollowupDrain(
      sessionConfig.acceptedJoinBurstQuietSeconds
    )
    if scheduled ~= true then
      return false, scheduleError
    end
    return true, "queued"
  end
  INTERNAL_API.LIDCOUNCIL_GetAcceptedJoinBurstStatus_Impl = sessionLifecycleOps.getAcceptedJoinBurstStatus
  INTERNAL_API.LIDCOUNCIL_QueueAcceptedJoinFollowup_Impl = sessionLifecycleOps.queueAcceptedJoinFollowup

  INTERNAL_API.LIDCOUNCIL_HandleJoin_Impl = function(fields, sender)
    local payload, payloadError = profileSyncMetaOps.parseInboundJoinPayload(fields, sender)
    if type(payload) ~= "table" then
      profileSyncMetaOps.recordInboundPayloadReject("JOIN", sender, fields, payloadError)
      return
    end
    local runtimeNow = GetProfileCheckpointSyncTime()
    PruneAgedSessionRuntimeTracking(runtimeNow)
    local sessionId = payload.sessionId
    local profileName = payload.profileName
    local memberKey = payload.memberKey
    local joinedAt = payload.joinedAt
    local addonVersion = payload.addonVersion
    local clientVersion = payload.clientVersion
    local className = payload.className
    local classFile = payload.classFile
    local specName = payload.specName
    local specIcon = payload.specIcon
    local localAutoPassEnabled = payload.localAutoPassEnabled
    local claimedProfileId = payload.claimedProfileId
    local remoteSettingsRevision = payload.remoteSettingsRevision
    local remotePermissionsRevision = payload.remotePermissionsRevision
    local remoteOperationalRevision = payload.remoteOperationalRevision
    local remoteProfileUpdatedAt = payload.remoteProfileUpdatedAt
    local hadLocalSharedProfile = payload.hadLocalSharedProfile
    local memberProtocolVersion = payload.memberProtocolVersion
    local remoteSettingsChecksum = payload.remoteSettingsChecksum
    local remotePermissionsChecksum = payload.remotePermissionsChecksum
    local remoteOperationalChecksum = payload.remoteOperationalChecksum
    local remoteLootRevision = payload.remoteLootRevision
    local remoteSessionRevision = payload.remoteSessionRevision
    local remoteLootChecksum = payload.remoteLootChecksum
    local remoteSessionChecksum = payload.remoteSessionChecksum
    local remoteLiveLootChecksum = payload.remoteLiveLootChecksum
    if sessionId == "" or profileName == "" or memberKey == "" then
      return
    end

    local activeSession, activeProfileName = GetActiveLootSession()
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if not DoesActiveSessionMatch(activeSession, activeProfileName, sessionId, profileName) then
      Print(sessionLifecycleOps.buildSyncNoticeText("join_ignored_session_mismatch", {
        memberKey = memberKey,
      }))
      return
    end
    if not AreCharacterKeysSame(activeSession.host or "", selfKey) then
      return
    end
    if not IsClaimedActorSenderMatch(sender, memberKey) then
      Print(sessionLifecycleOps.buildSyncNoticeText("join_ignored_sender_mismatch", {
        memberKey = memberKey,
        sender = sender,
      }))
      return
    end
    if not IsCurrentGroupCharacter(memberKey) then
      Print(sessionLifecycleOps.buildSyncNoticeText("join_ignored_not_in_group", {
        memberKey = memberKey,
      }))
      return
    end
    if AreCharacterKeysSame(memberKey, selfKey) then
      return
    end
    if memberProtocolVersion ~= COMM_PROTOCOL_VERSION then
      Print(sessionLifecycleOps.buildSyncNoticeText("join_incompatible_build_active_session", {
        profileName = profileName,
        memberKey = memberKey,
      }))
      SendComm("STOP", "WHISPER", memberKey, sessionId, profileName, activeSession.host, time and time() or 0)
      return
    end
    ExtendProfileSnapshotJoinGrace(sessionId, profileName, sessionConfig.joinQuietGraceSeconds, "join:" .. tostring(memberKey))
    if TrimText(sessionRuntime.existingReplicaJoinSessionId) ~= sessionId then
      sessionRuntime.existingReplicaJoinSessionId = sessionId
      sessionRuntime.existingReplicaJoinByMember = {}
    end
    sessionRuntime.existingReplicaJoinByMember = type(sessionRuntime.existingReplicaJoinByMember) == "table"
      and sessionRuntime.existingReplicaJoinByMember
      or {}
    sessionRuntime.existingReplicaJoinByMember[string.lower(memberKey)] = hadLocalSharedProfile == true
    if IsJoinedSessionCharacter(activeSession, memberKey) then
      local previousVisibleState = BuildSessionVisibleMemberStateSignature(FindSessionMember(activeSession, memberKey))
      UpsertLootSessionMember(profileName, sessionId, memberKey, {
        status = "JOINED",
        joinedAt = joinedAt,
        addonVersion = addonVersion,
        clientVersion = clientVersion,
        className = className,
        classFile = classFile,
        specName = specName,
        specIcon = specIcon,
        localAutoPassEnabled = localAutoPassEnabled,
        sharedProfileId = claimedProfileId,
        settingsRevision = remoteSettingsRevision,
        permissionsRevision = remotePermissionsRevision,
        operationalRevision = remoteOperationalRevision,
        lootRevision = remoteLootRevision,
        sessionRevision = remoteSessionRevision,
        settingsChecksum = remoteSettingsChecksum,
        permissionsChecksum = remotePermissionsChecksum,
        operationalChecksum = remoteOperationalChecksum,
        lootChecksum = remoteLootChecksum,
        sessionChecksum = remoteSessionChecksum,
        liveLootChecksum = remoteLiveLootChecksum,
        profileUpdatedAt = remoteProfileUpdatedAt,
        suppressProfileTouch = true,
      })
      local existingMember = FindSessionMember(activeSession, memberKey)
      SendJoinAck(activeSession, profileName, memberKey)
      local updatedVisibleState = BuildSessionVisibleMemberStateSignature(existingMember)
      if previousVisibleState ~= updatedVisibleState then
        BroadcastMember(profileName, sessionId, memberKey, existingMember or {
          name = memberKey,
          status = "JOINED",
          joinedAt = joinedAt,
        })
      end
      -- A repeated JOIN can repair a stale host roster, but comparison and
      -- snapshot work must not execute inside the inbound message handler.
      -- Coalesce retry storms per member and pace the recovery after the join
      -- wave has gone quiet.
      sessionLifecycleOps.queueAcceptedJoinFollowup(
        sessionId,
        profileName,
        memberKey,
        "returning-member recovery",
        function()
      local resentMemberRowCount = 0
      if type(profileSyncMetaOps.sendJoinTargetedMemberBurst) == "function" then
        -- Capture the first return before converting it. select(1, ...) returns
        -- every value, so passing it directly to tonumber also forwarded the
        -- burst detail table as tonumber's optional numeric base argument.
        local resentMemberRows = profileSyncMetaOps.sendJoinTargetedMemberBurst(
          activeSession,
          profileName,
          sessionId,
          memberKey,
          {
            suppressCheckpoint = true,
          }
        )
        resentMemberRowCount = math.max(0, tonumber(resentMemberRows) or 0)
      end
      -- MEMBER state can be rejected as older metadata by a reconnecting
      -- client. Send the host's preference separately so its displayed
      -- Auto-Pass state cannot remain at the joiner's default ON value.
      local hostAutoPassEnabled = type(deps.GetLocalAutoPassEnabled) == "function"
        and (deps.GetLocalAutoPassEnabled() and true or false)
        or (type(activeSession.members) == "table" and activeSession.members[selfKey]
          and activeSession.members[selfKey].localAutoPassEnabled == true)
      local hostAutoPassNoticeSent = BroadcastAutoPassNotice(
        sessionId,
        profileName,
        selfKey,
        hostAutoPassEnabled,
        "WHISPER",
        memberKey
      )
      local hostAutoPassStateText = "Host Auto-Pass "
        .. (hostAutoPassEnabled and "ON" or "OFF")
        .. (hostAutoPassNoticeSent and " was queued for " or " could not be queued for ")
        .. memberKey .. "."
      if type(RecordProfileSyncDecision) == "function" then
        RecordProfileSyncDecision("send_targeted_host_autopass", {
          action = hostAutoPassNoticeSent and "queued" or "failed",
          sessionId = sessionId,
          profileName = profileName,
          target = memberKey,
          enabled = hostAutoPassEnabled == true,
          reason = "duplicate_join_roster_refresh",
        })
      end
      sessionLifecycleOps.emitSyncRuntimeState(
        sessionId,
        profileName,
        "host_autopass_targeted_queued",
        hostAutoPassNoticeSent and "info" or "warn",
        hostAutoPassStateText,
        {
          sender = memberKey,
          skipIfSame = true,
          refreshSyncManagement = true,
          printNotice = false,
          coalesceWindowSeconds = 1.5,
          coalesceKey = "host_autopass_notice|" .. string.lower(TrimText(memberKey)),
          coalesceSignature = (hostAutoPassEnabled and "1" or "0") .. "|" .. (hostAutoPassNoticeSent and "queued" or "failed"),
        }
      )
      if type(profileSyncMetaOps.queueMemberBackgroundSyncBurst) == "function" then
        profileSyncMetaOps.queueMemberBackgroundSyncBurst(activeSession, profileName, sessionId, memberKey, {
          queuePrewarm = true,
          prewarmReason = "duplicate_join_prewarm",
        })
      else
        PrewarmMemberPreciseLiveSyncState(activeSession, profileName, sessionId, memberKey, {
          mode = "BACKGROUND",
          reason = "duplicate_join_prewarm",
          force = false,
        })
      end
      local syncCandidateSnapshot = BuildActiveSyncCandidateSnapshot()
      local duplicateJoinRepairDisplayBaseContext = INTERNAL_API.LIDCOUNCIL_BuildHostCurrentSessionDisplayContext(
        activeSession,
        profileName,
        nil,
        {
          syncCandidateSnapshot = syncCandidateSnapshot,
        }
      )
      local queuedRepair, queuedRepairCount, repairError, repairDetail = profileSyncMetaOps.queueAutomaticHostRepairForMember(
        activeSession,
        profileName,
        sessionId,
        memberKey,
        {
          mode = "LIVE",
          reason = "duplicate_join_recovery",
          refreshEditor = true,
          suppressUnchanged = true,
          syncCandidateSnapshot = syncCandidateSnapshot,
          currentSessionDisplayBaseContext = duplicateJoinRepairDisplayBaseContext,
          liveTargetSignature = BuildLiveSyncTargetSignature(activeSession, selfKey, nil),
        }
      )
      if queuedRepair and math.max(0, tonumber(queuedRepairCount) or 0) > 0 then
        local repairModeLabel = type(repairDetail) == "table" and TrimText(repairDetail.repairMode) or ""
        Print(sessionLifecycleOps.buildSyncNoticeText("duplicate_join_recovered_queued", {
          memberKey = memberKey,
          resentMemberRowCount = resentMemberRowCount,
          queuedFullFallback = type(repairDetail) == "table"
            and (repairDetail.forceFullSnapshot == true
              or repairDetail.fullSnapshotFallback == true
              or repairModeLabel == "full"),
          scopeEscalated = type(repairDetail) == "table"
            and repairDetail.scopeEscalated == true
            and repairDetail.fullSnapshotFallback ~= true,
          scopeEscalationKinds = type(repairDetail) == "table"
            and CloneDecisionTextList(repairDetail.scopeEscalationKinds)
            or nil,
        }))
      elseif queuedRepair and type(repairDetail) == "table" and repairDetail.deferredPatchState == true then
        Print(sessionLifecycleOps.buildSyncNoticeText("duplicate_join_recovered_deferred", {
          memberKey = memberKey,
          resentMemberRowCount = resentMemberRowCount,
        }))
      elseif queuedRepair then
        Print(sessionLifecycleOps.buildSyncNoticeText("duplicate_join_recovered_noop", {
          memberKey = memberKey,
          resentMemberRowCount = resentMemberRowCount,
        }))
      else
        Print(sessionLifecycleOps.buildSyncNoticeText("duplicate_join_recovered_failed", {
          memberKey = memberKey,
          resentMemberRowCount = resentMemberRowCount,
          error = repairError,
        }))
      end
        end,
        {
          priority = 2,
          ensureRole = true,
        }
      )
      return
    end
    local assignedRole = FirstNonEmptyText(deps.GetLootProfileRole(profileName, memberKey), "RAIDER")
    UpsertLootSessionMember(profileName, sessionId, memberKey, {
      status = "JOINED",
      joinedAt = joinedAt,
      addonVersion = addonVersion,
      clientVersion = clientVersion,
      className = className,
      classFile = classFile,
      specName = specName,
      specIcon = specIcon,
      localAutoPassEnabled = localAutoPassEnabled,
      sharedProfileId = claimedProfileId,
      settingsRevision = remoteSettingsRevision,
      permissionsRevision = remotePermissionsRevision,
      operationalRevision = remoteOperationalRevision,
      lootRevision = remoteLootRevision,
      sessionRevision = remoteSessionRevision,
      settingsChecksum = remoteSettingsChecksum,
      permissionsChecksum = remotePermissionsChecksum,
      operationalChecksum = remoteOperationalChecksum,
      lootChecksum = remoteLootChecksum,
      sessionChecksum = remoteSessionChecksum,
      liveLootChecksum = remoteLiveLootChecksum,
      profileUpdatedAt = remoteProfileUpdatedAt,
      role = assignedRole,
      suppressProfileTouch = true,
    })
    -- JOIN acceptance is durable before profile comparison and recovery work.
    -- A later optional failure must not hide the member or withhold their ACK.
    INTERNAL_API.LIDCOUNCIL_ClearDeferredJoinMemberRows(activeSession, memberKey)
    ClearSessionTargetMemberSnapshotWhispers(sessionId, memberKey)
    SendJoinAck(activeSession, profileName, memberKey)

    -- Keep the deferred closure's captured state compact. WoW's Lua runtime has
    -- a bounded upvalue budget, while the follow-up needs many JOIN fields.
    local joinFollowupContext = {
      activeSession = activeSession,
      assignedRole = assignedRole,
      claimedProfileId = claimedProfileId,
      hadLocalSharedProfile = hadLocalSharedProfile,
      joinedAt = joinedAt,
      memberKey = memberKey,
      profileName = profileName,
      remoteLiveLootChecksum = remoteLiveLootChecksum,
      remoteLootChecksum = remoteLootChecksum,
      remoteLootRevision = remoteLootRevision,
      remoteOperationalChecksum = remoteOperationalChecksum,
      remoteOperationalRevision = remoteOperationalRevision,
      remotePermissionsChecksum = remotePermissionsChecksum,
      remotePermissionsRevision = remotePermissionsRevision,
      remoteProfileUpdatedAt = remoteProfileUpdatedAt,
      remoteSessionChecksum = remoteSessionChecksum,
      remoteSessionRevision = remoteSessionRevision,
      remoteSettingsChecksum = remoteSettingsChecksum,
      remoteSettingsRevision = remoteSettingsRevision,
      selfKey = selfKey,
      sessionId = sessionId,
    }
    local function RunNewMemberAcceptedJoinFollowup()
    local activeSession = joinFollowupContext.activeSession
    local assignedRole = joinFollowupContext.assignedRole
    local claimedProfileId = joinFollowupContext.claimedProfileId
    local hadLocalSharedProfile = joinFollowupContext.hadLocalSharedProfile
    local joinedAt = joinFollowupContext.joinedAt
    local memberKey = joinFollowupContext.memberKey
    local profileName = joinFollowupContext.profileName
    local remoteLiveLootChecksum = joinFollowupContext.remoteLiveLootChecksum
    local remoteLootChecksum = joinFollowupContext.remoteLootChecksum
    local remoteLootRevision = joinFollowupContext.remoteLootRevision
    local remoteOperationalChecksum = joinFollowupContext.remoteOperationalChecksum
    local remoteOperationalRevision = joinFollowupContext.remoteOperationalRevision
    local remotePermissionsChecksum = joinFollowupContext.remotePermissionsChecksum
    local remotePermissionsRevision = joinFollowupContext.remotePermissionsRevision
    local remoteProfileUpdatedAt = joinFollowupContext.remoteProfileUpdatedAt
    local remoteSessionChecksum = joinFollowupContext.remoteSessionChecksum
    local remoteSessionRevision = joinFollowupContext.remoteSessionRevision
    local remoteSettingsChecksum = joinFollowupContext.remoteSettingsChecksum
    local remoteSettingsRevision = joinFollowupContext.remoteSettingsRevision
    local selfKey = joinFollowupContext.selfKey
    local sessionId = joinFollowupContext.sessionId
    deps.AddCharacterToList(memberKey)
    local roleOk, persistedRole = deps.EnsureLootProfileMemberRole(profileName, memberKey, "RAIDER")
    if roleOk then
      assignedRole = FirstNonEmptyText(persistedRole, assignedRole, "RAIDER")
    end

    local localProfileId = TrimText(select(1, deps.GetLootProfileId(profileName)) or "")
    local localRevisionSummary = deps.NormalizeRevisionSummary(
      GetLootProfileRevisionSummary(profileName),
      profileName,
      localProfileId
    )
    local localLiveLootChecksum = profileSyncMetaOps.buildSessionLiveLootChecksum(profileName, activeSession)
    local localArchiveLootChecksum = profileSyncMetaOps.buildSessionArchiveLootChecksum(profileName, activeSession)
    localRevisionSummary.liveLootChecksum = localLiveLootChecksum
    localRevisionSummary.archiveLootChecksum = localArchiveLootChecksum
    local remoteRevisionSummary = deps.NormalizeRevisionSummary({
      profileName = profileName,
      profileId = claimedProfileId,
      settings = remoteSettingsRevision,
      permissions = remotePermissionsRevision,
      operational = remoteOperationalRevision,
      loot = remoteLootRevision,
      session = remoteSessionRevision,
      settingsChecksum = remoteSettingsChecksum,
      permissionsChecksum = remotePermissionsChecksum,
      operationalChecksum = remoteOperationalChecksum,
      lootChecksum = remoteLootChecksum,
      sessionChecksum = remoteSessionChecksum,
      liveLootChecksum = remoteLiveLootChecksum,
      archiveLootChecksum = TrimText(type(activeSession.members) == "table" and type(activeSession.members[memberKey]) == "table" and activeSession.members[memberKey].archiveLootChecksum or ""),
      updatedAt = remoteProfileUpdatedAt,
    }, profileName, claimedProfileId)
    local remoteNewerDomains = {}
    local localNewerDomains = {}
    local shouldSendSnapshot = true
    local snapshotDomains = nil

    if localProfileId ~= "" and claimedProfileId ~= "" and string.lower(localProfileId) == string.lower(claimedProfileId) then
      remoteNewerDomains, localNewerDomains = deps.CompareProfileRevisionSummaries(localRevisionSummary, remoteRevisionSummary)
      if localLiveLootChecksum ~= "" and remoteLiveLootChecksum ~= ""
        and string.lower(localLiveLootChecksum) == string.lower(remoteLiveLootChecksum)
      then
        local remoteArchiveLootChecksum = TrimText(remoteRevisionSummary.archiveLootChecksum)
        local archiveOnlyLootDifference = localArchiveLootChecksum ~= ""
          and remoteArchiveLootChecksum ~= ""
          and string.lower(localArchiveLootChecksum) ~= string.lower(remoteArchiveLootChecksum)
        local filteredRemote = {}
        for _, domain in ipairs(remoteNewerDomains) do
          if string.lower(TrimText(domain)) ~= "loot" then
            filteredRemote[#filteredRemote + 1] = domain
          elseif not archiveOnlyLootDifference then
            filteredRemote[#filteredRemote + 1] = domain
          end
        end
        remoteNewerDomains = filteredRemote
        local filteredLocal = {}
        for _, domain in ipairs(localNewerDomains) do
          if string.lower(TrimText(domain)) ~= "loot" then
            filteredLocal[#filteredLocal + 1] = domain
          elseif not archiveOnlyLootDifference then
            filteredLocal[#filteredLocal + 1] = domain
          end
        end
        localNewerDomains = filteredLocal
      end
      if hadLocalSharedProfile then
        snapshotDomains = #localNewerDomains > 0 and CloneComparedDomains(localNewerDomains) or nil
        shouldSendSnapshot = #localNewerDomains > 0 and #remoteNewerDomains == 0
      else
        shouldSendSnapshot = true
      end

      if #remoteNewerDomains > 0 and #localNewerDomains > 0 then
        sessionLifecycleOps.emitSyncRuntimeStateNotice(sessionId, profileName, "remote_join_diverged", {
          profileName = profileName,
          memberKey = memberKey,
          sender = memberKey,
          remoteDomains = remoteNewerDomains,
          localDomains = localNewerDomains,
          refreshEditor = false,
          remoteDomainsText = deps.FormatProfileRevisionDomains(remoteNewerDomains),
          localDomainsText = deps.FormatProfileRevisionDomains(localNewerDomains),
        })
      elseif #remoteNewerDomains > 0 then
        sessionLifecycleOps.emitSyncRuntimeStateNotice(sessionId, profileName, "remote_join_member_newer", {
          profileName = profileName,
          memberKey = memberKey,
          sender = memberKey,
          remoteDomains = remoteNewerDomains,
          refreshEditor = false,
          role = assignedRole or "RAIDER",
          remoteDomainsText = deps.FormatProfileRevisionDomains(remoteNewerDomains),
        })
      end
    end

    local member = activeSession.members and activeSession.members[memberKey] or {
      name = memberKey,
      status = "JOINED",
      joinedAt = joinedAt,
    }
    member.profileMaster = deps.GetLootProfileMaster(profileName)
    member.role = assignedRole
    sessionLifecycleOps.emitSyncRuntimeState(
      sessionId,
      profileName,
      "member_joined",
      "info",
      memberKey .. " joined the preparation lobby.",
      {
        sender = memberKey,
        rosterEvent = {
          action = "joined",
          memberKey = memberKey,
        },
        printNotice = false,
      }
    )
    -- Publish one role-complete row after durable local admission.
    BroadcastMember(profileName, sessionId, memberKey, member, nil, nil, {
      forceImmediate = true,
    })
    if type(profileSyncMetaOps.sendJoinTargetedMemberBurst) == "function" then
      profileSyncMetaOps.sendJoinTargetedMemberBurst(activeSession, profileName, sessionId, memberKey, {
        suppressCheckpoint = true,
      })
    end
    -- The joiner defaults their own Auto-Pass to ON. Send the host's current
    -- preference separately after the roster snapshot so their host row has
    -- the correct state even if a stale MEMBER packet is skipped.
    local hostAutoPassEnabled = type(deps.GetLocalAutoPassEnabled) == "function"
      and (deps.GetLocalAutoPassEnabled() and true or false)
      or (type(activeSession.members) == "table" and activeSession.members[selfKey]
        and activeSession.members[selfKey].localAutoPassEnabled == true)
    local hostAutoPassNoticeSent = BroadcastAutoPassNotice(
      sessionId,
      profileName,
      selfKey,
      hostAutoPassEnabled,
      "WHISPER",
      memberKey
    )
    local hostAutoPassStateText = "Host Auto-Pass "
      .. (hostAutoPassEnabled and "ON" or "OFF")
      .. (hostAutoPassNoticeSent and " was queued for " or " could not be queued for ")
      .. memberKey .. "."
    if type(RecordProfileSyncDecision) == "function" then
      RecordProfileSyncDecision("send_targeted_host_autopass", {
        action = hostAutoPassNoticeSent and "queued" or "failed",
        sessionId = sessionId,
        profileName = profileName,
        target = memberKey,
        enabled = hostAutoPassEnabled == true,
        reason = "initial_join_roster_refresh",
      })
    end
    sessionLifecycleOps.emitSyncRuntimeState(
      sessionId,
      profileName,
      "host_autopass_targeted_queued",
      hostAutoPassNoticeSent and "info" or "warn",
      hostAutoPassStateText,
      {
        sender = memberKey,
        skipIfSame = true,
        refreshSyncManagement = true,
        printNotice = false,
        coalesceWindowSeconds = 1.5,
        coalesceKey = "host_autopass_notice|" .. string.lower(TrimText(memberKey)),
        coalesceSignature = (hostAutoPassEnabled and "1" or "0") .. "|" .. (hostAutoPassNoticeSent and "queued" or "failed"),
      }
    )
    if hadLocalSharedProfile then
      if type(profileSyncMetaOps.queueMemberBackgroundSyncBurst) == "function" then
        profileSyncMetaOps.queueMemberBackgroundSyncBurst(activeSession, profileName, sessionId, memberKey, {
          queuePrewarm = true,
          prewarmReason = "join_prewarm",
          prewarmDomains = CloneCheckpointDomainList(snapshotDomains),
        })
      else
        PrewarmMemberPreciseLiveSyncState(activeSession, profileName, sessionId, memberKey, {
          mode = "BACKGROUND",
          reason = "join_prewarm",
          domains = snapshotDomains,
        })
      end
    end
    if IsLiveSession(activeSession) then
      SendComm(
        "BEGIN",
        "WHISPER",
        memberKey,
        sessionId,
        profileName,
        localProfileId,
        activeSession.host,
        activeSession.activatedAt or (time and time() or 0),
        deps.GetLootProfileMaster(profileName),
        GetCommProtocolMarker()
      )
    end
    if shouldSendSnapshot then
      if hadLocalSharedProfile then
        local syncCandidateSnapshot = BuildActiveSyncCandidateSnapshot()
        local syncCandidate = select(1, GetActiveSyncCandidateContextFromSnapshot(memberKey, syncCandidateSnapshot))
        local repairDomains, repairSubdomains = profileSyncMetaOps.buildAutomaticHostRepairScope(
          memberKey,
          snapshotDomains,
          sessionId,
          syncCandidate
        )
        local immediateRepairDomains = CloneCheckpointDomainList(repairDomains)
        local immediateRepairSubdomains = CloneCheckpointSubdomainList(repairSubdomains)
        local deferredManifestDomains = {}
        local deferredManifestSubdomains = {}
        if HasComparedDomain(immediateRepairDomains, "loot")
          or #profileSyncMetaOps.filterRepairSubdomainsByDomain(immediateRepairSubdomains, "loot") > 0
        then
          deferredManifestDomains = { "loot" }
          deferredManifestSubdomains = profileSyncMetaOps.filterRepairSubdomainsByDomain(
            immediateRepairSubdomains,
            "loot"
          )
          immediateRepairDomains = profileSyncMetaOps.removeCheckpointDomain(immediateRepairDomains, "loot")
          immediateRepairSubdomains = profileSyncMetaOps.excludeRepairSubdomainsByDomain(
            immediateRepairSubdomains,
            "loot"
          )
        end

        local queuedRepair = false
        local queuedRepairCount = 0
        local repairError = nil
        if #immediateRepairDomains > 0 or #immediateRepairSubdomains > 0 then
          queuedRepair, queuedRepairCount, repairError = QueueLiveFirstRepairTransfersForMember(activeSession, profileName, sessionId, memberKey, {
            mode = "LIVE",
            reason = (#immediateRepairSubdomains > 0 and #immediateRepairDomains == 0)
              and "join_repair_precise"
              or (#immediateRepairSubdomains > 0 and "join_repair_targeted" or "join_repair"),
            domains = immediateRepairDomains,
            subdomains = immediateRepairSubdomains,
            syncCandidate = syncCandidate,
          })
        end

        local deferredRepairScheduled = false
        if #deferredManifestDomains > 0 then
          deferredRepairScheduled = ScheduleDeferredJoinManifestRepair(
            profileName,
            sessionId,
            memberKey,
            deferredManifestDomains,
            deferredManifestSubdomains,
            {
              requirePreciseProof = true,
              maxPreciseProofAttempts = 4,
            }
          )
        end

        if not queuedRepair and not deferredRepairScheduled then
          local preparedSnapshot, prepareError = PrepareProfileSnapshotTransfer(profileName, {
            domains = snapshotDomains,
          })
          if preparedSnapshot then
            local coalesceJoinSnapshotRepair, joinSnapshotRequestState, _, joinSnapshotCoalescedReason =
              EvaluateRecentMemberRepairRequest(
                activeSession,
                profileName,
                sessionId,
                memberKey,
                snapshotDomains,
                {},
                {
                  mode = "LIVE",
                  forceFullSnapshot = preparedSnapshot.fullSnapshotFallback == true,
                  syncCandidate = syncCandidate,
                }
              )
            if coalesceJoinSnapshotRepair then
              if type(RecordProfileSyncDecision) == "function" then
                RecordProfileSyncDecision("handle_join", {
                  action = "coalesced_join_snapshot_fallback",
                  sessionId = sessionId,
                  profileName = profileName,
                  mode = "LIVE",
                  reason = "join_repair",
                  target = memberKey,
                  targetCount = 1,
                  queuedCount = 0,
                  requestedDomains = CloneCheckpointDomainList(snapshotDomains),
                  requestedSubdomains = {},
                  requestedScope = "targeted",
                  coalescedReason = TrimText(joinSnapshotCoalescedReason),
                })
              end
            else
              local ok, queuedCountOrError = QueueProfileSnapshotForMember(profileName, sessionId, memberKey, {
                mode = "LIVE",
                reason = "join_repair",
                domains = snapshotDomains,
                preparedSnapshot = preparedSnapshot,
              })
              if ok then
                queuedRepair = true
                queuedRepairCount = math.max(1, tonumber(queuedCountOrError) or 1)
                RememberRecentMemberRepairRequestState(sessionId, memberKey, joinSnapshotRequestState)
              else
                repairError = queuedCountOrError
              end
            end
          elseif prepareError then
            repairError = prepareError
          end
        end

        local queuedImmediateRepairCount = math.max(0, tonumber(queuedRepairCount) or 0)
        if queuedRepair then
          if deferredRepairScheduled and queuedImmediateRepairCount > 0 then
            sessionLifecycleOps.emitSyncRuntimeStateNotice(sessionId, profileName, "host_join_repair_pending", {
              memberKey = memberKey,
              sender = memberKey,
              localDomains = localNewerDomains,
              skipIfSame = true,
              refreshEditor = false,
              printWhenChangedOnly = true,
              coalesceWindowSeconds = 2.0,
              coalesceKey = "host_join_repair|" .. string.lower(TrimText(memberKey)),
              coalesceSignature = "host_join_repair_progress",
            })
          elseif deferredRepairScheduled then
            sessionLifecycleOps.emitSyncRuntimeStateNotice(sessionId, profileName, "host_join_repair_scopes_only", {
              memberKey = memberKey,
              sender = memberKey,
              localDomains = localNewerDomains,
              skipIfSame = true,
              refreshEditor = false,
              printWhenChangedOnly = true,
              coalesceWindowSeconds = 2.0,
              coalesceKey = "host_join_repair|" .. string.lower(TrimText(memberKey)),
              coalesceSignature = "host_join_repair_progress",
            })
          elseif queuedImmediateRepairCount <= 0 then
            sessionLifecycleOps.emitSyncRuntimeStateNotice(sessionId, profileName, "host_join_repair_aligned", {
              memberKey = memberKey,
              sender = memberKey,
              localDomains = localNewerDomains,
              skipIfSame = true,
              refreshEditor = false,
              printWhenChangedOnly = true,
            })
          else
            sessionLifecycleOps.emitSyncRuntimeStateNotice(sessionId, profileName, "host_join_repair_sent", {
              memberKey = memberKey,
              sender = memberKey,
              localDomains = localNewerDomains,
              skipIfSame = true,
              refreshEditor = false,
              localDomainsText = deps.FormatProfileRevisionDomains(localNewerDomains),
              printWhenChangedOnly = true,
              coalesceWindowSeconds = 2.0,
              coalesceKey = "host_join_repair|" .. string.lower(TrimText(memberKey)),
              coalesceSignature = "host_join_repair_progress",
            })
          end
        elseif deferredRepairScheduled then
          sessionLifecycleOps.emitSyncRuntimeStateNotice(sessionId, profileName, "host_join_repair_scopes_only", {
            memberKey = memberKey,
            sender = memberKey,
            localDomains = localNewerDomains,
            skipIfSame = true,
            refreshEditor = false,
            printWhenChangedOnly = true,
            coalesceWindowSeconds = 2.0,
            coalesceKey = "host_join_repair|" .. string.lower(TrimText(memberKey)),
            coalesceSignature = "host_join_repair_progress",
          })
        elseif repairError then
          sessionLifecycleOps.emitSyncRuntimeStateNotice(sessionId, profileName, "host_join_repair_failed", {
            memberKey = memberKey,
            sender = memberKey,
            localDomains = localNewerDomains,
            error = repairError,
            skipIfSame = true,
            refreshEditor = false,
            printWhenChangedOnly = true,
          })
        end
      else
        local bootstrapQueued, backgroundQueued, queueError, bootstrapDetail = QueueMissingMemberBootstrapSync(profileName, sessionId, memberKey)
        if bootstrapQueued then
          if not (type(bootstrapDetail) == "table" and bootstrapDetail.deduped == true) then
            sessionLifecycleOps.emitSyncRuntimeStateNotice(sessionId, profileName, "missing_member_copy_bootstrap", {
              memberKey = memberKey,
              sender = memberKey,
              refreshEditor = false,
              printNotice = false,
            })
            if backgroundQueued then
              Print(sessionLifecycleOps.buildSyncNoticeText("bootstrap_queued_with_followup", {
                memberKey = memberKey,
              }))
            else
              Print(sessionLifecycleOps.buildSyncNoticeText("bootstrap_queued_without_followup", {
                memberKey = memberKey,
              }))
              if queueError then
                Print(sessionLifecycleOps.buildSyncNoticeText("bootstrap_followup_queue_failed", {
                  memberKey = memberKey,
                  error = queueError,
                }))
              end
            end
          end
        elseif queueError then
          sessionLifecycleOps.emitSyncRuntimeStateNotice(sessionId, profileName, "missing_member_copy_bootstrap_failed", {
            memberKey = memberKey,
            sender = memberKey,
            error = queueError,
            skipIfSame = true,
            refreshEditor = false,
            printWhenChangedOnly = true,
          })
        end
      end
    end
    if hadLocalSharedProfile and (#remoteNewerDomains > 0 or #localNewerDomains > 0) then
      QueueAutoDetailedComparison(memberKey, "join_mismatch")
    end
    Print(memberKey .. " joined loot session \"" .. profileName .. "\".")
    end

    local queuedFollowup, queueFollowupError = sessionLifecycleOps.queueAcceptedJoinFollowup(
      sessionId,
      profileName,
      memberKey,
      "new-member admission follow-up",
      RunNewMemberAcceptedJoinFollowup,
      {
        priority = 1,
        ensureRole = true,
      }
    )
    if queuedFollowup ~= true then
      -- WoW always provides the timer path used above. Keep a guarded fallback
      -- so admission remains complete in stripped validation environments.
      sessionLifecycleOps.runAcceptedJoinFollowup(
        "new-member admission fallback",
        sessionId,
        profileName,
        memberKey,
        RunNewMemberAcceptedJoinFollowup
      )
      if type(RecordProfileSyncDecision) == "function" then
        RecordProfileSyncDecision("accepted_join_followup", {
          action = "timer_fallback",
          sessionId = sessionId,
          profileName = profileName,
          target = memberKey,
          reason = queueFollowupError,
        })
      end
    end
  end

  INTERNAL_API.LIDCOUNCIL_HandleMember_Impl = function(fields, sender)
    local payload, payloadError = profileSyncMetaOps.parseInboundMemberPayload(fields)
    if type(payload) ~= "table" then
      profileSyncMetaOps.recordInboundPayloadReject("MEMBER", sender, fields, payloadError)
      return
    end
    local payloadNow = tonumber(time and time() or 0) or 0
    PruneAgedSessionRuntimeTracking(GetProfileCheckpointSyncTime())

    local activeSession, activeProfileName = GetActiveLootSession()
    if not DoesActiveSessionMatch(activeSession, activeProfileName, payload.sessionId, payload.profileName) then
      return
    end
    if not deps.IsActiveSessionHostSender(activeSession, sender) then
      return
    end
    if not IsCurrentGroupCharacter(NormalizeSenderKey(sender)) then
      return
    end

    local localProfileName = FirstNonEmptyText(activeProfileName, activeSession.profileName, activeSession.remoteProfileName, payload.profileName)
    local existingMember = FindSessionMember(activeSession, payload.memberKey)
    local previousCanonicalMemberStatus = type(existingMember) == "table"
      and string.upper(TrimText(existingMember.status or "JOINED"))
      or ""
    local previousVisibleState = BuildSessionVisibleMemberStateSignature(existingMember)
    local existingMemberState = type(existingMember) == "table" and existingMember or {}
    local retainedHostStatusMatrix = profileSyncMetaOps.getHostMemberStatusMatrixValue(
      existingMember,
      payload.sessionId
    )
    local retainedHostStatusGeneration = profileSyncMetaOps.getHostMemberStatusMatrixGeneration(
      existingMember,
      payload.sessionId
    )
    local acceptedHostStatusMatrix = retainedHostStatusMatrix
    local acceptedHostStatusGeneration = retainedHostStatusGeneration
    if type(profileSyncMetaOps.decodeHostMemberStatusMatrix(payload.hostSyncStatusMatrix)) == "table" then
      local accepted, resolvedMatrix, resolvedGeneration = profileSyncMetaOps.resolveHostMemberStatusGeneration(
        retainedHostStatusMatrix,
        retainedHostStatusGeneration,
        payload.hostSyncStatusMatrix,
        payload.hostSyncStatusGeneration,
        true
      )
      if accepted == true then
        acceptedHostStatusMatrix = resolvedMatrix
        acceptedHostStatusGeneration = resolvedGeneration
      end
    end
    local incomingMemberState = {
      status = payload.status,
      joinedAt = payload.joinedAt,
      leftAt = payload.leftAt,
      addonVersion = FirstNonEmptyText(payload.addonVersion, existingMemberState.addonVersion),
      clientVersion = FirstNonEmptyText(payload.clientVersion, existingMemberState.clientVersion),
      className = FirstNonEmptyText(payload.className, existingMemberState.className),
      classFile = FirstNonEmptyText(payload.classFile, existingMemberState.classFile),
      specName = FirstNonEmptyText(payload.specName, existingMemberState.specName),
      specIcon = FirstNonEmptyText(payload.specIcon, existingMemberState.specIcon),
      localAutoPassEnabled = payload.localAutoPassEnabled,
      profileMaster = FirstNonEmptyText(payload.profileMaster, existingMemberState.profileMaster),
      role = FirstNonEmptyText(payload.role, existingMemberState.role),
      sharedProfileId = payload.sharedProfileId,
      settingsRevision = payload.settingsRevision,
      permissionsRevision = payload.permissionsRevision,
      operationalRevision = payload.operationalRevision,
      lootRevision = payload.lootRevision,
      sessionRevision = payload.sessionRevision,
      profileUpdatedAt = payload.profileUpdatedAt,
      -- Compact MEMBER packets may omit checksums to stay below WoW's payload
      -- limit. An omitted checksum means no newer checksum information.
      settingsChecksum = FirstNonEmptyText(payload.settingsChecksum, existingMemberState.settingsChecksum),
      permissionsChecksum = FirstNonEmptyText(payload.permissionsChecksum, existingMemberState.permissionsChecksum),
      operationalChecksum = FirstNonEmptyText(payload.operationalChecksum, existingMemberState.operationalChecksum),
      lootChecksum = FirstNonEmptyText(payload.lootChecksum, existingMemberState.lootChecksum),
      sessionChecksum = FirstNonEmptyText(payload.sessionChecksum, existingMemberState.sessionChecksum),
      liveLootChecksum = FirstNonEmptyText(payload.liveLootChecksum, existingMemberState.liveLootChecksum),
      archiveLootChecksum = FirstNonEmptyText(payload.archiveLootChecksum, existingMemberState.archiveLootChecksum),
      lootListArchiveChecksum = FirstNonEmptyText(
        payload.lootListArchiveChecksum,
        existingMemberState.lootListArchiveChecksum
      ),
      itemHistoryArchiveChecksum = FirstNonEmptyText(
        payload.itemHistoryArchiveChecksum,
        existingMemberState.itemHistoryArchiveChecksum
      ),
      sessionHistoryArchiveChecksum = FirstNonEmptyText(
        payload.sessionHistoryArchiveChecksum,
        existingMemberState.sessionHistoryArchiveChecksum
      ),
      funAwardsArchiveChecksum = FirstNonEmptyText(
        payload.funAwardsArchiveChecksum,
        existingMemberState.funAwardsArchiveChecksum
      ),
      -- Only MEMBER packets from the verified active host reach this point.
      -- An omitted matrix preserves the last host verdict for compatibility
      -- with compact packets and older hosts.
      hostSyncStatusMatrix = acceptedHostStatusMatrix,
      hostSyncStatusSessionId = payload.sessionId,
      hostSyncStatusGeneration = acceptedHostStatusGeneration,
      lastSyncAt = payload.lastSyncAt,
      lastDeltaRecoveryAt = payload.lastDeltaRecoveryAt,
      lastDeltaRecoveryState = payload.lastDeltaRecoveryState,
      lastDeltaRecoveryKind = payload.lastDeltaRecoveryKind,
      lastDeltaRecoveryRequestedScope = payload.lastDeltaRecoveryRequestedScope,
      lastDeltaRecoveryScopeEscalated = payload.lastDeltaRecoveryScopeEscalated,
      lastDeltaRecoveryFullSnapshotFallback = payload.lastDeltaRecoveryFullSnapshotFallback,
      lastDeltaRecoveryScopeEscalationKinds = payload.lastDeltaRecoveryScopeEscalationKinds,
      lastDeltaRecoverySummary = payload.lastDeltaRecoverySummary,
    }
    local inboundMemberGate = profileSyncMetaOps.evaluateInboundStampedStateWrite(
      existingMember,
      incomingMemberState,
      {
        stateKind = "session_member",
        previousVisibleState = previousVisibleState,
      }
    )
    if inboundMemberGate.shouldSkip then
      return
    end
    if inboundMemberGate.needsFreshSyncStamp then
      incomingMemberState.lastSyncAt = payloadNow
      incomingMemberState.suppressProfileTouch = true
    end
    local memberRefreshOpts = {
      previousVisibleState = previousVisibleState,
      defer = true,
    }
    if inboundMemberGate.sameState == true then
      memberRefreshOpts.skipVisibleStateDiff = true
      memberRefreshOpts.forceCurrentSectionRefreshWhenCoalesced = inboundMemberGate.needsFreshSyncStamp == true
    end
    if payload.status == "REMOVED" then
      incomingMemberState.status = "REMOVED"
      incomingMemberState.leftAt = incomingMemberState.leftAt or payloadNow
      local ok, member = UpsertLootSessionMember(localProfileName, payload.sessionId, payload.memberKey, incomingMemberState)
      if ok and type(member) == "table" then
        profileSyncMetaOps.setHostMemberStatusMatrixValue(
          member,
          incomingMemberState.hostSyncStatusMatrix,
          payload.sessionId,
          incomingMemberState.hostSyncStatusGeneration,
          "MEMBER",
          "host readiness publication"
        )
      end
      INTERNAL_API.LIDCOUNCIL_HandleSessionMemberVisibleStateUpdate(
        activeSession,
        payload.memberKey,
        existingMember,
        ok and type(member) == "table" and member or nil,
        memberRefreshOpts
      )
      if type(profileSyncMetaOps.scheduleDelayedLocalProfileStateSend) == "function"
        and previousCanonicalMemberStatus ~= "REMOVED"
      then
        profileSyncMetaOps.scheduleDelayedLocalProfileStateSend(payload.sessionId, payload.profileName, localProfileName)
      end
      return
    end

    local ok, member = UpsertLootSessionMember(localProfileName, payload.sessionId, payload.memberKey, incomingMemberState)
    if ok and type(member) == "table" then
      profileSyncMetaOps.setHostMemberStatusMatrixValue(
        member,
        incomingMemberState.hostSyncStatusMatrix,
        payload.sessionId,
        incomingMemberState.hostSyncStatusGeneration,
        "MEMBER",
        "host readiness publication"
      )
    end
    deps.AddCharacterToList(payload.memberKey)
    INTERNAL_API.LIDCOUNCIL_HandleSessionMemberVisibleStateUpdate(
      activeSession,
      payload.memberKey,
      existingMember,
      ok and type(member) == "table" and member or nil,
      memberRefreshOpts
    )
    local currentCanonicalMemberStatus = type(member) == "table"
      and string.upper(TrimText(member.status or "JOINED"))
      or ""
    if type(profileSyncMetaOps.scheduleDelayedLocalProfileStateSend) == "function"
      and previousCanonicalMemberStatus ~= currentCanonicalMemberStatus
    then
      profileSyncMetaOps.scheduleDelayedLocalProfileStateSend(payload.sessionId, payload.profileName, localProfileName)
    end
  end

  INTERNAL_API.LIDCOUNCIL_HandleProfileState_Impl = function(fields, sender)
    local payload, payloadError = profileSyncMetaOps.parseInboundProfileStatePayload(fields, sender)
    if type(payload) ~= "table" then
      profileSyncMetaOps.recordInboundPayloadReject("PSTATE", sender, fields, payloadError)
      return
    end
    local payloadNow = tonumber(time and time() or 0) or 0
    PruneAgedSessionRuntimeTracking(GetProfileCheckpointSyncTime())

    local activeSession, activeProfileName = GetActiveLootSession()
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if not DoesActiveSessionMatch(activeSession, activeProfileName, payload.sessionId, payload.profileName) then
      return
    end
    if not AreCharacterKeysSame(activeSession.host or "", selfKey) then
      return
    end
    if not IsClaimedActorSenderMatch(sender, payload.memberKey) then
      return
    end
    if not IsJoinedSessionCharacter(activeSession, payload.memberKey) then
      return
    end
    if payload.protocolVersion ~= COMM_PROTOCOL_VERSION then
      return
    end

    local existingMember = FindSessionMember(activeSession, payload.memberKey)
    local incomingProfileState = {
      sharedProfileId = payload.sharedProfileId,
      settingsRevision = payload.settingsRevision,
      permissionsRevision = payload.permissionsRevision,
      operationalRevision = payload.operationalRevision,
      lootRevision = payload.lootRevision,
      sessionRevision = payload.sessionRevision,
      profileUpdatedAt = payload.profileUpdatedAt,
      settingsChecksum = payload.settingsChecksum,
      permissionsChecksum = payload.permissionsChecksum,
      operationalChecksum = payload.operationalChecksum,
      lootChecksum = payload.lootChecksum,
      sessionChecksum = payload.sessionChecksum,
      liveLootChecksum = payload.liveLootChecksum,
      archiveLootChecksum = payload.archiveLootChecksum,
    }
    if payload.archiveProofAvailable == true then
      for _, checksumField in ipairs({
        "lootListArchiveChecksum",
        "itemHistoryArchiveChecksum",
        "sessionHistoryArchiveChecksum",
        "funAwardsArchiveChecksum",
      }) do
        if TrimText(payload[checksumField]) ~= "" then
          incomingProfileState[checksumField] = payload[checksumField]
        end
      end
    end
    local inboundProfileStateGate = profileSyncMetaOps.evaluateInboundStampedStateWrite(
      existingMember,
      incomingProfileState,
      {
        stateKind = "profile",
      }
    )
    if inboundProfileStateGate.shouldSkip then
      return
    end
    local previousVisibleState = BuildSessionVisibleMemberStateSignature(existingMember)
    local previousHadSharedState = INTERNAL_API.LIDCOUNCIL_HasMemberSharedProfileState(existingMember)
    local previousCurrentSessionDisplayBaseContext = nil
    local previousCurrentSessionDisplay = nil
    if type(existingMember) == "table" then
      previousCurrentSessionDisplayBaseContext = INTERNAL_API.LIDCOUNCIL_BuildHostCurrentSessionDisplayContext(
        activeSession,
        payload.profileName,
        payload.memberKey
      )
      previousCurrentSessionDisplay = INTERNAL_API.LIDCOUNCIL_BuildHostCurrentSessionMemberDisplayState(
        activeSession,
        payload.profileName,
        payload.memberKey,
        existingMember,
        previousCurrentSessionDisplayBaseContext
      )
    end

    incomingProfileState.lastSyncAt = payloadNow
    incomingProfileState.suppressProfileTouch = true
    local ok, member = UpsertLootSessionMember(payload.profileName, payload.sessionId, payload.memberKey, incomingProfileState)
    if ok then
      profileSyncMetaOps.rememberHostMemberReadinessProof(
        member,
        payload.sessionId,
        payload.memberKey,
        "PSTATE"
      )
      if payload.archiveProofAvailable == true
        and type(profileSyncMetaOps.reconcileMemberArchiveTransactions) == "function"
      then
        profileSyncMetaOps.reconcileMemberArchiveTransactions(activeSession, payload.memberKey, member)
      end
      if payload.archiveProofComplete == true
        and type(profileSyncMetaOps.scheduleMemberArchiveScopesFromChecksums) == "function"
      then
        profileSyncMetaOps.scheduleMemberArchiveScopesFromChecksums(
          activeSession,
          payload.profileName,
          payload.sessionId,
          payload.memberKey,
          member
        )
      end
      local becameSharedReplica = INTERNAL_API.LIDCOUNCIL_HasMemberSharedProfileState(incomingProfileState)
        and not previousHadSharedState
      local acceptedStatusMatrix = profileSyncMetaOps.buildHostMemberSyncStatusMatrix(
        activeSession,
        payload.profileName,
        payload.memberKey,
        member
      )
      local shouldPrimeReplicaProof = INTERNAL_API.LIDCOUNCIL_ShouldPrimeReplicaProofWork_Impl(
        becameSharedReplica,
        acceptedStatusMatrix
      )
      local updatedSyncCandidateSnapshot = previousCurrentSessionDisplay ~= nil and BuildActiveSyncCandidateSnapshot() or nil
      local updatedCurrentSessionDisplayBaseContext = INTERNAL_API.LIDCOUNCIL_BuildHostCurrentSessionDisplayContextFromBase(
        activeSession,
        payload.profileName,
        payload.memberKey,
        previousCurrentSessionDisplayBaseContext,
        updatedSyncCandidateSnapshot
      )
      local deferredJoinBootstrapReady = INTERNAL_API.LIDCOUNCIL_GetDeferredJoinMemberBootstrapState(
        activeSession,
        payload.profileName,
        payload.memberKey,
        member,
        {
          localProfileId = updatedCurrentSessionDisplayBaseContext.localProfileId,
          localSummary = updatedCurrentSessionDisplayBaseContext.localSummary,
        }
      )
      INTERNAL_API.LIDCOUNCIL_HandleHostMemberPostUpdate(
        activeSession,
        payload.profileName,
        payload.sessionId,
        payload.memberKey,
        existingMember,
        member,
        {
          previousVisibleState = previousVisibleState,
          previousCurrentSessionDisplay = previousCurrentSessionDisplay,
          currentSessionDisplayContext = previousCurrentSessionDisplayBaseContext,
          updatedCurrentSessionDisplayContext = updatedCurrentSessionDisplayBaseContext,
          flushDeferredJoinRows = true,
          passDisplayStateToDeferredFlush = true,
          deferredJoinFlushOpts = {
            bootstrapReady = deferredJoinBootstrapReady == "READY",
            localProfileId = updatedCurrentSessionDisplayBaseContext.localProfileId,
            localSummary = updatedCurrentSessionDisplayBaseContext.localSummary,
          },
          broadcastVisibleStateChange = true,
          -- Publish the first accepted exact proof even when an earlier repair
          -- ACK predicted the same row. Stable MEMBER dedupe suppresses every
          -- identical repeat, and proof publication never creates a checkpoint.
          broadcastVisibleStateAlways = true,
          broadcastVisibleStateForceImmediate = true,
          broadcastVisibleStateSuppressCheckpoint = true,
          prewarmWhen = shouldPrimeReplicaProof,
          prewarmOnVisibleStateChange = false,
          prewarmReason = becameSharedReplica and "profile_state_bootstrap_prewarm" or "profile_state_prewarm",
          prewarmForce = shouldPrimeReplicaProof,
          queueComparisonWhen = shouldPrimeReplicaProof,
          queueComparisonOnVisibleStateChange = false,
          queueComparisonReason = "profile_state",
          queuePostBootstrapRevalidation = shouldPrimeReplicaProof,
          syncCandidateSnapshot = updatedSyncCandidateSnapshot,
          skipRefreshWhenUnchanged = true,
          refreshSyncManagementWhenUnchanged = false,
          retainRefreshWhenUnchanged = shouldPrimeReplicaProof,
        }
      )
    end
  end

  INTERNAL_API.LIDCOUNCIL_HandleProfileStatePart_Impl = function(fields, sender)
    local payload, payloadError = profileSyncMetaOps.parseInboundProfileStatePartPayload(fields, sender)
    if type(payload) ~= "table" then
      profileSyncMetaOps.recordInboundPayloadReject("PSTATE_PART", sender, fields, payloadError)
      return
    end
    local activeSession, activeProfileName = GetActiveLootSession()
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if not DoesActiveSessionMatch(activeSession, activeProfileName, payload.sessionId, payload.profileName)
      or not AreCharacterKeysSame(activeSession.host or "", selfKey)
      or not IsClaimedActorSenderMatch(sender, payload.memberKey)
      or not IsJoinedSessionCharacter(activeSession, payload.memberKey)
    then
      return
    end

    local encodedState, assemblyState = profileSyncMetaOps.rememberPendingProfileStatePart(payload)
    if encodedState == nil and assemblyState == "waiting_for_profile_state_parts" then
      return
    end
    if encodedState == nil then
      profileSyncMetaOps.recordInboundPayloadReject("PSTATE_PART", sender, fields, assemblyState)
      return
    end
    if type(profileSyncMetaOps.parsePayload) ~= "function" then
      profileSyncMetaOps.recordInboundPayloadReject("PSTATE_PART", sender, fields, "profile_state_part_decoder_unavailable")
      return
    end
    local decodedOk, decodedFields = pcall(profileSyncMetaOps.parsePayload, encodedState)
    if not decodedOk or type(decodedFields) ~= "table" or TrimText(decodedFields[1]) ~= "PSTATE" then
      profileSyncMetaOps.recordInboundPayloadReject("PSTATE_PART", sender, fields, "invalid_reassembled_profile_state_payload")
      return
    end
    if TrimText(decodedFields[2]) ~= payload.sessionId
      or string.lower(TrimText(decodedFields[3])) ~= string.lower(payload.profileName)
      or not AreCharacterKeysSame(decodedFields[4], payload.memberKey)
      or TrimText(decodedFields[5]) ~= payload.profileId
    then
      profileSyncMetaOps.recordInboundPayloadReject("PSTATE_PART", sender, fields, "profile_state_part_identity_mismatch")
      return
    end
    INTERNAL_API.LIDCOUNCIL_HandleProfileState_Impl(decodedFields, sender)
  end

  INTERNAL_API.LIDCOUNCIL_HandleLocalAutoPass_Impl = function(fields, sender)
    local payload, payloadError = profileSyncMetaOps.parseInboundAutoPassPayload(fields, sender, {
      allowSenderFallback = true,
    })
    if type(payload) ~= "table" then
      profileSyncMetaOps.recordInboundPayloadReject("LOCALAP", sender, fields, payloadError)
      return
    end
    PruneAgedSessionRuntimeTracking(GetProfileCheckpointSyncTime())
    local sessionId = payload.sessionId
    local profileName = payload.profileName
    local memberKey = payload.memberKey
    local enabled = payload.enabled

    local activeSession, activeProfileName = GetActiveLootSession()
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if not DoesActiveSessionMatch(activeSession, activeProfileName, sessionId, profileName) then
      return
    end
    if not AreCharacterKeysSame(activeSession.host or "", selfKey) then
      return
    end
    if not IsClaimedActorSenderMatch(sender, memberKey) then
      return
    end
    if not IsCurrentGroupCharacter(memberKey) then
      return
    end
    if not IsJoinedSessionCharacter(activeSession, memberKey) then
      return
    end
    local existingMember = FindSessionMember(activeSession, memberKey)
    if type(existingMember) == "table"
      and deps.NormalizeEnabledFlag(existingMember.localAutoPassEnabled, true) == enabled
    then
      return
    end
    local previousVisibleState = BuildSessionVisibleMemberStateSignature(existingMember)

    local ok, member = UpsertLootSessionMember(profileName, sessionId, memberKey, {
      localAutoPassEnabled = enabled,
      suppressProfileTouch = true,
    })
    if not ok then
      return
    end

    local broadcastData = member or (type(activeSession.members) == "table" and activeSession.members[memberKey]) or {
      name = memberKey,
      status = "JOINED",
      joinedAt = time and time() or 0,
      localAutoPassEnabled = enabled,
    }
    BroadcastMember(profileName, sessionId, memberKey, broadcastData)
    BroadcastAutoPassNotice(sessionId, profileName, memberKey, enabled)
    Print(sessionLifecycleOps.buildMemberNoticeText("member_autopass_changed", {
      memberKey = memberKey,
      enabled = enabled,
    }))
    local currentUpdate = INTERNAL_API.LIDCOUNCIL_HandleSessionMemberVisibleStateUpdate(
      activeSession,
      memberKey,
      existingMember,
      member,
      {
        previousVisibleState = previousVisibleState,
        refreshEditor = false,
      }
    )
    if type(currentUpdate) == "table" and currentUpdate.currentSectionChanged == true then
      sessionUiOps.refreshCurrentSection()
    end
  end

  INTERNAL_API.LIDCOUNCIL_HandleAutoPassNotice_Impl = function(fields, sender)
    local payload, payloadError = profileSyncMetaOps.parseInboundAutoPassPayload(fields, sender, {
      allowSenderFallback = false,
    })
    if type(payload) ~= "table" then
      profileSyncMetaOps.recordInboundPayloadReject("APNOTICE", sender, fields, payloadError)
      return
    end
    PruneAgedSessionRuntimeTracking(GetProfileCheckpointSyncTime())
    local sessionId = payload.sessionId
    local profileName = payload.profileName
    local memberKey = payload.memberKey
    local enabled = payload.enabled

    local activeSession, activeProfileName = GetActiveLootSession()
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if not DoesActiveSessionMatch(activeSession, activeProfileName, sessionId, profileName) then
      return
    end
    if not deps.IsActiveSessionHostSender(activeSession, sender) then
      return
    end
    if not IsCurrentGroupCharacter(NormalizeSenderKey(sender)) then
      return
    end
    if AreCharacterKeysSame(NormalizeSenderKey(sender), selfKey) then
      return
    end
    if AreCharacterKeysSame(memberKey, selfKey) then
      return
    end
    local existingMember = FindSessionMember(activeSession, memberKey)
    if type(existingMember) == "table"
      and deps.NormalizeEnabledFlag(existingMember.localAutoPassEnabled, true) == enabled
    then
      return
    end

    local localProfileName = FirstNonEmptyText(activeProfileName, activeSession.profileName, activeSession.remoteProfileName, profileName)
    local previousVisibleState = BuildSessionVisibleMemberStateSignature(existingMember)
    local ok, member = UpsertLootSessionMember(localProfileName, sessionId, memberKey, {
      localAutoPassEnabled = enabled,
      suppressProfileTouch = true,
    })
    if not ok then
      return
    end
    if AreCharacterKeysSame(memberKey, activeSession.host or "") then
      local hostAutoPassAppliedText = "Applied host Auto-Pass "
        .. (enabled and "ON" or "OFF") .. " from " .. NormalizeSenderKey(sender) .. "."
      if type(RecordProfileSyncDecision) == "function" then
        RecordProfileSyncDecision("apply_targeted_host_autopass", {
          action = "applied",
          sessionId = sessionId,
          profileName = localProfileName,
          sender = NormalizeSenderKey(sender),
          memberKey = memberKey,
          enabled = enabled == true,
        })
      end
      sessionLifecycleOps.emitSyncRuntimeState(
        sessionId,
        localProfileName,
        "host_autopass_targeted_applied",
        "success",
        hostAutoPassAppliedText,
        {
          sender = NormalizeSenderKey(sender),
          skipIfSame = true,
          refreshSyncManagement = true,
          printNotice = false,
          coalesceWindowSeconds = 1.5,
          coalesceKey = "host_autopass_applied|" .. string.lower(TrimText(memberKey)),
          coalesceSignature = enabled and "1" or "0",
        }
      )
    end
    Print(sessionLifecycleOps.buildMemberNoticeText("member_autopass_changed", {
      memberKey = memberKey,
      enabled = enabled,
    }))
    local currentUpdate = INTERNAL_API.LIDCOUNCIL_HandleSessionMemberVisibleStateUpdate(
      activeSession,
      memberKey,
      existingMember,
      member,
      {
        previousVisibleState = previousVisibleState,
        refreshEditor = false,
      }
    )
    if type(currentUpdate) == "table" and currentUpdate.currentSectionChanged == true then
      sessionUiOps.refreshCurrentSection()
    end
  end

  INTERNAL_API.LIDCOUNCIL_BroadcastActiveSessionRoleUpdate_Impl = function(profileName, memberKey)
    local activeSession, activeProfileName = GetActiveLootSession()
    if not activeSession or tostring(activeProfileName or "") ~= tostring(profileName or "") then
      return false, sessionLifecycleOps.buildFlowNoticeText("role_update_no_session")
    end

    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if resolvedMemberKey == "" then
      return false, sessionLifecycleOps.buildFlowNoticeText("role_update_member_key_required")
    end

    local member = FindSessionMember(activeSession, resolvedMemberKey)
    if type(member) ~= "table" then
      return false, sessionLifecycleOps.buildFlowNoticeText("role_update_member_not_found")
    end

    member.profileMaster = deps.GetLootProfileMaster(profileName)
    member.role = deps.GetLootProfileRole(profileName, resolvedMemberKey)
    return BroadcastMember(profileName, activeSession.id, resolvedMemberKey, member)
  end

  INTERNAL_API.LIDCOUNCIL_HandleDecline_Impl = function(fields, sender)
    local payload, payloadError = profileSyncMetaOps.parseInboundDeclinePayload(fields, sender)
    if type(payload) ~= "table" then
      profileSyncMetaOps.recordInboundPayloadReject("DECLINE", sender, fields, payloadError)
      return
    end
    PruneAgedSessionRuntimeTracking(GetProfileCheckpointSyncTime())
    local sessionId = payload.sessionId
    local profileName = payload.profileName
    local memberKey = payload.memberKey

    local activeSession, activeProfileName = GetActiveLootSession()
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if not DoesActiveSessionMatch(activeSession, activeProfileName, sessionId, profileName) then
      return
    end
    if not AreCharacterKeysSame(activeSession.host or "", selfKey) then
      return
    end
    if not IsClaimedActorSenderMatch(sender, memberKey) then
      return
    end
    if not IsCurrentGroupCharacter(memberKey) then
      return
    end

    Print(sessionLifecycleOps.buildMemberNoticeText("member_declined", {
      profileName = profileName,
      memberKey = memberKey,
    }))
  end

  INTERNAL_API.LIDCOUNCIL_HandleLeave_Impl = function(fields, sender)
    local payload, payloadError = profileSyncMetaOps.parseInboundLeavePayload(fields, sender)
    if type(payload) ~= "table" then
      profileSyncMetaOps.recordInboundPayloadReject("LEAVE", sender, fields, payloadError)
      return
    end
    PruneAgedSessionRuntimeTracking(GetProfileCheckpointSyncTime())
    local sessionId = payload.sessionId
    local profileName = payload.profileName
    local memberKey = payload.memberKey
    local leftAt = payload.leftAt

    local activeSession, activeProfileName = GetActiveLootSession()
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if not DoesActiveSessionMatch(activeSession, activeProfileName, sessionId, profileName) then
      return
    end
    if not AreCharacterKeysSame(activeSession.host or "", selfKey) then
      return
    end
    if AreCharacterKeysSame(memberKey, selfKey) then
      return
    end
    if not IsClaimedActorSenderMatch(sender, memberKey) then
      return
    end

    local existingMember = FindSessionMember(activeSession, memberKey)
    if type(existingMember) ~= "table" then
      return
    end
    local previousVisibleState = BuildSessionVisibleMemberStateSignature(existingMember)
    local existingStatus = string.upper(TrimText(existingMember.status or "JOINED"))
    local existingJoinedAt = math.max(0, tonumber(existingMember.joinedAt) or 0)
    local existingLeftAt = math.max(0, tonumber(existingMember.leftAt) or 0)
    if existingStatus == "REMOVED" then
      ClearSessionMemberTargetedSyncRuntime(sessionId, profileName, memberKey, activeSession)
      return
    end
    if existingJoinedAt > 0 and leftAt > 0 and leftAt < existingJoinedAt then
      return
    end
    if existingStatus == "LEFT" and existingLeftAt >= math.max(0, leftAt) then
      return
    end

    local ok, member = UpsertLootSessionMember(profileName, sessionId, memberKey, {
      status = "LEFT",
      leftAt = leftAt,
      joinedAt = existingMember.joinedAt,
      suppressProfileTouch = true,
    })
    if not ok then
      return
    end
    ClearSessionMemberTargetedSyncRuntime(sessionId, profileName, memberKey, activeSession)

    BroadcastMember(profileName, sessionId, memberKey, member or existingMember)
    RefreshHostSessionMemberState(profileName, sessionId, {
      suppressCheckpoint = true,
    })
    sessionLifecycleOps.emitMemberStateNotice(sessionId, profileName, "remote_member_left", {
      profileName = profileName,
      memberKey = memberKey,
      sender = memberKey,
      refreshEditor = false,
      rosterEvent = {
        action = "left",
        memberKey = memberKey,
      },
    })
    INTERNAL_API.LIDCOUNCIL_HandleSessionMemberVisibleStateUpdate(
      activeSession,
      memberKey,
      existingMember,
      member,
      {
        previousVisibleState = previousVisibleState,
        defer = true,
      }
    )
  end

  INTERNAL_API.LIDCOUNCIL_HandleStop_Impl = function(fields, sender)
    local payload, payloadError = profileSyncMetaOps.parseInboundStopPayload(fields)
    if type(payload) ~= "table" then
      profileSyncMetaOps.recordInboundPayloadReject("STOP", sender, fields, payloadError)
      return
    end
    PruneAgedSessionRuntimeTracking(GetProfileCheckpointSyncTime())
    local sessionId = payload.sessionId
    local profileName = payload.profileName
    local host = payload.host
    local endedAt = payload.endedAt
    local token = payload.token
    if host == "" or not IsClaimedActorSenderMatch(sender, host) then
      return
    end
    local recentReceipt = token ~= "" and sessionRuntime.recentSessionFinalizationReceipts[token] or nil
    if type(recentReceipt) == "table"
      and TrimText(recentReceipt.sessionId) == sessionId
      and string.lower(TrimText(recentReceipt.profileName)) == string.lower(profileName)
      and AreCharacterKeysSame(recentReceipt.host, host)
    then
      sessionLifecycleOps.sendSessionFinalizationReceipt(payload, "ALREADY_APPLIED")
      recentReceipt.updatedAt = GetProfileCheckpointSyncTime()
      return
    end
    if not IsCurrentGroupCharacter(host) then
      return
    end

    local pendingInviteCleared = false
    local pendingInvite = sessionRuntime.pendingInvites[sessionId]
    if type(pendingInvite) == "table" and TrimText(pendingInvite.profileName) == profileName and AreCharacterKeysSame(pendingInvite.host, host) then
      sessionRuntime.pendingInvites[sessionId] = nil
      pendingInviteCleared = true
    end
    local pendingJoinCleared = false
    local pendingJoin = sessionRuntime.pendingJoinRequests[sessionId]
    if type(pendingJoin) == "table" and type(pendingJoin.invite) == "table"
        and TrimText(pendingJoin.invite.profileName) == profileName
        and AreCharacterKeysSame(pendingJoin.invite.host, host) then
      sessionRuntime.pendingJoinRequests[sessionId] = nil
      pendingJoinCleared = true
    end

    local activeSession, activeProfileName = GetActiveLootSession()
    if type(activeSession) ~= "table" or TrimText(activeSession.id) ~= sessionId then
      return
    end
    if not deps.IsActiveSessionHostSender(activeSession, sender) then
      return
    end

    local localProfileName = TrimText(activeProfileName) ~= "" and activeProfileName or profileName
    local stopped = FinishLootSession(localProfileName, sessionId, endedAt, "FINISHED")
    if not stopped then
      sessionUiOps.refreshPanelsAndLiveBoard()
      return
    end
    if token ~= "" then
      local receiptNow = GetProfileCheckpointSyncTime()
      sessionRuntime.recentSessionFinalizationReceipts[token] = {
        sessionId = sessionId,
        profileName = profileName,
        host = host,
        receivedAt = receiptNow,
        updatedAt = receiptNow,
      }
      sessionLifecycleOps.sendSessionFinalizationReceipt(payload, "APPLIED")
    end
    sessionLifecycleOps.finalizeEndedSessionEvent(sessionId, profileName, "remote_stopped", {
      profileName = profileName,
      sender = host ~= "" and host or NormalizeSenderKey(sender),
      activeSession = activeSession,
      endedBy = (host ~= "" and host) or NormalizeSenderKey(sender) or "Unknown",
    })
  end

  INTERNAL_API.LIDCOUNCIL_HandleStopAck_Impl = function(fields, sender)
    local payload, payloadError = profileSyncMetaOps.parseInboundStopAckPayload(fields, sender)
    if type(payload) ~= "table" then
      profileSyncMetaOps.recordInboundPayloadReject("STOP_ACK", sender, fields, payloadError)
      return
    end
    PruneAgedSessionRuntimeTracking(GetProfileCheckpointSyncTime())
    local tracker = sessionRuntime.pendingSessionFinalizations[payload.token]
    if type(tracker) ~= "table"
      or TrimText(tracker.sessionId) ~= payload.sessionId
      or string.lower(TrimText(tracker.profileName)) ~= string.lower(payload.profileName)
    then
      return
    end
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if selfKey == "" or not AreCharacterKeysSame(tracker.host, selfKey) then
      return
    end

    local trackedMemberKey = ""
    for memberKey in pairs(tracker.targets or {}) do
      if AreCharacterKeysSame(memberKey, payload.memberKey) then
        trackedMemberKey = memberKey
        break
      end
    end
    if trackedMemberKey == "" then
      return
    end

    tracker.receipts[trackedMemberKey] = {
      state = payload.receiptState,
      receivedAt = GetProfileCheckpointSyncTime(),
    }
    tracker.missing[trackedMemberKey] = nil
    if type(tracker.unresolved) == "table" then
      tracker.unresolved[trackedMemberKey] = nil
    end
    tracker.updatedAt = GetProfileCheckpointSyncTime()
    if sessionLifecycleOps.getSessionFinalizationMissingCount(tracker) == 0 then
      tracker.state = "complete"
    end
  end

  INTERNAL_API.LIDCOUNCIL_GetReadinessTransitionLog_Impl = function(memberKey, sessionId, limit)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    local resolvedSessionId = TrimText(sessionId)
    local remaining = math.max(1, math.min(80, math.floor(tonumber(limit) or 20)))
    local result = {}
    for index = #sessionRuntime.readinessTransitionLog, 1, -1 do
      local entry = sessionRuntime.readinessTransitionLog[index]
      if type(entry) == "table"
        and (resolvedMemberKey == "" or AreCharacterKeysSame(entry.memberKey, resolvedMemberKey))
        and (resolvedSessionId == "" or TrimText(entry.sessionId) == resolvedSessionId)
      then
        result[#result + 1] = {
          at = entry.at,
          sessionId = entry.sessionId,
          memberKey = entry.memberKey,
          previous = entry.previous,
          current = entry.current,
          generation = entry.generation,
          source = entry.source,
          reason = entry.reason,
        }
        remaining = remaining - 1
        if remaining <= 0 then
          break
        end
      end
    end
    return result
  end

  INTERNAL_API.LIDCOUNCIL_ValidateReadinessProofLifecycle_Impl = function()
    local readyMatrix = profileSyncMetaOps.encodeHostMemberStatusMatrix({
      p1 = "READY",
      p2 = "READY",
      lootList = "READY",
      itemHistory = "READY",
      sessionHistory = "READY",
      funAwards = "READY",
    })
    local pendingMatrix = profileSyncMetaOps.encodeHostMemberStatusMatrix({
      p1 = "READY",
      p2 = "VALIDATING",
      lootList = "READY",
      itemHistory = "PENDING",
      sessionHistory = "READY",
      funAwards = "READY",
    })
    local staleArchiveMatrix = profileSyncMetaOps.encodeHostMemberStatusMatrix({
      p1 = "READY",
      p2 = "READY",
      lootList = "READY",
      itemHistory = "READY",
      sessionHistory = "STALE",
      funAwards = "READY",
    })
    local decodedStaleArchiveMatrix = profileSyncMetaOps.decodeHostMemberStatusMatrix(staleArchiveMatrix)
    local staleAccepted, staleValue, staleGeneration = profileSyncMetaOps.resolveHostMemberStatusGeneration(
      readyMatrix,
      4,
      pendingMatrix,
      3,
      true
    )
    local sameGenerationAccepted = profileSyncMetaOps.resolveHostMemberStatusGeneration(
      readyMatrix,
      4,
      pendingMatrix,
      4,
      true
    )
    local newerAccepted, newerValue, newerGeneration = profileSyncMetaOps.resolveHostMemberStatusGeneration(
      readyMatrix,
      4,
      pendingMatrix,
      5,
      true
    )
    local legacyAccepted = profileSyncMetaOps.resolveHostMemberStatusGeneration(
      readyMatrix,
      4,
      pendingMatrix,
      0,
      true
    )
    local unchangedAccepted, unchangedValue, unchangedGeneration = profileSyncMetaOps.resolveHostMemberStatusGeneration(
      readyMatrix,
      4,
      readyMatrix,
      nil,
      false
    )
    local previousStatusSessionId = sessionRuntime.hostMemberSyncStatusSessionId
    local previousStatusByKey = sessionRuntime.hostMemberSyncStatusByKey
    local previousStatusGenerationByKey = sessionRuntime.hostMemberSyncStatusGenerationByKey
    local previousProofByKey = sessionRuntime.hostMemberReadinessProofByKey
    local previousProofGenerationByKey = sessionRuntime.hostMemberReadinessProofGenerationByKey
    local proofMember = {
      name = "ReadinessProof-ValidationRealm",
      sessionChecksum = "proof-a",
      itemHistoryArchiveChecksum = "archive-a",
    }
    local proofSessionId = "SESSION-READINESS-PROOF-VALIDATION"
    profileSyncMetaOps.rememberHostMemberReadinessProof(
      proofMember,
      proofSessionId,
      proofMember.name,
      "validation"
    )
    proofMember.sessionChecksum = "proof-b"
    proofMember.itemHistoryArchiveChecksum = "archive-b"
    local immutableProof = profileSyncMetaOps.getHostMemberReadinessProof(
      proofMember,
      proofSessionId,
      proofMember.name
    )
    local crossLobbyProof = profileSyncMetaOps.getHostMemberReadinessProof(
      proofMember,
      proofSessionId .. "-NEXT",
      proofMember.name
    )
    sessionRuntime.hostMemberSyncStatusSessionId = previousStatusSessionId
    sessionRuntime.hostMemberSyncStatusByKey = previousStatusByKey
    sessionRuntime.hostMemberSyncStatusGenerationByKey = previousStatusGenerationByKey
    sessionRuntime.hostMemberReadinessProofByKey = previousProofByKey
    sessionRuntime.hostMemberReadinessProofGenerationByKey = previousProofGenerationByKey
    return {
      staleGenerationRejected = staleAccepted == false
        and staleValue == readyMatrix
        and staleGeneration == 4,
      equalGenerationRewriteRejected = sameGenerationAccepted == false,
      newerGenerationAccepted = newerAccepted == true
        and newerValue == pendingMatrix
        and newerGeneration == 5,
      generatedMatrixIsMonotonic = unchangedAccepted == true
        and unchangedValue == readyMatrix
        and unchangedGeneration == 4,
      legacyMatrixCannotReplaceGeneratedState = legacyAccepted == false,
      staleArchiveMatrixRoundTrips = type(decodedStaleArchiveMatrix) == "table"
        and decodedStaleArchiveMatrix.sessionHistory == "STALE"
        and decodedStaleArchiveMatrix.p3 == "STALE",
      acceptedProofIsImmutable = type(immutableProof) == "table"
        and immutableProof.sessionChecksum == "proof-a"
        and immutableProof.itemHistoryArchiveChecksum == "archive-a",
      newLobbyDoesNotReuseProof = crossLobbyProof == nil,
      missingProofState = crossLobbyProof == nil and "VALIDATING" or "READY",
    }
  end

  if type(INTERNAL_API.LIDCOUNCIL_RegisterCombatSyncInboxApplier_Impl) ~= "function"
    or not INTERNAL_API.LIDCOUNCIL_RegisterCombatSyncInboxApplier_Impl(
      "PDELTA",
      "session_flow",
      profileSyncMetaOps.applyCombatStagedProfileDelta
    )
    or not INTERNAL_API.LIDCOUNCIL_RegisterCombatSyncInboxApplier_Impl(
      "PDELTA_REQ",
      "session_flow",
      profileSyncMetaOps.applyCombatStagedProfileDelta
    )
  then
    error("LidCouncil missing profile delta combat inbox registration.")
  end

  return {
    EnsureSessionPopup = INTERNAL_API.LIDCOUNCIL_EnsureSessionPopup_Impl,
    HandleOutboundJoinSent = sessionLifecycleOps.handleOutboundJoinSent,
    HasJoinedActiveLootSession = INTERNAL_API.LIDCOUNCIL_HasJoinedActiveLootSession_Impl,
    StartLootSessionFlow = INTERNAL_API.LIDCOUNCIL_StartLootSessionFlow_Impl,
    ActivatePreparedLootSessionFlow = INTERNAL_API.LIDCOUNCIL_ActivatePreparedLootSessionFlow_Impl,
    SendActiveSessionInviteFlow = INTERNAL_API.LIDCOUNCIL_SendActiveSessionInviteFlow_Impl,
    PushActiveProfileSnapshotFlow = INTERNAL_API.LIDCOUNCIL_PushActiveProfileSnapshotFlow_Impl,
    PushProfileHostOverrideFlow = INTERNAL_API.LIDCOUNCIL_PushProfileHostOverrideFlow_Impl,
    BroadcastActiveProfileSnapshotFlow = INTERNAL_API.LIDCOUNCIL_BroadcastActiveProfileSnapshotFlow_Impl,
    BroadcastActiveProfileDeltaFlow = INTERNAL_API.LIDCOUNCIL_BroadcastActiveProfileDeltaFlow_Impl,
    QueueActiveProfileCheckpointFlow = INTERNAL_API.LIDCOUNCIL_QueueActiveProfileCheckpointFlow_Impl,
    BroadcastMember = BroadcastMember,
    RefreshHostSessionMemberState = RefreshHostSessionMemberState,
    RequestActiveProfileSubchecksumFlow = INTERNAL_API.LIDCOUNCIL_RequestActiveProfileSubchecksumFlow_Impl,
    RefreshActiveSessionReadinessFlow = INTERNAL_API.LIDCOUNCIL_RefreshActiveSessionReadinessFlow_Impl,
    RequestActiveProfileSnapshotFlow = INTERNAL_API.LIDCOUNCIL_RequestActiveProfileSnapshotFlow_Impl,
    StopLootSessionFlow = INTERNAL_API.LIDCOUNCIL_StopLootSessionFlow_Impl,
    LeaveActiveSessionFlow = INTERNAL_API.LIDCOUNCIL_LeaveActiveSessionFlow_Impl,
    RemoveActiveSessionMemberFlow = INTERNAL_API.LIDCOUNCIL_RemoveActiveSessionMemberFlow_Impl,
    HandleGroupRosterChanged = INTERNAL_API.LIDCOUNCIL_HandleGroupRosterChanged_Impl,
    NotifyLocalAutoPassChanged = INTERNAL_API.LIDCOUNCIL_NotifyLocalAutoPassChanged_Impl,
    BroadcastActiveSessionRoleUpdate = INTERNAL_API.LIDCOUNCIL_BroadcastActiveSessionRoleUpdate_Impl,
    HandleStartInvite = INTERNAL_API.LIDCOUNCIL_HandleStartInvite_Impl,
    HandleInviteAck = INTERNAL_API.LIDCOUNCIL_HandleInviteAck_Impl,
    GetInviteDeliveryStatus = sessionLifecycleOps.getInviteDeliveryStatus,
    HandleOutboundStartSent = sessionLifecycleOps.handleOutboundStartSent,
    GetAcceptedJoinBurstStatus = sessionLifecycleOps.getAcceptedJoinBurstStatus,
    HandleBegin = INTERNAL_API.LIDCOUNCIL_HandleBegin_Impl,
    HandleJoin = INTERNAL_API.LIDCOUNCIL_HandleJoin_Impl,
    HandleJoinAck = INTERNAL_API.LIDCOUNCIL_HandleJoinAck_Impl,
    HandleMember = INTERNAL_API.LIDCOUNCIL_HandleMember_Impl,
    HandleLocalAutoPass = INTERNAL_API.LIDCOUNCIL_HandleLocalAutoPass_Impl,
    HandleAutoPassNotice = INTERNAL_API.LIDCOUNCIL_HandleAutoPassNotice_Impl,
    HandleDecline = INTERNAL_API.LIDCOUNCIL_HandleDecline_Impl,
    HandleLeave = INTERNAL_API.LIDCOUNCIL_HandleLeave_Impl,
    HandleProfileState = INTERNAL_API.LIDCOUNCIL_HandleProfileState_Impl,
    HandleProfileStatePart = INTERNAL_API.LIDCOUNCIL_HandleProfileStatePart_Impl,
    HandleProfileDeltaRequest = INTERNAL_API.LIDCOUNCIL_HandleProfileDeltaRequest_Impl,
    HandleProfileDelta = INTERNAL_API.LIDCOUNCIL_HandleProfileDelta_Impl,
    HandleProfileDeltaAck = INTERNAL_API.LIDCOUNCIL_HandleProfileDeltaAck_Impl,
    HandleProfileDeltaNack = INTERNAL_API.LIDCOUNCIL_HandleProfileDeltaNack_Impl,
    ShouldPublishProfileDeltaStateProof = INTERNAL_API.LIDCOUNCIL_ShouldPublishProfileDeltaStateProof_Impl,
    GetProfileDeltaAckStatus = profileSyncMetaOps.getProfileDeltaAckStatus,
    GetUndispatchedAckTimeoutRevalidationDomains = profileSyncMetaOps.getUndispatchedAckTimeoutRevalidationDomains,
    ShouldScheduleAckTimeoutRevalidationRecovery = profileSyncMetaOps.shouldScheduleAckTimeoutRevalidationRecovery,
    GetAckTimeoutRevalidationStats = profileSyncMetaOps.getAckTimeoutRevalidationStats,
    ReconcileOutboundProfileAckTimeout = profileSyncMetaOps.reconcileOutboundProfileAckTimeout,
    HandleStop = INTERNAL_API.LIDCOUNCIL_HandleStop_Impl,
    HandleStopAck = INTERNAL_API.LIDCOUNCIL_HandleStopAck_Impl,
  }
end
