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

INTERNAL_API.LIDCOUNCIL_ProjectPreciseRequestState_Impl = function(candidate, requestState)
  candidate = type(candidate) == "table" and candidate or {}
  requestState = type(requestState) == "table" and requestState or {}

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

  candidate.preciseRequestState = clean(requestState.status)
  candidate.preciseRequestError = clean(requestState.error)
  candidate.preciseRequestToken = clean(requestState.requestToken)
  candidate.preciseRequestedDomainCount = math.max(0, tonumber(requestState.requestedCount) or 0)
  candidate.preciseReceivedDomainCount = math.max(0, tonumber(requestState.receivedCount) or 0)
  candidate.preciseResponseComplete = requestState.complete == true
  candidate.preciseResponseReceived = requestState.complete == true
  candidate.preciseRequestDeadlineAt = math.max(0, tonumber(requestState.deadlineAt) or 0)
  candidate.preciseLastProgressAt = math.max(0, tonumber(requestState.lastProgressAt) or 0)
  return candidate
end

INTERNAL_API.LIDCOUNCIL_AdvancePreciseRequestProgress_Impl = function(
  requestState,
  requestToken,
  now,
  stallTimeoutSeconds
)
  if type(requestState) ~= "table" 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(requestState.requestToken)
  local receivedToken = clean(requestToken)
  if expectedToken ~= "" and receivedToken ~= expectedToken then
    return false
  end

  local currentTime = math.max(0, tonumber(now) or 0)
  local stallTimeout = math.max(1, tonumber(stallTimeoutSeconds) or 1)
  requestState.lastProgressAt = currentTime
  requestState.updatedAt = currentTime
  requestState.deadlineAt = math.max(
    math.max(0, tonumber(requestState.deadlineAt) or 0),
    currentTime + stallTimeout
  )
  if string.lower(clean(requestState.status)) == "failed"
    and clean(requestState.error) == "response_timeout"
  then
    requestState.status = "waiting"
    requestState.error = ""
  end
  return true
end

INTERNAL_API.LIDCOUNCIL_RecordPreciseMultipartPart_Impl = function(bucket, partIndex, partTotal, payload)
  if type(bucket) ~= "table" then
    return false, false
  end
  partIndex = math.max(1, tonumber(partIndex) or 1)
  partTotal = math.max(partIndex, tonumber(partTotal) or 1)
  bucket.parts = type(bucket.parts) == "table" and bucket.parts or {}
  bucket.receivedCount = math.max(0, tonumber(bucket.receivedCount) or 0)
  local firstReceipt = bucket.parts[partIndex] == nil
  if firstReceipt then
    bucket.receivedCount = bucket.receivedCount + 1
  end
  bucket.parts[partIndex] = tostring(payload or "")
  return bucket.receivedCount >= partTotal, firstReceipt
end

INTERNAL_API.LIDCOUNCIL_ShouldSuppressPreciseResponse_Impl = function(recentState, signature, requestToken, now, dedupeSeconds)
  if type(recentState) ~= "table" then
    return false
  end
  local resolvedSignature = tostring(signature or "")
  local resolvedRequestToken = tostring(requestToken or "")
  local recentSignature = tostring(recentState.signature or "")
  local recentRequestToken = tostring(recentState.requestToken or "")
  local recentSentAt = math.max(0, tonumber(recentState.sentAt) or 0)
  local currentTime = math.max(0, tonumber(now) or 0)
  local dedupeWindow = math.max(0, tonumber(dedupeSeconds) or 0)
  return resolvedSignature ~= ""
    and recentSignature == resolvedSignature
    and recentRequestToken == resolvedRequestToken
    and (currentTime - recentSentAt) < dedupeWindow
end

INTERNAL_API.LIDCOUNCIL_ResolvePreciseResponseToken_Impl = function(
  recentState,
  signature,
  requestToken,
  scope,
  fallbackToken
)
  local resolvedFallback = tostring(fallbackToken or "")
  if type(recentState) ~= "table"
    or tostring(recentState.signature or "") ~= tostring(signature or "")
    or tostring(recentState.requestToken or "") ~= tostring(requestToken or "")
  then
    return resolvedFallback, false
  end

  local resolvedScope = tostring(scope or "")
  local responseToken = ""
  if resolvedScope ~= "" and type(recentState.responseTokens) == "table" then
    responseToken = tostring(recentState.responseTokens[resolvedScope] or "")
  end
  if responseToken == "" then
    responseToken = tostring(recentState.responseToken or "")
  end
  if responseToken == "" then
    return resolvedFallback, false
  end
  return responseToken, true
end

INTERNAL_API.LIDCOUNCIL_ShouldSuppressLocalProfileStateSend_Impl = function(
  recentState,
  signature,
  now,
  dedupeSeconds,
  force
)
  if force == true or type(recentState) ~= "table" then
    return false
  end
  local resolvedSignature = tostring(signature or "")
  local recentSignature = tostring(recentState.signature or "")
  local recentSentAt = math.max(0, tonumber(recentState.sentAt) or 0)
  local currentTime = math.max(0, tonumber(now) or 0)
  local dedupeWindow = math.max(0, tonumber(dedupeSeconds) or 0)
  return resolvedSignature ~= ""
    and recentSignature == resolvedSignature
    and (currentTime - recentSentAt) < dedupeWindow
end

INTERNAL_API.LIDCOUNCIL_ClearIncomingProfileSyncsForSession_Impl = function(pendingSyncs, sessionId, normalizeText)
  if type(pendingSyncs) ~= "table" then
    return 0
  end
  local normalize = type(normalizeText) == "function" and normalizeText or function(value)
    return tostring(value or "")
  end
  local resolvedSessionId = normalize(sessionId)
  if resolvedSessionId == "" then
    return 0
  end
  local removed = 0
  for transferId, syncState in pairs(pendingSyncs) do
    if type(syncState) == "table" and normalize(syncState.sessionId) == resolvedSessionId then
      pendingSyncs[transferId] = nil
      removed = removed + 1
    end
  end
  return removed
end

INTERNAL_API.LIDCOUNCIL_ResolveIncomingProfileSyncTransfer_Impl = function(pendingSyncs, transferId, senderKey, normalizeText)
  if type(pendingSyncs) ~= "table" then
    return nil, "missing_transfer"
  end
  local normalize = type(normalizeText) == "function" and normalizeText or function(value)
    return tostring(value or "")
  end
  local resolvedTransferId = normalize(transferId)
  local syncState = resolvedTransferId ~= "" and pendingSyncs[resolvedTransferId] or nil
  if type(syncState) ~= "table" then
    return nil, "missing_transfer"
  end
  if senderKey ~= normalize(syncState.sender) then
    return nil, "sender_mismatch"
  end
  return syncState, "matched"
end

INTERNAL_API.LIDCOUNCIL_CopyProfileSyncArchivePreviewMetadata_Impl = function(target, source, normalizeText)
  if type(target) ~= "table" then
    return target
  end
  local normalize = type(normalizeText) == "function" and normalizeText or function(value)
    return tostring(value or "")
  end
  local scope = string.upper(normalize(type(source) == "table" and source.authoritativeArchiveScope or ""))
  if scope ~= "LOOT_LIST" and scope ~= "SESSION_HISTORY" and scope ~= "FUN_AWARDS" then
    scope = ""
  end
  target.authoritativeArchiveScope = scope
  return target
end

INTERNAL_API.LIDCOUNCIL_ApplyIncomingProfileSyncChunk_Impl = function(syncState, chunkIndex, chunkData, maxChunkBytes, maxTransferBytes, updatedAt)
  if type(syncState) ~= "table" then
    return false, "profile_sync_transfer_missing"
  end
  local resolvedChunkIndex = math.max(0, math.floor(tonumber(chunkIndex) or 0))
  local resolvedChunkCount = math.max(0, tonumber(syncState.chunkCount) or 0)
  if resolvedChunkIndex > resolvedChunkCount then
    return false, "profile_sync_chunk_index_exceeds_declared_count"
  end
  local resolvedChunkData = type(chunkData) == "string" and chunkData or tostring(chunkData or "")
  if #resolvedChunkData > math.max(1, tonumber(maxChunkBytes) or 1) then
    return false, "profile_sync_chunk_bytes_exceed_limit"
  end
  syncState.chunks = type(syncState.chunks) == "table" and syncState.chunks or {}
  local previousChunk = syncState.chunks[resolvedChunkIndex]
  local previousBytes = type(previousChunk) == "string" and #previousChunk or 0
  local receivedBytes = math.max(0, tonumber(syncState.receivedBytes) or 0) - previousBytes + #resolvedChunkData
  if receivedBytes > math.max(1, tonumber(maxTransferBytes) or 1) then
    return false, "profile_sync_transfer_bytes_exceed_limit"
  end
  syncState.chunks[resolvedChunkIndex] = resolvedChunkData
  syncState.receivedBytes = receivedBytes
  if type(previousChunk) ~= "string" then
    syncState.receivedChunkCount = math.max(0, tonumber(syncState.receivedChunkCount) or 0) + 1
  end
  syncState.updatedAt = math.max(0, tonumber(updatedAt) or 0)
  return true, "accepted"
end

INTERNAL_API.LIDCOUNCIL_BeginIncomingSnapshotDiagnosticsForSession_Impl = function(sessionState, sessionId, startedAt, normalizeText)
  if type(sessionState) ~= "table" then
    return false
  end
  local normalize = type(normalizeText) == "function" and normalizeText or function(value)
    return tostring(value or "")
  end
  local resolvedSessionId = normalize(sessionId)
  if resolvedSessionId == "" or normalize(sessionState.incomingSnapshotDiagnosticsSessionId) == resolvedSessionId then
    return false
  end

  sessionState.incomingSnapshotDiagnosticsSessionId = resolvedSessionId
  sessionState.incomingSnapshotDiagnosticsStartedAt = math.max(0, tonumber(startedAt) or 0)
  sessionState.incomingSnapshotRejectTotal = 0
  sessionState.lastIncomingSnapshotRejectOpcode = ""
  sessionState.lastIncomingSnapshotRejectReason = ""
  sessionState.lastIncomingSnapshotRejectSender = ""
  sessionState.lastIncomingSnapshotRejectTransferId = ""
  sessionState.lastIncomingSnapshotRejectSessionId = ""
  sessionState.lastIncomingSnapshotRejectAt = 0
  sessionState.incomingSnapshotRejectCounts = {}
  sessionState.incomingSnapshotRejectHistory = {}
  return true
end

INTERNAL_API.LIDCOUNCIL_RecordIncomingSnapshotReject_Impl = function(sessionState, opcode, sender, fields, reason, recordedAt, normalizeText, knownSessionId)
  if type(sessionState) ~= "table" then
    return false
  end
  local normalize = type(normalizeText) == "function" and normalizeText or function(value)
    return tostring(value or "")
  end
  local resolvedOpcode = normalize(opcode)
  if resolvedOpcode ~= "PSYNC_START" and resolvedOpcode ~= "PSYNC_CHUNK" and resolvedOpcode ~= "PSYNC_END" then
    return false
  end

  local resolvedReason = normalize(reason)
  if resolvedReason == "" then
    resolvedReason = "unknown_snapshot_reject"
  end
  local resolvedFields = type(fields) == "table" and fields or {}
  local resolvedTransferId = normalize(resolvedFields[2])
  local resolvedSessionId = resolvedOpcode == "PSYNC_START" and normalize(resolvedFields[3]) or normalize(knownSessionId)
  local resolvedSender = normalize(sender)
  local resolvedAt = math.max(0, tonumber(recordedAt) or 0)

  sessionState.incomingSnapshotRejectTotal = math.max(0, tonumber(sessionState.incomingSnapshotRejectTotal) or 0) + 1
  sessionState.lastIncomingSnapshotRejectOpcode = resolvedOpcode
  sessionState.lastIncomingSnapshotRejectReason = resolvedReason
  sessionState.lastIncomingSnapshotRejectSender = resolvedSender
  sessionState.lastIncomingSnapshotRejectTransferId = resolvedTransferId
  sessionState.lastIncomingSnapshotRejectSessionId = resolvedSessionId
  sessionState.lastIncomingSnapshotRejectAt = resolvedAt

  local reasonCounts = type(sessionState.incomingSnapshotRejectCounts) == "table"
    and sessionState.incomingSnapshotRejectCounts or {}
  sessionState.incomingSnapshotRejectCounts = reasonCounts
  if reasonCounts[resolvedReason] ~= nil or resolvedReason == "other" then
    reasonCounts[resolvedReason] = math.max(0, tonumber(reasonCounts[resolvedReason]) or 0) + 1
  else
    local namedReasonCount = 0
    for reasonName in pairs(reasonCounts) do
      if reasonName ~= "other" then
        namedReasonCount = namedReasonCount + 1
      end
    end
    if namedReasonCount >= math.max(1, tonumber(sessionState.maxIncomingSnapshotRejectReasons) or 8) then
      reasonCounts.other = math.max(0, tonumber(reasonCounts.other) or 0) + 1
    else
      reasonCounts[resolvedReason] = 1
    end
  end

  local retainedHistory = {}
  for _, entry in ipairs(type(sessionState.incomingSnapshotRejectHistory) == "table"
    and sessionState.incomingSnapshotRejectHistory or {}) do
    if type(entry) == "table" and not (
      normalize(entry.opcode) == resolvedOpcode
      and normalize(entry.reason) == resolvedReason
      and normalize(entry.sender) == resolvedSender
      and normalize(entry.transferId) == resolvedTransferId
      and normalize(entry.sessionId) == resolvedSessionId
    ) then
      retainedHistory[#retainedHistory + 1] = entry
    end
  end
  table.insert(retainedHistory, 1, {
    opcode = resolvedOpcode,
    reason = resolvedReason,
    sender = resolvedSender,
    transferId = resolvedTransferId,
    sessionId = resolvedSessionId,
    at = resolvedAt,
  })
  while #retainedHistory > math.max(1, tonumber(sessionState.maxIncomingSnapshotRejectHistory) or 8) do
    table.remove(retainedHistory)
  end
  sessionState.incomingSnapshotRejectHistory = retainedHistory
  return true
end

INTERNAL_API.LIDCOUNCIL_FinalizeIncomingProfileSyncSessionState_Impl = function(sessionState, sessionId, cleanupAt, normalizeText)
  if type(sessionState) ~= "table" then
    return 0
  end
  local normalize = type(normalizeText) == "function" and normalizeText or function(value)
    return tostring(value or "")
  end
  local resolvedSessionId = normalize(sessionId)
  if resolvedSessionId == "" then
    return 0
  end
  local removed = INTERNAL_API.LIDCOUNCIL_ClearIncomingProfileSyncsForSession_Impl(
    sessionState.pendingProfileSyncs,
    resolvedSessionId,
    normalize
  )
  if removed <= 0 then
    return 0
  end

  sessionState.incomingSnapshotCleanupTotal = math.max(0, tonumber(sessionState.incomingSnapshotCleanupTotal) or 0) + removed
  sessionState.lastIncomingSnapshotCleanupCount = removed
  sessionState.lastIncomingSnapshotCleanupSessionId = resolvedSessionId
  sessionState.lastIncomingSnapshotCleanupAt = math.max(0, tonumber(cleanupAt) or 0)

  local retainedHistory = {}
  for _, cleanup in ipairs(type(sessionState.incomingSnapshotCleanupHistory) == "table"
    and sessionState.incomingSnapshotCleanupHistory or {}) do
    if type(cleanup) == "table" and normalize(cleanup.sessionId) ~= resolvedSessionId then
      retainedHistory[#retainedHistory + 1] = cleanup
    end
  end
  table.insert(retainedHistory, 1, {
    sessionId = resolvedSessionId,
    count = removed,
    at = sessionState.lastIncomingSnapshotCleanupAt,
  })
  while #retainedHistory > math.max(1, tonumber(sessionState.maxIncomingSnapshotCleanupHistory) or 8) do
    table.remove(retainedHistory)
  end
  sessionState.incomingSnapshotCleanupHistory = retainedHistory
  return removed
end

INTERNAL_API.LIDCOUNCIL_GetIncomingProfileSyncHealth_Impl = function(pendingCount, longestIdleSeconds, stallSeconds)
  local resolvedPendingCount = math.max(0, tonumber(pendingCount) or 0)
  if resolvedPendingCount <= 0 then
    return "idle"
  end
  local resolvedStallSeconds = math.max(1, tonumber(stallSeconds) or 30)
  if math.max(0, tonumber(longestIdleSeconds) or 0) >= resolvedStallSeconds then
    return "stalled"
  end
  return "receiving"
end

INTERNAL_API.LIDCOUNCIL_ResolvePreciseRequestLifecycle_Impl = function(requestState, currentTime)
  if type(requestState) ~= "table" then
    return {
      status = "idle",
      requestedCount = 0,
      receivedCount = 0,
      complete = false,
      waiting = false,
      failed = false,
      error = "",
    }
  end

  local status = string.lower(tostring(requestState.status or "waiting"))
  local requestedCount = 0
  local receivedCount = 0
  local receivedDomains = type(requestState.receivedDomains) == "table" and requestState.receivedDomains or {}
  for _, domain in ipairs(type(requestState.domains) == "table" and requestState.domains or {}) do
    requestedCount = requestedCount + 1
    if receivedDomains[string.lower(tostring(domain or ""))] == true then
      receivedCount = receivedCount + 1
    end
  end
  if status == "waiting" and requestedCount > 0 and receivedCount >= requestedCount then
    status = "complete"
  elseif status == "waiting" then
    local deadlineAt = math.max(0, tonumber(requestState.deadlineAt) or 0)
    if deadlineAt > 0 and math.max(0, tonumber(currentTime) or 0) >= deadlineAt then
      status = "failed"
    end
  end
  local errorText = tostring(requestState.error or "")
  if status == "failed" and errorText == "" then
    errorText = "response_timeout"
  end
  return {
    status = status,
    requestedCount = requestedCount,
    receivedCount = receivedCount,
    complete = status == "complete",
    waiting = status == "waiting",
    failed = status == "failed",
    error = errorText,
  }
end

INTERNAL_API.LIDCOUNCIL_CreateLootSessionProfileSyncHelpers_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 CloneProfileSyncDomainList = deps.CloneProfileSyncDomainList
  local RecordProfileSyncDecision = deps.RecordProfileSyncDecision
  local SetProfileSyncRuntimeState = deps.SetProfileSyncRuntimeState
  local profileSyncRuntimeState = deps.profileSyncRuntimeState or {}
  local PROFILE_REVISION_DOMAINS = deps.PROFILE_REVISION_DOMAINS or {}
  local PROFILE_REVISION_DOMAIN_LABELS = deps.PROFILE_REVISION_DOMAIN_LABELS or {}
  local GetCharacterKey = deps.GetCharacterKey
  local GetActiveLootSession = deps.GetActiveLootSession
  local GetLootProfileId = deps.GetLootProfileId
  local GetLootProfileRevisionSummary = deps.GetLootProfileRevisionSummary
  local CalculateStableChecksum = deps.CalculateStableChecksum
  local GetLootProfileSubchecksumManifest = deps.GetLootProfileSubchecksumManifest
  local NormalizeLootProfileSubdomainList = deps.NormalizeLootProfileSubdomainList
  local CloneLootProfileSubdomainList = deps.CloneLootProfileSubdomainList
  local FilterLootProfilePatchCapableSubdomains = deps.FilterLootProfilePatchCapableSubdomains
  local GetLootProfileSubdomainLabel = deps.GetLootProfileSubdomainLabel
  local GetLootProfileSubdomainParentDomain = deps.GetLootProfileSubdomainParentDomain
  local ResolveLootProfileDomainsForSubdomains = deps.ResolveLootProfileDomainsForSubdomains
  local SendComm = deps.SendComm
  local sessionRuntimeOps = {
    buildProtocolMarker = deps.BuildCommProtocolMarker,
    markTransferAcked = deps.MarkOutboundProfileTransferAcked,
    markTransferQueued = deps.MarkOutboundProfileTransferQueued,
    annotateTransfer = deps.AnnotateOutboundProfileTransfer,
    cancelQueuedProfileTransfersForScope = deps.CancelQueuedProfileTransfersForScope,
    isHostSender = deps.IsActiveSessionHostSender,
    isJoinedCharacter = deps.IsJoinedSessionCharacter,
    isCurrentGroupCharacter = deps.IsCurrentGroupCharacter,
    doesSessionMatch = deps.DoesActiveSessionMatch,
    refreshEditor = deps.RefreshEditor,
    requestSessionEditorRefresh = deps.RequestSessionEditorRefresh,
    refreshCurrentAndSyncSections = deps.RefreshEditorForCurrentAndSyncSections,
    refreshSyncManagementSection = deps.RefreshEditorForSyncManagementSection,
    getProfile = deps.GetLootProfile,
    recordInboundReject = deps.RecordInboundCommReject,
    splitProfileSnapshotPayload = deps.SplitProfileSnapshotPayload,
    validateProfileSnapshotStartPayload = deps.ValidateProfileSnapshotStartPayload,
    validateCommPayload = deps.ValidateCommPayload,
    splitCommPayloadField = deps.SplitCommPayloadField,
    buildPayload = deps.BuildPayload,
    recordOutboundPayloadReject = deps.RecordOutboundPayloadReject,
    previewOutboundProfileTransferGeneration = deps.PreviewOutboundProfileTransferGeneration,
    getCommOutboundQueueStatus = deps.GetCommOutboundQueueStatus,
  }
  local snapshotTransferOps = {
    exportDomain = deps.ExportLootProfileDomainSnapshot,
    exportSubdomain = deps.ExportLootProfileSubdomainSnapshot,
    exportPatch = deps.ExportLootProfileSubdomainPatch,
    exportRowPatch = deps.ExportLootProfileConflictRowPatch,
    exportPatchManifest = deps.ExportLootProfileSubdomainPatchManifest,
    importDomain = deps.ImportLootProfileDomainSnapshot,
    importSubdomain = deps.ImportLootProfileSubdomainSnapshot,
    importPatch = deps.ImportLootProfileSubdomainPatch,
    importRowPatch = deps.ImportLootProfileConflictRowPatch,
    previewDomain = deps.PreviewLootProfileDomainSnapshot,
    previewSubdomain = deps.PreviewLootProfileSubdomainSnapshot,
    previewPatch = deps.PreviewLootProfileSubdomainPatch,
    previewRowPatch = deps.PreviewLootProfileConflictRowPatch,
    previewPatchManifest = deps.PreviewLootProfileSubdomainPatchManifest,
  }

  local profileSyncSessionState = {
    pendingProfileSyncs = {},
    appliedSnapshotGenerationByStream = {},
    pendingSnapshotBatch = {},
    snapshotBatchJoinHoldUntilBySession = {},
    snapshotBatchJoinHoldReasonBySession = {},
    snapshotBatchPreferredSessionId = "",
    snapshotBatchRunning = false,
    snapshotBatchTimerToken = 0,
    snapshotAdmissionHoldReason = "",
    snapshotAdmissionHoldCount = 0,
    snapshotAdmissionHoldAt = 0,
    archiveInFlightCoalescedTotal = 0,
    lastArchiveInFlightCoalescedAt = 0,
    lastArchiveInFlightCoalescedTarget = "",
    archivePreparationCoalescedTotal = 0,
    archivePreparationPrunedTotal = 0,
    lastArchivePreparationCoalescedAt = 0,
    lastArchivePreparationCoalescedTarget = "",
    preparedSnapshotCacheHits = 0,
    preparedSnapshotCacheMisses = 0,
    incomingSnapshotCleanupTotal = 0,
    lastIncomingSnapshotCleanupCount = 0,
    lastIncomingSnapshotCleanupSessionId = "",
    lastIncomingSnapshotCleanupAt = 0,
    incomingSnapshotCleanupHistory = {},
    maxIncomingSnapshotCleanupHistory = 8,
    incomingSnapshotDiagnosticsSessionId = "",
    incomingSnapshotDiagnosticsStartedAt = 0,
    incomingSnapshotRejectTotal = 0,
    lastIncomingSnapshotRejectOpcode = "",
    lastIncomingSnapshotRejectReason = "",
    lastIncomingSnapshotRejectSender = "",
    lastIncomingSnapshotRejectTransferId = "",
    lastIncomingSnapshotRejectSessionId = "",
    lastIncomingSnapshotRejectAt = 0,
    incomingSnapshotRejectCounts = {},
    incomingSnapshotRejectHistory = {},
    maxIncomingSnapshotRejectHistory = 8,
    maxIncomingSnapshotRejectReasons = 8,
  }
  local profileSyncLocalOps = {}
  profileSyncLocalOps.isActiveHostAuthoritativeOverride = function(syncState, activeSession, sender)
    return type(syncState) == "table"
      and syncState.hostAuthoritativeOverride == true
      and type(sessionRuntimeOps.isHostSender) == "function"
      and sessionRuntimeOps.isHostSender(activeSession, sender) == true
  end
  INTERNAL_API.LIDCOUNCIL_IsActiveHostAuthoritativeProfileOverride_Impl =
    profileSyncLocalOps.isActiveHostAuthoritativeOverride
  profileSyncLocalOps.beginPerformanceSample = function(metricName, sampleEvery)
    if type(deps.BeginSyncPerformanceSample) ~= "function" then
      return nil
    end
    return deps.BeginSyncPerformanceSample(metricName, sampleEvery)
  end
  profileSyncLocalOps.recordPerformance = function(metricName, startedAt, metadata)
    if type(deps.RecordSyncPerformance) ~= "function" then
      return false
    end
    return deps.RecordSyncPerformance(metricName, startedAt, metadata)
  end
  local profileSyncCaches = {
    memberSubchecksumBySession = {},
    lootListDifferenceDiagnosticsBySession = {},
    itemHistoryDifferenceDiagnosticsBySession = {},
    sessionHistoryDifferenceDiagnosticsBySession = {},
    pendingMemberSubchecksumPartsBySession = {},
    pendingSubchecksumRequests = {},
    memberPatchManifestBySession = {},
    pendingMemberPatchManifestPartsBySession = {},
    pendingPatchManifestRequests = {},
    pendingAutoPatchManifestTimers = {},
    recentPatchManifestRequests = {},
    patchManifestRequestTokensByStamp = {},
    recentSubchecksumRequests = {},
    preciseSubchecksumRequestStateByMember = {},
    preciseResponseTokens = {},
    preciseResponseDrops = {},
    recentLocalProfileStateSends = {},
    delayedLocalProfileStateSendTokens = {},
    profileStateMultipartSequence = 0,
    preparedArchiveRepairs = {},
    preparedSnapshots = {},
    optionalApiFunctions = {},
    optionalApiFailureSignatures = {},
    optionalApiUnavailable = {},
    lastPreciseMultipartPruneAt = 0,
  }
  local profileSyncResponseRuntime = {
    precise = {
      pendingSubchecksum = {},
      pendingPatchManifest = {},
      recentSubchecksum = {},
      recentPatchManifest = {},
      timerToken = 0,
    },
    requested = {
      pending = {},
      recent = {},
    },
    inboundRequestWindows = {},
  }
  local profileSyncConfig = {
    -- PSYNC_START can safely advertise a wider scope than PSUB_STATE can carry.
    subcheckChunkLimit = 80,
    -- Keep precise-state responses below the transport ceiling before their final
    -- multipart envelope is built.  This leaves room for long character/profile
    -- identifiers and prevents archive-history checks from being rejected later.
    subcheckStateChunkLimit = 40,
    subcheckStatePayloadTargetBytes = 220,
    subcheckRequestCoalesceDelaySeconds = 0.05,
    subcheckRequestDedupeSeconds = 6,
    patchManifestRequestLimit = 120,
    patchManifestRequestCoalesceDelaySeconds = 0.05,
    patchManifestDedupeSeconds = 8,
    autoPatchManifestDelaySeconds = 0.25,
    localProfileStateDedupeSeconds = 1.0,
    localProfileStateRetentionSeconds = 20,
    profileStatePartChunkBytes = 120,
    profileStatePartPayloadTargetBytes = 220,
    maxProfileStateParts = 16,
    previewConflictTtlSeconds = 120,
    generationConvergenceTtlSeconds = 8,
    preciseMemberStateTtlSeconds = 45,
    preciseRequestTimeoutSeconds = 30,
    preciseRequestProgressTimeoutSeconds = 20,
    preciseRequestStateRetentionSeconds = 60,
    maxIncomingSnapshotChunks = 4096,
    maxIncomingSnapshotChunkBytes = 240,
    maxIncomingSnapshotBytes = 524288,
    incomingSnapshotTransferTtlSeconds = 180,
    incomingSnapshotStallSeconds = 30,
    maxPendingIncomingSnapshotTransfers = 24,
    maxPendingIncomingSnapshotTransfersPerSender = 4,
    maxIncomingPreciseMultipartParts = 256,
    maxIncomingPreciseResponseTokenBytes = 64,
    maxPendingPreciseMultipartMembers = 40,
    pendingPreciseMultipartTtlSeconds = 45,
    pendingPreciseMultipartPruneIntervalSeconds = 1,
    inboundRequestWindowRetentionSeconds = 20,
    incomingSnapshotStartWindowSeconds = 5,
    maxIncomingSnapshotStartsPerSender = 6,
    incomingSnapshotRequestWindowSeconds = 5,
    maxIncomingSnapshotRequestsPerSender = 2,
    incomingPreciseRequestWindowSeconds = 2,
    maxIncomingPreciseRequestsPerSender = 12,
    preciseResponseTokenRetentionSeconds = 30,
    maxIncomingPreciseRequestTokenBytes = 64,
    preparedArchiveRepairRetentionSeconds = 3,
    maxPreparedArchiveRepairs = 12,
    preparedSnapshotRetentionSeconds = 20,
    maxPreparedSnapshots = 8,
    snapshotPreparationBurstLimit = 1,
    -- Queue one chunked snapshot at a time. A raid fanout may contain hundreds
    -- of packets per member, so overlapping generations only increases chat
    -- throttling without improving the first member's readiness time.
    snapshotAdmissionMaxActiveTransfers = 1,
    snapshotAdmissionMaxActiveTransfersWhileThrottled = 1,
    snapshotAdmissionMaxBackgroundActiveTransfers = 1,
    snapshotAdmissionMaxQueuedMessages = 96,
    snapshotAdmissionMaxQueuedMessagesWhileThrottled = 48,
    snapshotAdmissionPollSeconds = 0.50,
  }
  local CloneProfileSyncSubdomainList
  local EncodeProfileSyncSubchecks
  local DecodeProfileSyncSubchecks
  local SendProfileSyncAck

  local generationOps = (function()
    local createProfileSyncGenerationOps = type(rawget(_G, "LIDCOUNCIL_API")) == "table"
      and type(rawget(_G, "LIDCOUNCIL_API").__internal) == "table"
      and rawget(_G, "LIDCOUNCIL_API").__internal.LIDCOUNCIL_CreateProfileSyncGenerationOps_Impl
      or nil
    if type(createProfileSyncGenerationOps) ~= "function" then
      error("LidCouncil missing profile sync generation helpers.")
    end
    return createProfileSyncGenerationOps({
      TrimText = TrimText,
      NormalizeCharacterKey = NormalizeCharacterKey,
      ttlSeconds = profileSyncConfig.generationConvergenceTtlSeconds,
    })
  end)()
  INTERNAL_API.LIDCOUNCIL_RunArchiveTransactionValidation_Impl = generationOps.RunArchiveTransactionValidation

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

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

  -- Keep incomplete or malformed transfers from retaining memory across a session.
  profileSyncLocalOps.pruneIncomingProfileSyncs = function(now)
    local currentTime = math.max(0, tonumber(now) or GetNow())
    local pendingSyncs = type(profileSyncSessionState.pendingProfileSyncs) == "table"
      and profileSyncSessionState.pendingProfileSyncs
      or {}
    local total = 0
    for transferId, syncState in pairs(pendingSyncs) do
      local updatedAt = math.max(0, tonumber(type(syncState) == "table" and (syncState.updatedAt or syncState.startedAt) or 0) or 0)
      if updatedAt <= 0 or (currentTime - updatedAt) >= profileSyncConfig.incomingSnapshotTransferTtlSeconds then
        pendingSyncs[transferId] = nil
      else
        total = total + 1
      end
    end
    profileSyncSessionState.pendingProfileSyncs = pendingSyncs
    return total
  end

  profileSyncLocalOps.canStartIncomingProfileSync = function(senderKey, now)
    local pendingCount = profileSyncLocalOps.pruneIncomingProfileSyncs(now)
    if pendingCount >= profileSyncConfig.maxPendingIncomingSnapshotTransfers then
      return false, "incoming_profile_sync_capacity_reached"
    end
    local normalizedSender = NormalizeSenderKey(senderKey)
    local senderCount = 0
    for _, syncState in pairs(profileSyncSessionState.pendingProfileSyncs) do
      if type(syncState) == "table" and NormalizeSenderKey(syncState.sender) == normalizedSender then
        senderCount = senderCount + 1
      end
    end
    if senderCount >= profileSyncConfig.maxPendingIncomingSnapshotTransfersPerSender then
      return false, "incoming_profile_sync_sender_capacity_reached"
    end
    return true
  end

  profileSyncLocalOps.resolveOptionalApiFunction = function(apiName)
    local resolvedApiName = TrimText(apiName)
    if resolvedApiName == "" then
      return nil
    end
    local cached = profileSyncCaches.optionalApiFunctions[resolvedApiName]
    if cached ~= nil then
      return cached ~= false and cached or nil
    end
    if type(deps.ResolveOptionalApiFunction) ~= "function" then
      profileSyncCaches.optionalApiFunctions[resolvedApiName] = false
      profileSyncCaches.optionalApiUnavailable[resolvedApiName] = true
      return nil
    end
    local ok, resolved = pcall(deps.ResolveOptionalApiFunction, resolvedApiName)
    if not ok then
      profileSyncCaches.optionalApiFunctions[resolvedApiName] = false
      profileSyncCaches.optionalApiUnavailable[resolvedApiName] = true
      profileSyncLocalOps.warnOptionalApiFailure("ResolveOptionalApiFunction(" .. resolvedApiName .. ")", resolved, "resolve")
      return nil
    end
    if type(resolved) == "function" then
      profileSyncCaches.optionalApiFunctions[resolvedApiName] = resolved
      return resolved
    end
    profileSyncCaches.optionalApiFunctions[resolvedApiName] = false
    profileSyncCaches.optionalApiUnavailable[resolvedApiName] = true
    return nil
  end

  profileSyncLocalOps.warnOptionalApiFailure = function(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 profileSyncCaches.optionalApiFailureSignatures[failureSignature] == true then
      return
    end
    profileSyncCaches.optionalApiFailureSignatures[failureSignature] = true
    local contextSuffix = resolvedContext ~= "" and " during " .. resolvedContext or ""
    profileSyncLocalOps.printTextIfSupported("Optional LidCouncil API " .. resolvedApiName .. " failed during profile sync" .. contextSuffix .. ": " .. resolvedErrorText)
  end

  profileSyncLocalOps.invokeOptionalApi = function(apiName, context, ...)
    local resolvedApiName = TrimText(apiName)
    local optionalFn = profileSyncLocalOps.resolveOptionalApiFunction(resolvedApiName)
    if type(optionalFn) ~= "function" then
      return false, "unavailable"
    end
    local ok, result1, result2, result3, result4, result5 = pcall(optionalFn, ...)
    if not ok then
      profileSyncLocalOps.warnOptionalApiFailure(resolvedApiName, result1, context)
      return false, "failed", result1
    end
    return true, result1, result2, result3, result4, result5
  end

  profileSyncLocalOps.getOptionalApiSafetyStatus = function()
    local unavailableCount = 0
    local failureCount = 0
    for _ in pairs(profileSyncCaches.optionalApiUnavailable) do
      unavailableCount = unavailableCount + 1
    end
    for _ in pairs(profileSyncCaches.optionalApiFailureSignatures) do
      failureCount = failureCount + 1
    end
    return {
      unavailableCount = unavailableCount,
      failureCount = failureCount,
    }
  end

  profileSyncLocalOps.refreshHostSessionMemberState = function(profileName, sessionId, opts)
    local invoked, result1, result2, result3 = profileSyncLocalOps.invokeOptionalApi(
      "LIDCOUNCIL_RefreshHostSessionMemberState",
      "host_member_refresh",
      profileName,
      sessionId,
      opts
    )
    if not invoked then
      return false, result1 == "failed" and tostring(result2 or "Optional host session member refresh failed.")
        or "Optional host session member refresh is unavailable."
    end
    return result1, result2, result3
  end

  profileSyncLocalOps.refreshChoicePopup = function(opts)
    local invoked, result = profileSyncLocalOps.invokeOptionalApi(
      "LIDCOUNCIL_RefreshChoicePopup",
      "choice_popup_refresh",
      type(opts) == "table" and opts or {}
    )
    if not invoked then
      return false
    end
    return result == true
  end

  profileSyncLocalOps.broadcastSessionMemberUpdate = function(profileName, sessionId, memberKey, memberState)
    local invoked, result = profileSyncLocalOps.invokeOptionalApi(
      "LIDCOUNCIL_BroadcastSessionMemberUpdate",
      "member_update_broadcast",
      profileName,
      sessionId,
      memberKey,
      memberState
    )
    if not invoked then
      return false
    end
    return result == true
  end

  profileSyncLocalOps.requestSessionEditorRefresh = function(opts)
    opts = type(opts) == "table" and opts or {}
    if type(sessionRuntimeOps.requestSessionEditorRefresh) == "function" then
      return sessionRuntimeOps.requestSessionEditorRefresh(opts)
    end
    if type(sessionRuntimeOps.refreshEditor) == "function" then
      return sessionRuntimeOps.refreshEditor(opts)
    end
    return false
  end

  profileSyncLocalOps.refreshCurrentAndSyncSections = function(currentSectionChanged, opts)
    opts = type(opts) == "table" and opts or {}
    if type(sessionRuntimeOps.refreshCurrentAndSyncSections) == "function" then
      return sessionRuntimeOps.refreshCurrentAndSyncSections(currentSectionChanged == true, opts)
    end
    return profileSyncLocalOps.requestSessionEditorRefresh({
      refreshEditor = opts.refreshEditor,
      defer = opts.defer,
      delaySeconds = opts.delaySeconds,
      forceImmediate = opts.forceImmediate,
      lootSessionSections = currentSectionChanged == true and {
        CURRENT = true,
        SYNCMGMT = true,
      } or {
        SYNCMGMT = true,
      },
    })
  end

  profileSyncLocalOps.refreshSyncManagementSection = function(opts)
    opts = type(opts) == "table" and opts or {}
    if type(sessionRuntimeOps.refreshSyncManagementSection) == "function" then
      return sessionRuntimeOps.refreshSyncManagementSection(opts)
    end
    return profileSyncLocalOps.requestSessionEditorRefresh({
      refreshEditor = opts.refreshEditor,
      defer = opts.defer,
      delaySeconds = opts.delaySeconds,
      forceImmediate = opts.forceImmediate,
      lootSessionSections = {
        SYNCMGMT = true,
      },
    })
  end

  profileSyncLocalOps.buildCountLabelText = function(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

  profileSyncLocalOps.buildUndoSnapshotSummary = function(actionLabel, actorKey)
    local resolvedActionLabel = TrimText(actionLabel)
    if resolvedActionLabel == "" then
      resolvedActionLabel = "applying incoming shared profile data"
    end
    return "Before " .. resolvedActionLabel .. " from " .. tostring(NormalizeCharacterKey(actorKey) ~= "" and NormalizeCharacterKey(actorKey) or actorKey) .. "."
  end

  profileSyncLocalOps.pushUndoSnapshotIfSupported = function(profileName, kind, memberKey, profileId, summary)
    if type(deps.PushUndoSnapshot) ~= "function" then
      return false
    end
    deps.PushUndoSnapshot(profileName, {
      kind = TrimText(kind),
      memberKey = NormalizeCharacterKey(memberKey),
      profileId = TrimText(profileId),
      summary = TrimText(summary),
    })
    return true
  end

  profileSyncLocalOps.recordRepairHistoryIfSupported = function(entry)
    if type(deps.RecordRepairHistory) == "function" and type(entry) == "table" then
      deps.RecordRepairHistory(entry)
      return true
    end
    return false
  end

  profileSyncLocalOps.printTextIfSupported = function(text)
    local resolvedText = TrimText(text)
    if resolvedText == "" or type(Print) ~= "function" then
      return false
    end
    Print(resolvedText)
    return true
  end

  profileSyncLocalOps.printResolvedFailure = function(result, fallbackText)
    return profileSyncLocalOps.printTextIfSupported(tostring(result or TrimText(fallbackText)))
  end

  profileSyncLocalOps.buildPreviewResolutionMessage = function(memberKey, rowCount, subdomainCount, queuedDirectRepair, directRepairStats)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if resolvedMemberKey == "" then
      resolvedMemberKey = tostring(memberKey or "Unknown")
    end
    directRepairStats = type(directRepairStats) == "table" and directRepairStats or {}

    local directRepairMembers = math.max(0, tonumber(directRepairStats.queuedMembers) or 0)
    local directRepairTransfers = math.max(0, tonumber(directRepairStats.queuedTransfers) or 0)
    local directRepairRowPatchTransfers = math.max(0, tonumber(directRepairStats.rowPatchTransfers) or 0)
    local directRepairRowPatchRows = math.max(0, tonumber(directRepairStats.rowPatchRows) or 0)
    local directRepairPatchTransfers = math.max(0, tonumber(directRepairStats.patchTransfers) or 0)
    local directRepairPatchScopes = math.max(0, tonumber(directRepairStats.patchSubdomains) or 0)
    local directRepairSnapshotTransfers = math.max(0, tonumber(directRepairStats.snapshotTransfers) or 0)
    local directRepairSkippedLineage = math.max(0, tonumber(directRepairStats.skippedLineage) or 0)
    local directRepairFailures = math.max(0, tonumber(directRepairStats.failedMembers) or 0)

    local resolutionMessage = "Applied " .. profileSyncLocalOps.buildCountLabelText(rowCount, "preview row")
      .. " across " .. profileSyncLocalOps.buildCountLabelText(subdomainCount, "leaf scope")
      .. " for " .. tostring(resolvedMemberKey) .. "."
    if queuedDirectRepair and directRepairMembers > 0 then
      resolutionMessage = resolutionMessage
        .. " Queued direct host repair for " .. profileSyncLocalOps.buildCountLabelText(directRepairMembers, "joined member")
        .. " (" .. profileSyncLocalOps.buildCountLabelText(directRepairTransfers, "transfer")
        .. ", " .. profileSyncLocalOps.buildCountLabelText(directRepairRowPatchTransfers, "row-patch transfer")
        .. ", " .. profileSyncLocalOps.buildCountLabelText(directRepairRowPatchRows, "selected row")
        .. ", " .. profileSyncLocalOps.buildCountLabelText(directRepairPatchTransfers, "patch transfer")
        .. ", " .. profileSyncLocalOps.buildCountLabelText(directRepairPatchScopes, "patch scope")
        .. ", " .. profileSyncLocalOps.buildCountLabelText(directRepairSnapshotTransfers, "snapshot fallback transfer") .. ")."
    elseif directRepairSkippedLineage > 0 then
      resolutionMessage = resolutionMessage
        .. " Skipped " .. profileSyncLocalOps.buildCountLabelText(directRepairSkippedLineage, "joined member")
        .. " because the shared profile lineage did not match."
    end
    if directRepairFailures > 0 then
      resolutionMessage = resolutionMessage
        .. " " .. profileSyncLocalOps.buildCountLabelText(directRepairFailures, "direct repair target")
        .. " could not be queued cleanly."
    end
    return resolutionMessage
  end

  profileSyncLocalOps.buildPreviewResolutionNoticeText = function(memberKey, queuedDirectRepair, directRepairStats)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if resolvedMemberKey == "" then
      resolvedMemberKey = tostring(memberKey or "Unknown")
    end
    local queuedMembers = math.max(0, tonumber(type(directRepairStats) == "table" and directRepairStats.queuedMembers or 0) or 0)
    if queuedDirectRepair and queuedMembers > 0 then
      return "Applied selected preview rows from " .. tostring(resolvedMemberKey)
        .. " to the host copy and queued direct host repair for the affected leaf scopes."
    end
    return "Applied selected preview rows from " .. tostring(resolvedMemberKey) .. " to the host copy."
  end

  profileSyncLocalOps.buildPreviewSnapshotReceivedNoticeText = function(senderKey)
    local resolvedSenderKey = NormalizeSenderKey(senderKey)
    if resolvedSenderKey == "" then
      resolvedSenderKey = tostring(senderKey or "Unknown")
    end
    return "Received a member change preview snapshot from " .. tostring(resolvedSenderKey) .. "."
  end

  profileSyncLocalOps.resolvePreviewResolutionGuardTexts = function(reason)
    local resolvedReason = TrimText(reason)
    if resolvedReason == "no_active_session" then
      return "No active loot session.", "No active loot session."
    end
    if resolvedReason == "not_host" then
      return "Only the loot session host can apply preview conflict selections.", "Only the host can apply preview conflict selections."
    end
    if resolvedReason == "missing_preview_state" then
      return "No preview conflict state is ready. Request Preview Member Repair again.", "No preview conflict state is ready."
    end
    if resolvedReason == "stale_preview_state" then
      return "The stored preview state is no longer current.", "The stored preview state is stale."
    end
    if resolvedReason == "preview_expired" then
      return "That preview is too old. Request Preview Member Repair again.", "Preview expired."
    end
    if resolvedReason == "member_mismatch" then
      return "The selected preview does not match that joined member anymore.", "The selected preview does not match that joined member."
    end
    if resolvedReason == "local_changed_after_preview" then
      return "Your local host copy changed after the preview. Request a fresh preview before applying nested selections.", "Local host copy changed after preview."
    end
    if resolvedReason == "member_unavailable" then
      return "That joined member is no longer available for preview resolution.", "Member is no longer available."
    end
    if resolvedReason == "member_changed_after_preview" then
      return "That member reported newer sync state after the preview. Request a fresh preview before applying nested selections.", "Member state changed after preview."
    end
    return "", "Preview resolution unavailable."
  end

  profileSyncLocalOps.failPreviewResolutionGuard = function(reason)
    local printMessage, resultMessage = profileSyncLocalOps.resolvePreviewResolutionGuardTexts(reason)
    profileSyncLocalOps.printTextIfSupported(printMessage)
    return false, TrimText(resultMessage) ~= "" and resultMessage or "Preview resolution unavailable."
  end

  profileSyncLocalOps.buildRequestedProfileSyncResponseRuntimeMessage = function(responseMode, preparedTransferCount, patchTransferCount, patchScopeCount)
    local isPreview = string.upper(TrimText(responseMode)) == "PREVIEW"
    local resolvedTransferCount = math.max(0, tonumber(preparedTransferCount) or 0)
    local resolvedPatchTransferCount = math.max(0, tonumber(patchTransferCount) or 0)
    local resolvedPatchScopeCount = math.max(0, tonumber(patchScopeCount) or 0)

    local message = isPreview
      and "Sent your local shared profile change preview to the session host."
      or "Sent your local shared profile update to the session host."
    if resolvedTransferCount > 1 then
      message = message .. " Transfers: " .. tostring(resolvedTransferCount) .. "."
    end
    if resolvedPatchTransferCount > 0 then
      message = message .. " Nested patch transfers: " .. tostring(resolvedPatchTransferCount)
        .. " for " .. profileSyncLocalOps.buildCountLabelText(resolvedPatchScopeCount, "scope") .. "."
    end
    return message
  end

  profileSyncLocalOps.buildRequestedProfileSyncResponsePrintText = function(responseMode, targetMemberKey, patchTransferCount)
    local isPreview = string.upper(TrimText(responseMode)) == "PREVIEW"
    local resolvedTarget = NormalizeCharacterKey(targetMemberKey)
    if resolvedTarget == "" then
      resolvedTarget = tostring(targetMemberKey or "Unknown")
    end
    local resolvedPatchTransferCount = math.max(0, tonumber(patchTransferCount) or 0)

    local message = "Sent your shared profile " .. (isPreview and "change preview" or "update")
      .. " to the session host " .. tostring(resolvedTarget)
    if resolvedPatchTransferCount > 0 then
      message = message .. " using " .. profileSyncLocalOps.buildCountLabelText(resolvedPatchTransferCount, "nested patch transfer")
    end
    return message .. "."
  end

  profileSyncLocalOps.emitRequestedProfileSyncResponseNotice = function(opts)
    opts = type(opts) == "table" and opts or {}
    local sessionId = TrimText(opts.sessionId)
    local profileName = TrimText(opts.profileName)
    local responseMode = string.upper(TrimText(opts.responseMode))
    local targetMemberKey = opts.targetMemberKey
    local preparedTransferCount = math.max(0, tonumber(opts.preparedTransferCount) or 0)
    local patchTransferCount = math.max(0, tonumber(opts.patchTransferCount) or 0)
    local patchScopeCount = math.max(0, tonumber(opts.patchScopeCount) or 0)

    return profileSyncLocalOps.emitProfileSyncRuntimeNotice({
      sessionId = sessionId,
      profileName = profileName,
      runtimeStateKey = responseMode == "PREVIEW" and "member_sent_preview" or "member_sent_update",
      runtimeStateLevel = "success",
      runtimeStateMessage = profileSyncLocalOps.buildRequestedProfileSyncResponseRuntimeMessage(
        responseMode,
        preparedTransferCount,
        patchTransferCount,
        patchScopeCount
      ),
      sender = targetMemberKey,
      skipIfSame = true,
      printMessage = profileSyncLocalOps.buildRequestedProfileSyncResponsePrintText(responseMode, targetMemberKey, patchTransferCount),
    })
  end

  profileSyncLocalOps.buildPreciseProfileSyncSendRuntimeMessage = function(kind)
    local resolvedKind = TrimText(kind)
    if resolvedKind == "subchecks" then
      return "Sent detailed shared-profile checksum scopes to the session host."
    end
    if resolvedKind == "patch_manifest" then
      return "Sent nested patch manifests to the session host."
    end
    return "Sent precise shared-profile sync details to the session host."
  end

  profileSyncLocalOps.emitPreciseProfileSyncSendNotice = function(opts)
    opts = type(opts) == "table" and opts or {}
    local preciseKind = TrimText(opts.kind)
    return profileSyncLocalOps.emitProfileSyncRuntimeNotice({
      sessionId = TrimText(opts.sessionId),
      profileName = TrimText(opts.profileName),
      runtimeStateKey = preciseKind == "patch_manifest" and "member_sent_patch_manifest" or "member_sent_subchecks",
      runtimeStateLevel = "success",
      runtimeStateMessage = profileSyncLocalOps.buildPreciseProfileSyncSendRuntimeMessage(preciseKind),
      sender = opts.sender,
      skipIfSame = true,
    })
  end

  profileSyncLocalOps.buildPreciseProfileSyncLoadRuntimeMessage = function(kind, senderKey, domain)
    local resolvedKind = TrimText(kind)
    local resolvedSenderKey = NormalizeCharacterKey(senderKey)
    if resolvedSenderKey == "" then
      resolvedSenderKey = tostring(senderKey or "Unknown")
    end
    if resolvedKind == "subchecks" then
      local resolvedDomain = TrimText(domain)
      if resolvedDomain == "" then
        resolvedDomain = "unknown scope"
      else
        resolvedDomain = tostring(PROFILE_REVISION_DOMAIN_LABELS[resolvedDomain] or resolvedDomain)
      end
      return "Loaded detailed checksum scopes from " .. tostring(resolvedSenderKey) .. " for " .. tostring(resolvedDomain) .. "."
    end
    if resolvedKind == "patch_manifest" then
      return "Loaded nested patch manifests from " .. tostring(resolvedSenderKey) .. "."
    end
    if resolvedKind == "subchecks_timeout" then
      return "Detailed checksum request to " .. tostring(resolvedSenderKey) .. " timed out. Retry is available."
    end
    if resolvedKind == "subchecks_send_failed" then
      return "Detailed checksum request to " .. tostring(resolvedSenderKey) .. " could not be sent. Retry is available."
    end
    return "Loaded precise shared-profile sync details from " .. tostring(resolvedSenderKey) .. "."
  end

  profileSyncLocalOps.emitPreciseProfileSyncLoadNotice = function(opts)
    opts = type(opts) == "table" and opts or {}
    local preciseKind = TrimText(opts.kind)
    local runtimeStateChanged = profileSyncLocalOps.emitProfileSyncRuntimeNotice({
      sessionId = TrimText(opts.sessionId),
      profileName = TrimText(opts.profileName),
      runtimeStateKey = preciseKind == "patch_manifest" and "patch_manifest_loaded" or "subchecks_loaded",
      runtimeStateLevel = (preciseKind == "subchecks_timeout" or preciseKind == "subchecks_send_failed") and "warning" or "info",
      runtimeStateMessage = profileSyncLocalOps.buildPreciseProfileSyncLoadRuntimeMessage(preciseKind, opts.sender, opts.domain),
      sender = opts.sender,
      skipIfSame = true,
    })
    if opts.refreshSection ~= false then
      profileSyncLocalOps.refreshSyncManagementSection({
        defer = opts.deferRefresh ~= false,
      })
    end
    return runtimeStateChanged
  end

  profileSyncLocalOps.buildSnapshotAckRuntimeMessage = function(senderKey, chunkCount)
    local resolvedSenderKey = NormalizeCharacterKey(senderKey)
    if resolvedSenderKey == "" then
      resolvedSenderKey = tostring(senderKey or "Unknown")
    end
    return "Profile snapshot was applied by " .. tostring(resolvedSenderKey)
      .. " (" .. tostring(math.max(0, tonumber(chunkCount) or 0)) .. " chunks)."
  end

  profileSyncLocalOps.emitSnapshotAckNotice = function(opts)
    opts = type(opts) == "table" and opts or {}
    return profileSyncLocalOps.emitProfileSyncRuntimeNotice({
      sessionId = TrimText(opts.sessionId),
      profileName = TrimText(opts.profileName),
      runtimeStateKey = "snapshot_ack",
      runtimeStateLevel = "success",
      runtimeStateMessage = profileSyncLocalOps.buildSnapshotAckRuntimeMessage(opts.sender, opts.chunkCount),
      sender = opts.sender,
      skipIfSame = true,
    })
  end

  local function PrunePreciseResponseRuntime(now)
    local currentTime = tonumber(now) or GetNow()
    local cutoff = currentTime - profileSyncConfig.localProfileStateRetentionSeconds
    local inboundRequestCutoff = currentTime - profileSyncConfig.inboundRequestWindowRetentionSeconds
    local responseTokenCutoff = currentTime - profileSyncConfig.preciseResponseTokenRetentionSeconds
    local activeSession = GetActiveLootSession()
    local activeRequestPrefix = type(activeSession) == "table" and TrimText(activeSession.id) ~= ""
      and (string.lower(TrimText(activeSession.id)) .. "|")
      or ""
    for requestKey, pending in pairs(profileSyncResponseRuntime.precise.pendingSubchecksum) do
      local updatedAt = math.max(0, tonumber(type(pending) == "table" and (pending.updatedAt or pending.queuedAt) or 0) or 0)
      if updatedAt <= 0 or updatedAt < cutoff then
        profileSyncResponseRuntime.precise.pendingSubchecksum[requestKey] = nil
      end
    end
    for requestKey, pending in pairs(profileSyncResponseRuntime.precise.pendingPatchManifest) do
      local updatedAt = math.max(0, tonumber(type(pending) == "table" and (pending.updatedAt or pending.queuedAt) or 0) or 0)
      if updatedAt <= 0 or updatedAt < cutoff then
        profileSyncResponseRuntime.precise.pendingPatchManifest[requestKey] = nil
      end
    end
    for requestStamp, recentState in pairs(profileSyncResponseRuntime.precise.recentSubchecksum) do
      local sentAt = math.max(0, tonumber(type(recentState) == "table" and recentState.sentAt or 0) or 0)
      local belongsToActiveSession = activeRequestPrefix ~= ""
        and string.lower(TrimText(requestStamp)):sub(1, #activeRequestPrefix) == activeRequestPrefix
      if not belongsToActiveSession and (sentAt <= 0 or sentAt < cutoff) then
        profileSyncResponseRuntime.precise.recentSubchecksum[requestStamp] = nil
      end
    end
    for requestStamp, recentState in pairs(profileSyncResponseRuntime.precise.recentPatchManifest) do
      local sentAt = math.max(0, tonumber(type(recentState) == "table" and recentState.sentAt or 0) or 0)
      local belongsToActiveSession = activeRequestPrefix ~= ""
        and string.lower(TrimText(requestStamp)):sub(1, #activeRequestPrefix) == activeRequestPrefix
      if not belongsToActiveSession and (sentAt <= 0 or sentAt < cutoff) then
        profileSyncResponseRuntime.precise.recentPatchManifest[requestStamp] = nil
      end
    end
    for requestKey, pending in pairs(profileSyncResponseRuntime.requested.pending) do
      local updatedAt = math.max(0, tonumber(type(pending) == "table" and (pending.updatedAt or pending.queuedAt) or 0) or 0)
      if updatedAt <= 0 or updatedAt < cutoff then
        profileSyncResponseRuntime.requested.pending[requestKey] = nil
      end
    end
    for requestStamp, recentState in pairs(profileSyncResponseRuntime.requested.recent) do
      local sentAt = math.max(0, tonumber(type(recentState) == "table" and recentState.sentAt or 0) or 0)
      if sentAt <= 0 or sentAt < cutoff then
        profileSyncResponseRuntime.requested.recent[requestStamp] = nil
      end
    end
    for requestKey, requestState in pairs(profileSyncResponseRuntime.inboundRequestWindows) do
      local updatedAt = math.max(0, tonumber(type(requestState) == "table" and requestState.updatedAt or 0) or 0)
      if updatedAt <= 0 or updatedAt < inboundRequestCutoff then
        profileSyncResponseRuntime.inboundRequestWindows[requestKey] = nil
      end
    end
    for tokenKey, tokenState in pairs(profileSyncCaches.preciseResponseTokens) do
      local updatedAt = math.max(0, tonumber(type(tokenState) == "table" and tokenState.updatedAt or 0) or 0)
      local belongsToActiveSession = activeRequestPrefix ~= ""
        and string.lower(TrimText(tokenKey)):sub(1, #activeRequestPrefix) == activeRequestPrefix
      if not belongsToActiveSession and (updatedAt <= 0 or updatedAt < responseTokenCutoff) then
        profileSyncCaches.preciseResponseTokens[tokenKey] = nil
      end
    end
    for requestStamp, tokenState in pairs(profileSyncCaches.patchManifestRequestTokensByStamp) do
      local updatedAt = math.max(0, tonumber(type(tokenState) == "table" and tokenState.updatedAt or 0) or 0)
      local belongsToActiveSession = activeRequestPrefix ~= ""
        and string.lower(TrimText(requestStamp)):sub(1, #activeRequestPrefix) == activeRequestPrefix
      if not belongsToActiveSession and (updatedAt <= 0 or updatedAt < responseTokenCutoff) then
        profileSyncCaches.patchManifestRequestTokensByStamp[requestStamp] = nil
      end
    end
    local requestStateCutoff = currentTime - profileSyncConfig.preciseRequestStateRetentionSeconds
    for requestKey, requestState in pairs(profileSyncCaches.preciseSubchecksumRequestStateByMember) do
      local updatedAt = math.max(0, tonumber(type(requestState) == "table" and requestState.updatedAt or 0) or 0)
      local belongsToActiveSession = activeRequestPrefix ~= ""
        and string.lower(TrimText(requestKey)):sub(1, #activeRequestPrefix) == activeRequestPrefix
      if not belongsToActiveSession and (updatedAt <= 0 or updatedAt < requestStateCutoff) then
        profileSyncCaches.preciseSubchecksumRequestStateByMember[requestKey] = nil
      end
    end
    for dropKey, dropState in pairs(profileSyncCaches.preciseResponseDrops) do
      local updatedAt = math.max(0, tonumber(type(dropState) == "table" and dropState.updatedAt or 0) or 0)
      if updatedAt <= 0 or updatedAt < responseTokenCutoff then
        profileSyncCaches.preciseResponseDrops[dropKey] = nil
      end
    end
  end

  profileSyncLocalOps.allowInboundResponseRequest = function(sessionId, senderKey, kind)
    local resolvedSessionId = string.lower(TrimText(sessionId))
    local resolvedSenderKey = string.lower(NormalizeSenderKey(senderKey))
    local resolvedKind = string.upper(TrimText(kind))
    if resolvedSessionId == "" or resolvedSenderKey == "" or resolvedKind == "" then
      return false, "invalid_inbound_request_identity"
    end
    local windowSeconds = profileSyncConfig.incomingPreciseRequestWindowSeconds
    local maximum = profileSyncConfig.maxIncomingPreciseRequestsPerSender
    if resolvedKind == "PSYNC_START" then
      windowSeconds = profileSyncConfig.incomingSnapshotStartWindowSeconds
      maximum = profileSyncConfig.maxIncomingSnapshotStartsPerSender
    elseif resolvedKind == "PSYNC_REQ" then
      windowSeconds = profileSyncConfig.incomingSnapshotRequestWindowSeconds
      maximum = profileSyncConfig.maxIncomingSnapshotRequestsPerSender
    end
    local now = GetNow()
    PrunePreciseResponseRuntime(now)
    local requestKey = resolvedSessionId .. "|" .. resolvedSenderKey .. "|" .. resolvedKind
    local requestState = profileSyncResponseRuntime.inboundRequestWindows[requestKey]
    if type(requestState) ~= "table" or (now - math.max(0, tonumber(requestState.windowStartedAt) or 0)) >= windowSeconds then
      requestState = {
        windowStartedAt = now,
        count = 0,
        updatedAt = now,
      }
      profileSyncResponseRuntime.inboundRequestWindows[requestKey] = requestState
    end
    if math.max(0, tonumber(requestState.count) or 0) >= maximum then
      requestState.updatedAt = now
      return false, "inbound_" .. string.lower(resolvedKind) .. "_rate_limited"
    end
    requestState.count = math.max(0, tonumber(requestState.count) or 0) + 1
    requestState.updatedAt = now
    return true
  end

  profileSyncLocalOps.buildPreciseResponseTokenKey = function(sessionId, memberKey, kind, scope)
    local resolvedSessionId = string.lower(TrimText(sessionId))
    local resolvedMemberKey = string.lower(NormalizeCharacterKey(memberKey))
    local resolvedKind = string.upper(TrimText(kind))
    local resolvedScope = string.lower(TrimText(scope))
    if resolvedSessionId == "" or resolvedMemberKey == "" or resolvedKind == "" or resolvedScope == "" then
      return ""
    end
    return resolvedSessionId .. "|" .. resolvedMemberKey .. "|" .. resolvedKind .. "|" .. resolvedScope
  end

  profileSyncLocalOps.createPreciseRequestToken = function(kind)
    return string.format(
      "PRQ-%s-%d-%d",
      string.upper(TrimText(kind)),
      math.max(0, tonumber(GetNow()) or 0),
      math.random(1000, 9999)
    )
  end

  profileSyncLocalOps.rememberPreciseResponseToken = function(sessionId, memberKey, kind, scopes, requestToken)
    local resolvedToken = TrimText(requestToken)
    if resolvedToken == "" or #resolvedToken > profileSyncConfig.maxIncomingPreciseRequestTokenBytes then
      return 0
    end
    local now = GetNow()
    PrunePreciseResponseRuntime(now)
    local remembered = 0
    for _, scope in ipairs(type(scopes) == "table" and scopes or {}) do
      local tokenKey = profileSyncLocalOps.buildPreciseResponseTokenKey(sessionId, memberKey, kind, scope)
      if tokenKey ~= "" then
        profileSyncCaches.preciseResponseTokens[tokenKey] = {
          token = resolvedToken,
          updatedAt = now,
        }
        remembered = remembered + 1
      end
    end
    return remembered
  end

  profileSyncLocalOps.isCurrentPreciseResponseToken = function(sessionId, memberKey, kind, scopes, requestToken)
    local resolvedToken = TrimText(requestToken)
    if resolvedToken == "" then
      return true
    end
    for _, scope in ipairs(type(scopes) == "table" and scopes or {}) do
      local tokenKey = profileSyncLocalOps.buildPreciseResponseTokenKey(sessionId, memberKey, kind, scope)
      local tokenState = tokenKey ~= "" and profileSyncCaches.preciseResponseTokens[tokenKey] or nil
      if type(tokenState) == "table" and TrimText(tokenState.token) ~= "" then
        if TrimText(tokenState.token) ~= resolvedToken then
          local dropKey = string.lower(TrimText(sessionId)) .. "|" .. string.lower(NormalizeCharacterKey(memberKey)) .. "|" .. string.upper(TrimText(kind))
          local dropState = profileSyncCaches.preciseResponseDrops[dropKey] or {
            count = 0,
          }
          dropState.count = math.max(0, tonumber(dropState.count) or 0) + 1
          dropState.updatedAt = GetNow()
          profileSyncCaches.preciseResponseDrops[dropKey] = dropState
          return false
        end
      end
    end
    return true
  end

  profileSyncLocalOps.isKnownPreciseResponseToken = function(sessionId, memberKey, kind, requestToken)
    local resolvedToken = TrimText(requestToken)
    if resolvedToken == "" then
      return true
    end
    local tokenPrefix = string.lower(TrimText(sessionId))
      .. "|" .. string.lower(NormalizeCharacterKey(memberKey))
      .. "|" .. string.upper(TrimText(kind)) .. "|"
    local foundRememberedScope = false
    for tokenKey, tokenState in pairs(profileSyncCaches.preciseResponseTokens) do
      if type(tokenKey) == "string"
        and string.sub(tokenKey, 1, #tokenPrefix) == tokenPrefix
        and type(tokenState) == "table"
        and TrimText(tokenState.token) ~= ""
      then
        foundRememberedScope = true
        if TrimText(tokenState.token) == resolvedToken then
          return true
        end
      end
    end
    if not foundRememberedScope then
      return true
    end
    local dropKey = string.lower(TrimText(sessionId))
      .. "|" .. string.lower(NormalizeCharacterKey(memberKey))
      .. "|" .. string.upper(TrimText(kind))
    local dropState = profileSyncCaches.preciseResponseDrops[dropKey] or { count = 0 }
    dropState.count = math.max(0, tonumber(dropState.count) or 0) + 1
    dropState.updatedAt = GetNow()
    profileSyncCaches.preciseResponseDrops[dropKey] = dropState
    return false
  end

  profileSyncLocalOps.getPreciseResponseSafetyStatus = function()
    PrunePreciseResponseRuntime(GetNow())
    local staleResponseDrops = 0
    local lastStaleResponseDropAt = 0
    for _, dropState in pairs(profileSyncCaches.preciseResponseDrops) do
      if type(dropState) == "table" then
        staleResponseDrops = staleResponseDrops + math.max(0, tonumber(dropState.count) or 0)
        lastStaleResponseDropAt = math.max(lastStaleResponseDropAt, math.max(0, tonumber(dropState.updatedAt) or 0))
      end
    end
    return {
      staleResponseDrops = staleResponseDrops,
      lastStaleResponseDropAt = lastStaleResponseDropAt,
    }
  end

  local function PruneRecentLocalProfileStateSends(now)
    local cutoff = (tonumber(now) or GetNow()) - profileSyncConfig.localProfileStateRetentionSeconds
    for stateKey, stateInfo in pairs(profileSyncCaches.recentLocalProfileStateSends) do
      local sentAt = math.max(0, tonumber(type(stateInfo) == "table" and stateInfo.sentAt or 0) or 0)
      if sentAt <= 0 or sentAt < cutoff then
        profileSyncCaches.recentLocalProfileStateSends[stateKey] = nil
      end
    end
  end

  profileSyncLocalOps.buildLocalProfileStateSendKey = function(host, sessionId, profileName, selfKey)
    local resolvedHost = string.lower(NormalizeCharacterKey(host))
    local resolvedSessionId = string.lower(TrimText(sessionId))
    local resolvedProfileName = string.lower(TrimText(profileName))
    local resolvedSelfKey = string.lower(NormalizeCharacterKey(selfKey))
    if resolvedHost == "" or resolvedSessionId == "" or resolvedProfileName == "" or resolvedSelfKey == "" then
      return ""
    end
    return table.concat({
      resolvedHost,
      resolvedSessionId,
      resolvedProfileName,
      resolvedSelfKey,
    }, "|")
  end

  profileSyncLocalOps.buildLocalProfileStateSendSignature = function(profileId, summary, liveLootChecksum, archiveLootChecksum, archiveScopeChecksums)
    summary = type(summary) == "table" and summary or {}
    archiveScopeChecksums = type(archiveScopeChecksums) == "table" and archiveScopeChecksums or {}
    return table.concat({
      TrimText(profileId),
      tostring(summary.settings or 0),
      tostring(summary.permissions or 0),
      tostring(summary.operational or 0),
      tostring(summary.loot or summary.operational or 0),
      tostring(summary.session or summary.operational or 0),
      tostring(summary.updatedAt or 0),
      TrimText(summary.settingsChecksum),
      TrimText(summary.permissionsChecksum),
      TrimText(summary.operationalChecksum),
      TrimText(summary.lootChecksum),
      TrimText(summary.sessionChecksum),
      TrimText(liveLootChecksum),
      TrimText(archiveLootChecksum),
      TrimText(archiveScopeChecksums.lootList),
      TrimText(archiveScopeChecksums.itemHistory),
      TrimText(archiveScopeChecksums.sessionHistory),
      TrimText(archiveScopeChecksums.funAwards),
    }, "\31")
  end

  profileSyncLocalOps.getArchiveSyncPaused = function()
    local invoked, paused = profileSyncLocalOps.invokeOptionalApi(
      "LIDCOUNCIL_GetArchiveSyncPaused",
      "archive_pause_check"
    )
    if not invoked then
      return false
    end
    return paused == true
  end

  profileSyncLocalOps.isSnapshotBatchItemArchivePaused = function(item)
    item = type(item) == "table" and item or {}
    local opts = type(item.opts) == "table" and item.opts or {}
    local resolvedReason = string.lower(TrimText(opts.reason))
    return profileSyncLocalOps.getArchiveSyncPaused()
      and resolvedReason ~= ""
      and string.find(resolvedReason, "archive", 1, true) ~= nil
      and string.find(resolvedReason, "background", 1, true) ~= nil
  end

  local function BuildEmptyRevisionSummary(profileName, profileId)
    return {
      profileName = TrimText(profileName),
      profileId = TrimText(profileId),
      settings = 0,
      permissions = 0,
      operational = 0,
      loot = 0,
      session = 0,
      settingsChecksum = "",
      permissionsChecksum = "",
      operationalChecksum = "",
      lootChecksum = "",
      sessionChecksum = "",
      liveLootChecksum = "",
      archiveLootChecksum = "",
      updatedAt = 0,
    }
  end

  local function NormalizeRevisionSummary(summary, fallbackName, fallbackId)
    summary = type(summary) == "table" and summary or {}
    local operationalRevision = math.max(0, tonumber(summary.operational) or 0)
    local operationalChecksum = TrimText(summary.operationalChecksum)
    local lootRevision = math.max(0, tonumber(summary.loot) or operationalRevision)
    local sessionRevision = math.max(0, tonumber(summary.session) or operationalRevision)
    local lootChecksum = TrimText(summary.lootChecksum)
    if lootChecksum == "" then
      lootChecksum = operationalChecksum
    end
    local sessionChecksum = TrimText(summary.sessionChecksum)
    if sessionChecksum == "" then
      sessionChecksum = operationalChecksum
    end
    return {
      profileName = FirstNonEmptyText(summary.profileName, fallbackName),
      profileId = FirstNonEmptyText(summary.profileId, fallbackId),
      settings = math.max(0, tonumber(summary.settings) or 0),
      permissions = math.max(0, tonumber(summary.permissions) or 0),
      operational = operationalRevision,
      loot = lootRevision,
      session = sessionRevision,
      settingsChecksum = TrimText(summary.settingsChecksum),
      permissionsChecksum = TrimText(summary.permissionsChecksum),
      operationalChecksum = operationalChecksum,
      lootChecksum = lootChecksum,
      sessionChecksum = sessionChecksum,
      liveLootChecksum = TrimText(summary.liveLootChecksum),
      archiveLootChecksum = TrimText(summary.archiveLootChecksum),
      updatedAt = math.max(
        0,
        tonumber(summary.updatedAt) or 0,
        tonumber(summary.settingsUpdatedAt) or 0,
        tonumber(summary.permissionsUpdatedAt) or 0,
        tonumber(summary.operationalUpdatedAt) or 0,
        tonumber(summary.lootUpdatedAt) or 0,
        tonumber(summary.sessionUpdatedAt) or 0
      ),
    }
  end

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

  local function DoRevisionSummariesMatch(leftSummary, rightSummary, domains)
    leftSummary = NormalizeRevisionSummary(leftSummary, "", "")
    rightSummary = NormalizeRevisionSummary(rightSummary, "", "")
    local comparedDomains = ResolveProfileRevisionDomainList(domains)
    if leftSummary.profileId ~= "" and rightSummary.profileId ~= ""
      and string.lower(leftSummary.profileId) ~= string.lower(rightSummary.profileId)
    then
      return false
    end
    for _, domain in ipairs(comparedDomains) do
      if math.max(0, tonumber(leftSummary[domain]) or 0) ~= math.max(0, tonumber(rightSummary[domain]) or 0) then
        return false
      end
      if TrimText(leftSummary[domain .. "Checksum"]) ~= TrimText(rightSummary[domain .. "Checksum"]) then
        return false
      end
    end
    return true
  end

  local function CaptureSessionMemberRevisionSummary(sessionId, memberKey, profileName, profileId)
    local activeSession, activeProfileName = GetActiveLootSession()
    local resolvedSessionId = TrimText(sessionId)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if type(activeSession) ~= "table" or TrimText(activeSession.id) ~= resolvedSessionId or resolvedMemberKey == "" then
      return nil
    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 NormalizeCharacterKey(storedMemberKey) == resolvedMemberKey and type(storedMember) == "table" then
          member = storedMember
          break
        end
      end
    end
    if type(member) ~= "table" then
      return nil
    end
    return NormalizeRevisionSummary({
      profileName = FirstNonEmptyText(profileName, activeProfileName),
      profileId = FirstNonEmptyText(member.sharedProfileId, profileId),
      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),
      updatedAt = tonumber(member.profileUpdatedAt) or 0,
    }, FirstNonEmptyText(profileName, activeProfileName), FirstNonEmptyText(member.sharedProfileId, profileId))
  end

  local function ClearRuntimePreviewConflictState()
    profileSyncRuntimeState.detailDiff = nil
    profileSyncRuntimeState.detailConflict = nil
    profileSyncRuntimeState.detailSnapshotData = nil
    profileSyncRuntimeState.detailPreviewSummary = nil
    profileSyncRuntimeState.detailBaseSummary = nil
  end

  local function EncodeProfileRevisionDomains(domains)
    local resolved = ResolveProfileRevisionDomainList(domains)
    return table.concat(resolved, ",")
  end

  local function DecodeProfileRevisionDomains(text)
    local domains = {}
    local value = TrimText(text)
    if value ~= "" then
      for token in string.gmatch(value, "[^,%s;|]+") do
        domains[#domains + 1] = token
      end
    end
    return ResolveProfileRevisionDomainList(domains)
  end

  local function MergeProfileRevisionDomains(...)
    local merged = {}
    local seen = {}
    for index = 1, select("#", ...) do
      for _, domain in ipairs(ResolveProfileRevisionDomainList(select(index, ...))) do
        if not seen[domain] then
          seen[domain] = true
          merged[#merged + 1] = domain
        end
      end
    end
    return merged
  end

  local function BuildSessionMemberRevisionStateSignature(memberData)
    if type(memberData) ~= "table" then
      return ""
    end
    return table.concat({
      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

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

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

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

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

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

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

  profileSyncLocalOps.buildMemberSubchecksumStateSignature = function(state)
    state = type(state) == "table" and state or {}
    local normalizedDomains = {}
    local seenDomains = {}
    for domain in pairs(type(state.byDomain) == "table" and state.byDomain or {}) do
      local resolvedDomain = string.lower(TrimText(domain))
      if resolvedDomain ~= "" and not seenDomains[resolvedDomain] then
        seenDomains[resolvedDomain] = true
        normalizedDomains[#normalizedDomains + 1] = resolvedDomain
      end
    end
    table.sort(normalizedDomains)

    local normalizedByDomain = {}
    for _, domain in ipairs(normalizedDomains) do
      local domainState = type(state.byDomain) == "table" and type(state.byDomain[domain]) == "table" and state.byDomain[domain] or {}
      normalizedByDomain[domain] = {
        checksum = TrimText(domainState.checksum),
        subchecksums = DecodeProfileSyncSubchecks(domain, EncodeProfileSyncSubchecks(domain, domainState.subchecksums)),
      }
    end

    return BuildStableValueSignature({
      profileName = TrimText(state.profileName),
      profileId = TrimText(state.profileId),
      revisionSummary = NormalizeRevisionSummary(state.revisionSummary, state.profileName, state.profileId),
      byDomain = normalizedByDomain,
    })
  end

  profileSyncLocalOps.buildMemberPatchManifestStateSignature = function(state)
    state = type(state) == "table" and state or {}
    local normalizedSubdomains = CloneProfileSyncSubdomainList(state.scopeSubdomains)
    table.sort(normalizedSubdomains, function(left, right)
      return string.lower(tostring(left)) < string.lower(tostring(right))
    end)

    local normalizedBySubdomain = {}
    for _, subdomain in ipairs(normalizedSubdomains) do
      if type(state.bySubdomain) == "table" and type(state.bySubdomain[subdomain]) == "table" then
        normalizedBySubdomain[subdomain] = state.bySubdomain[subdomain]
      end
    end

    return BuildStableValueSignature({
      profileName = TrimText(state.profileName),
      profileId = TrimText(state.profileId),
      revisionSummary = NormalizeRevisionSummary(state.revisionSummary, state.profileName, state.profileId),
      scopeDomains = ResolveProfileRevisionDomainList(state.scopeDomains),
      scopeSubdomains = normalizedSubdomains,
      bySubdomain = normalizedBySubdomain,
    })
  end

  local function CloneProfileSyncTextList(values)
    local cloned = {}
    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
        cloned[#cloned + 1] = text
      end
    end
    return cloned
  end

  CloneProfileSyncSubdomainList = function(subdomains)
    if type(CloneLootProfileSubdomainList) == "function" then
      return CloneLootProfileSubdomainList(subdomains)
    end
    return CloneProfileSyncTextList(subdomains)
  end

  local function NormalizeProfileSyncSubdomainList(subdomains, domains)
    if type(NormalizeLootProfileSubdomainList) == "function" then
      return NormalizeLootProfileSubdomainList(subdomains, domains)
    end
    return CloneProfileSyncSubdomainList(subdomains)
  end

  local function NormalizeRequestedProfileSyncSubdomains(subdomains, domains)
    local hasExplicitSubdomains = false
    if type(subdomains) == "string" then
      hasExplicitSubdomains = TrimText(subdomains) ~= ""
    elseif type(subdomains) == "table" then
      hasExplicitSubdomains = #subdomains > 0
    end
    if not hasExplicitSubdomains then
      return {}
    end
    return NormalizeProfileSyncSubdomainList(subdomains, domains)
  end

  local function MergeRequestedProfileSyncSubdomains(domains, ...)
    local merged = {}
    for index = 1, select("#", ...) do
      local subdomains = select(index, ...)
      if type(subdomains) == "table" then
        for _, subdomain in ipairs(subdomains) do
          merged[#merged + 1] = subdomain
        end
      end
    end
    return NormalizeRequestedProfileSyncSubdomains(merged, domains)
  end

  function sessionRuntimeOps.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 sessionRuntimeOps.parseInboundNumberField(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 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

  profileSyncLocalOps.recordIncomingSnapshotReject = function(opcode, sender, fields, reason, knownSessionId)
    return INTERNAL_API.LIDCOUNCIL_RecordIncomingSnapshotReject_Impl(
      profileSyncSessionState,
      opcode,
      sender,
      fields,
      reason,
      GetNow(),
      TrimText,
      knownSessionId
    )
  end

  profileSyncLocalOps.beginIncomingSnapshotDiagnosticsForSession = function(sessionId, startedAt)
    return INTERNAL_API.LIDCOUNCIL_BeginIncomingSnapshotDiagnosticsForSession_Impl(
      profileSyncSessionState,
      sessionId,
      startedAt or GetNow(),
      TrimText
    )
  end

  function sessionRuntimeOps.recordInboundPayloadReject(opcode, sender, fields, reason, knownSessionId)
    if type(sessionRuntimeOps.recordInboundReject) == "function" then
      sessionRuntimeOps.recordInboundReject(opcode, sender, reason)
    end
    profileSyncLocalOps.recordIncomingSnapshotReject(opcode, sender, fields, reason, knownSessionId)
    if type(RecordProfileSyncDecision) ~= "function" then
      return
    end
    local resolvedOpcode = TrimText(opcode)
    local transferId = ""
    local sessionId = ""
    local profileName = ""
    if type(fields) == "table" then
      if string.find(resolvedOpcode, "PSYNC", 1, true) == 1 then
        transferId = TrimText(fields[2])
        if resolvedOpcode == "PSYNC_START" then
          sessionId = TrimText(fields[3])
          profileName = TrimText(fields[4])
        else
          sessionId = TrimText(knownSessionId)
        end
      else
        sessionId = TrimText(fields[2])
        profileName = TrimText(fields[3])
      end
    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 = resolvedOpcode,
      sender = NormalizeCharacterKey(sender),
      transferId = transferId,
      sessionId = sessionId,
      profileName = profileName,
      reason = TrimText(reason),
      fieldCount = type(fields) == "table" and math.max(0, #fields) or 0,
    })
  end

  function sessionRuntimeOps.parseInboundProfileSyncStartPayload(fields, sender)
    if not sessionRuntimeOps.hasRequiredInboundFields(fields, 6) then
      return nil, "truncated_profile_sync_start_payload"
    end
    local transferId = TrimText(fields[2])
    local sessionId = TrimText(fields[3])
    local profileName = TrimText(fields[4])
    local chunkCount, chunkCountValid = sessionRuntimeOps.parseInboundNumberField(fields, 6)
    if transferId == "" or sessionId == "" or profileName == "" then
      return nil, "missing_profile_sync_start_identity"
    end
    if not chunkCountValid or chunkCount <= 0 then
      return nil, "invalid_profile_sync_start_chunk_count"
    end
    if chunkCount > profileSyncConfig.maxIncomingSnapshotChunks then
      return nil, "profile_sync_start_chunk_count_exceeds_limit"
    end
    local syncMode = string.upper(TrimText(fields[7]))
    if syncMode ~= "" and syncMode ~= "LIVE" and syncMode ~= "REVIEW" and syncMode ~= "PREVIEW" and syncMode ~= "BACKGROUND" then
      return nil, "invalid_profile_sync_start_mode"
    end
    local transferKind = string.upper(TrimText(fields[9]))
    if transferKind ~= "" and transferKind ~= "FULL" and transferKind ~= "DOMAINS"
      and transferKind ~= "SUBDOMAINS" and transferKind ~= "PATCHES" and transferKind ~= "ROWPATCHES" then
      return nil, "invalid_profile_sync_start_transfer_kind"
    end
    local transferLane = string.lower(TrimText(fields[12]))
    if transferLane ~= "" and transferLane ~= "live" and transferLane ~= "stats" and transferLane ~= "archive" then
      return nil, "invalid_profile_sync_start_transfer_lane"
    end
    local transferPolicy = string.upper(TrimText(fields[13]))
    if transferPolicy ~= "" and transferPolicy ~= "HOST_OVERRIDE" then
      return nil, "invalid_profile_sync_start_transfer_policy"
    end
    local transferGeneration, transferGenerationValid = sessionRuntimeOps.parseInboundNumberField(fields, 11, {
      allowMissing = true,
      allowEmpty = true,
      emptyValue = 0,
    })
    if not transferGenerationValid then
      return nil, "invalid_profile_sync_start_generation"
    end
    local requestedDomains = DecodeProfileRevisionDomains(fields[8])
    return {
      transferId = transferId,
      sessionId = sessionId,
      profileName = profileName,
      profileId = TrimText(fields[5]),
      chunkCount = chunkCount,
      syncMode = syncMode,
      requestedDomains = requestedDomains,
      transferKind = transferKind,
      requestedSubdomains = NormalizeRequestedProfileSyncSubdomains(fields[10], requestedDomains),
      transferGeneration = transferGeneration,
      transferLane = transferLane,
      hostAuthoritativeOverride = transferPolicy == "HOST_OVERRIDE",
      senderKey = NormalizeSenderKey(sender),
    }, nil
  end

  function sessionRuntimeOps.parseInboundProfileSyncRequestPayload(fields, sender)
    if not sessionRuntimeOps.hasRequiredInboundFields(fields, 3) then
      return nil, "truncated_profile_sync_request_payload"
    end
    local sessionId = TrimText(fields[2])
    local profileName = TrimText(fields[3])
    if sessionId == "" or profileName == "" then
      return nil, "missing_profile_sync_request_identity"
    end
    local requestDomains = TrimText(fields[6])
    return {
      sessionId = sessionId,
      profileName = profileName,
      profileId = TrimText(fields[4]),
      requestMode = string.upper(TrimText(fields[5])),
      requestDomains = requestDomains,
      requestSubdomains = NormalizeRequestedProfileSyncSubdomains(fields[7], requestDomains),
      expectedPatchManifestToken = TrimText(fields[8]),
      senderKey = NormalizeSenderKey(sender),
    }, nil
  end

  function sessionRuntimeOps.parseInboundProfileSyncChunkPayload(fields, sender)
    if not sessionRuntimeOps.hasRequiredInboundFields(fields, 4) then
      return nil, "truncated_profile_sync_chunk_payload"
    end
    local transferId = TrimText(fields[2])
    local chunkIndex, chunkIndexValid = sessionRuntimeOps.parseInboundNumberField(fields, 3, {
      floorZero = false,
    })
    if transferId == "" then
      return nil, "missing_profile_sync_chunk_identity"
    end
    if not chunkIndexValid or chunkIndex < 1 then
      return nil, "invalid_profile_sync_chunk_index"
    end
    return {
      transferId = transferId,
      chunkIndex = chunkIndex,
      chunkData = tostring(fields[4] or ""),
      senderKey = NormalizeSenderKey(sender),
    }, nil
  end

  function sessionRuntimeOps.parseInboundProfileSyncEndPayload(fields, sender)
    if not sessionRuntimeOps.hasRequiredInboundFields(fields, 2) then
      return nil, "truncated_profile_sync_end_payload"
    end
    local transferId = TrimText(fields[2])
    if transferId == "" then
      return nil, "missing_profile_sync_end_identity"
    end
    return {
      transferId = transferId,
      senderKey = NormalizeSenderKey(sender),
    }, nil
  end

  function sessionRuntimeOps.parseInboundProfileSyncAckPayload(fields, sender)
    if not sessionRuntimeOps.hasRequiredInboundFields(fields, 17) then
      return nil, "truncated_profile_sync_ack_payload"
    end
    local transferId = TrimText(fields[2])
    local sessionId = TrimText(fields[3])
    local profileName = TrimText(fields[4])
    if transferId == "" or sessionId == "" or profileName == "" then
      return nil, "missing_profile_sync_ack_identity"
    end
    local chunkCount, chunkCountValid = sessionRuntimeOps.parseInboundNumberField(fields, 6)
    if not chunkCountValid then
      return nil, "invalid_profile_sync_ack_chunk_count"
    end
    local settingsRevision, settingsRevisionValid = sessionRuntimeOps.parseInboundNumberField(fields, 7)
    if not settingsRevisionValid then
      return nil, "invalid_profile_sync_ack_settings_revision"
    end
    local permissionsRevision, permissionsRevisionValid = sessionRuntimeOps.parseInboundNumberField(fields, 8)
    if not permissionsRevisionValid then
      return nil, "invalid_profile_sync_ack_permissions_revision"
    end
    local operationalRevision, operationalRevisionValid = sessionRuntimeOps.parseInboundNumberField(fields, 9)
    if not operationalRevisionValid then
      return nil, "invalid_profile_sync_ack_operational_revision"
    end
    local profileUpdatedAt, profileUpdatedAtValid = sessionRuntimeOps.parseInboundNumberField(fields, 10)
    if not profileUpdatedAtValid then
      return nil, "invalid_profile_sync_ack_profile_updated_at"
    end
    local lootRevision, lootRevisionValid = sessionRuntimeOps.parseInboundNumberField(fields, 14, {
      allowMissing = true,
      allowEmpty = true,
      emptyValue = operationalRevision,
    })
    if not lootRevisionValid then
      return nil, "invalid_profile_sync_ack_loot_revision"
    end
    local sessionRevision, sessionRevisionValid = sessionRuntimeOps.parseInboundNumberField(fields, 15, {
      allowMissing = true,
      allowEmpty = true,
      emptyValue = operationalRevision,
    })
    if not sessionRevisionValid then
      return nil, "invalid_profile_sync_ack_session_revision"
    end
    local appliedGeneration, appliedGenerationValid = sessionRuntimeOps.parseInboundNumberField(fields, 18, {
      allowMissing = true,
      allowEmpty = true,
      emptyValue = 0,
    })
    if not appliedGenerationValid then
      return nil, "invalid_profile_sync_ack_generation"
    end
    local ackPhase = type(INTERNAL_API.LIDCOUNCIL_NormalizeCombatSyncAckPhase_Impl) == "function"
      and INTERNAL_API.LIDCOUNCIL_NormalizeCombatSyncAckPhase_Impl(fields[19])
      or (TrimText(fields[19]) == "" and "APPLIED" or string.upper(TrimText(fields[19])))
    if ackPhase == "" then
      return nil, "invalid_profile_sync_ack_phase"
    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
    return {
      transferId = transferId,
      sessionId = sessionId,
      profileName = profileName,
      sharedProfileId = TrimText(fields[5]),
      chunkCount = chunkCount,
      settingsRevision = settingsRevision,
      permissionsRevision = permissionsRevision,
      operationalRevision = operationalRevision,
      profileUpdatedAt = profileUpdatedAt,
      settingsChecksum = TrimText(fields[11]),
      permissionsChecksum = TrimText(fields[12]),
      operationalChecksum = operationalChecksum,
      lootRevision = lootRevision,
      sessionRevision = sessionRevision,
      lootChecksum = lootChecksum,
      sessionChecksum = sessionChecksum,
      appliedGeneration = appliedGeneration,
      ackPhase = ackPhase,
      senderKey = NormalizeSenderKey(sender),
    }, nil
  end

  function sessionRuntimeOps.parseInboundProfileSubchecksumRequestPayload(fields, sender)
    if not sessionRuntimeOps.hasRequiredInboundFields(fields, 5) then
      return nil, "truncated_profile_subchecksum_request_payload"
    end
    local sessionId = TrimText(fields[2])
    local profileName = TrimText(fields[3])
    if sessionId == "" or profileName == "" then
      return nil, "missing_profile_subchecksum_request_identity"
    end
    local requestedDomains = DecodeProfileRevisionDomains(fields[5])
    local requestToken = TrimText(fields[6])
    if #requestToken > profileSyncConfig.maxIncomingPreciseRequestTokenBytes then
      return nil, "profile_subchecksum_request_token_exceeds_limit"
    end
    return {
      sessionId = sessionId,
      profileName = profileName,
      profileId = TrimText(fields[4]),
      requestedDomains = requestedDomains,
      requestToken = requestToken,
      senderKey = NormalizeSenderKey(sender),
    }, nil
  end

  function sessionRuntimeOps.parseInboundProfileSubchecksumStatePayload(fields, sender)
    if not sessionRuntimeOps.hasRequiredInboundFields(fields, 7) then
      return nil, "truncated_profile_subchecksum_state_payload"
    end
    local sessionId = TrimText(fields[2])
    local profileName = TrimText(fields[3])
    local domain = string.lower(TrimText(fields[5]))
    if sessionId == "" or profileName == "" or domain == "" then
      return nil, "missing_profile_subchecksum_state_identity"
    end
    local partIndex, partIndexValid = sessionRuntimeOps.parseInboundNumberField(fields, 9, {
      allowMissing = true,
      allowEmpty = true,
      emptyValue = 1,
    })
    if not partIndexValid then
      return nil, "invalid_profile_subchecksum_state_part_index"
    end
    local partTotal, partTotalValid = sessionRuntimeOps.parseInboundNumberField(fields, 10, {
      allowMissing = true,
      allowEmpty = true,
      emptyValue = 1,
    })
    if not partTotalValid then
      return nil, "invalid_profile_subchecksum_state_part_total"
    end
    partIndex = math.max(1, tonumber(partIndex) or 1)
    partTotal = math.max(partIndex, tonumber(partTotal) or 1)
    if partTotal > profileSyncConfig.maxIncomingPreciseMultipartParts then
      return nil, "profile_subchecksum_state_part_total_exceeds_limit"
    end
    local responseToken = TrimText(fields[8])
    if #responseToken > profileSyncConfig.maxIncomingPreciseResponseTokenBytes then
      return nil, "profile_subchecksum_state_response_token_exceeds_limit"
    end
    local requestToken = TrimText(fields[11])
    if #requestToken > profileSyncConfig.maxIncomingPreciseRequestTokenBytes then
      return nil, "profile_subchecksum_state_request_token_exceeds_limit"
    end
    return {
      sessionId = sessionId,
      profileName = profileName,
      profileId = TrimText(fields[4]),
      domain = domain,
      domainChecksum = TrimText(fields[6]),
      encodedSubchecks = TrimText(fields[7]),
      responseToken = responseToken,
      partIndex = partIndex,
      partTotal = partTotal,
      requestToken = requestToken,
      senderKey = NormalizeSenderKey(sender),
    }, nil
  end

  function sessionRuntimeOps.parseInboundProfilePatchManifestRequestPayload(fields, sender)
    if not sessionRuntimeOps.hasRequiredInboundFields(fields, 5) then
      return nil, "truncated_profile_patch_manifest_request_payload"
    end
    local sessionId = TrimText(fields[2])
    local profileName = TrimText(fields[3])
    if sessionId == "" or profileName == "" then
      return nil, "missing_profile_patch_manifest_request_identity"
    end
    local requestedSubdomains = type(FilterLootProfilePatchCapableSubdomains) == "function"
      and FilterLootProfilePatchCapableSubdomains(fields[5])
      or CloneProfileSyncSubdomainList(fields[5])
    if #requestedSubdomains == 0 then
      return nil, "missing_profile_patch_manifest_request_subdomains"
    end
    local requestToken = TrimText(fields[6])
    if #requestToken > profileSyncConfig.maxIncomingPreciseRequestTokenBytes then
      return nil, "profile_patch_manifest_request_token_exceeds_limit"
    end
    return {
      sessionId = sessionId,
      profileName = profileName,
      profileId = TrimText(fields[4]),
      requestedSubdomains = requestedSubdomains,
      requestToken = requestToken,
      senderKey = NormalizeSenderKey(sender),
    }, nil
  end

  function sessionRuntimeOps.parseInboundProfilePatchManifestStatePayload(fields, sender)
    if not sessionRuntimeOps.hasRequiredInboundFields(fields, 8) then
      return nil, "truncated_profile_patch_manifest_state_payload"
    end
    local sessionId = TrimText(fields[2])
    local profileName = TrimText(fields[3])
    if sessionId == "" or profileName == "" then
      return nil, "missing_profile_patch_manifest_state_identity"
    end
    local partIndex, partIndexValid = sessionRuntimeOps.parseInboundNumberField(fields, 6, {
      allowMissing = true,
      allowEmpty = true,
      emptyValue = 1,
    })
    if not partIndexValid then
      return nil, "invalid_profile_patch_manifest_state_part_index"
    end
    local partTotal, partTotalValid = sessionRuntimeOps.parseInboundNumberField(fields, 7, {
      allowMissing = true,
      allowEmpty = true,
      emptyValue = 1,
    })
    if not partTotalValid then
      return nil, "invalid_profile_patch_manifest_state_part_total"
    end
    partIndex = math.max(1, tonumber(partIndex) or 1)
    partTotal = math.max(partIndex, tonumber(partTotal) or 1)
    if partTotal > profileSyncConfig.maxIncomingPreciseMultipartParts then
      return nil, "profile_patch_manifest_state_part_total_exceeds_limit"
    end
    local responseToken = TrimText(fields[5])
    if #responseToken > profileSyncConfig.maxIncomingPreciseResponseTokenBytes then
      return nil, "profile_patch_manifest_state_response_token_exceeds_limit"
    end
    local requestToken = TrimText(fields[9])
    if #requestToken > profileSyncConfig.maxIncomingPreciseRequestTokenBytes then
      return nil, "profile_patch_manifest_state_request_token_exceeds_limit"
    end
    return {
      sessionId = sessionId,
      profileName = profileName,
      profileId = TrimText(fields[4]),
      responseToken = responseToken,
      partIndex = partIndex,
      partTotal = partTotal,
      chunkPayload = tostring(fields[8] or ""),
      requestToken = requestToken,
      senderKey = NormalizeSenderKey(sender),
    }, nil
  end

  local function AppendDecisionReason(reasons, reason)
    local resolvedReason = TrimText(reason)
    if resolvedReason == "" then
      return
    end
    local compareKey = string.lower(resolvedReason)
    for _, existing in ipairs(type(reasons) == "table" and reasons or {}) do
      if string.lower(TrimText(existing)) == compareKey then
        return
      end
    end
    reasons[#reasons + 1] = resolvedReason
  end

  local function ClassifyPreparedTransferFallback(requestedDomains, requestedSubdomains, transferKind, fallbackReasons)
    local resolvedRequestedDomains = CloneProfileSyncDomainList(requestedDomains)
    local resolvedRequestedSubdomains = CloneProfileSyncSubdomainList(requestedSubdomains)
    local resolvedTransferKind = string.upper(TrimText(transferKind))
    local resolvedFallbackReasons = CloneProfileSyncTextList(fallbackReasons)
    local requestedScope = #resolvedRequestedSubdomains > 0 and "precise"
      or (#resolvedRequestedDomains > 0 and "targeted" or "full")
    local fallbackEscalation = ""
    local scopeEscalated = false
    local fullSnapshotFallback = false

    if requestedScope == "precise" then
      if resolvedTransferKind == "FULL" then
        fallbackEscalation = "precise_to_full_snapshot"
        scopeEscalated = true
        fullSnapshotFallback = true
      elseif resolvedTransferKind == "DOMAINS" then
        fallbackEscalation = "precise_to_domain_snapshot"
        scopeEscalated = true
      elseif resolvedTransferKind == "SUBDOMAINS" and #resolvedFallbackReasons > 0 then
        fallbackEscalation = "patch_to_subdomain_snapshot"
        scopeEscalated = true
      end
    elseif requestedScope == "targeted" and resolvedTransferKind == "FULL" then
      fallbackEscalation = "targeted_to_full_snapshot"
      scopeEscalated = true
      fullSnapshotFallback = true
    end

    return {
      requestedScope = requestedScope,
      fallbackEscalation = fallbackEscalation,
      scopeEscalated = scopeEscalated,
      fullSnapshotFallback = fullSnapshotFallback,
    }
  end

  local function BuildPreparedTransferKindList(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 CloneProfileSyncTextList(kinds)
  end

  EncodeProfileSyncSubchecks = function(domain, subchecksums)
    local orderedKeys = type(deps.GetLootProfileSubdomainKeysForDomain) == "function"
      and deps.GetLootProfileSubdomainKeysForDomain(domain)
      or {}
    local parts = {}
    local seen = {}
    for _, subdomain in ipairs(orderedKeys or {}) do
      local checksum = TrimText(type(subchecksums) == "table" and subchecksums[subdomain] or "")
      if checksum ~= "" then
        parts[#parts + 1] = tostring(subdomain) .. "=" .. checksum
        seen[string.lower(tostring(subdomain))] = true
      end
    end
    if type(subchecksums) == "table" then
      local extraKeys = {}
      for subdomain in pairs(subchecksums) do
        extraKeys[#extraKeys + 1] = subdomain
      end
      table.sort(extraKeys, function(left, right)
        return string.lower(tostring(left)) < string.lower(tostring(right))
      end)
      for _, subdomain in ipairs(extraKeys) do
        local checksum = subchecksums[subdomain]
        local key = TrimText(subdomain)
        local checksumText = TrimText(checksum)
        if key ~= "" and checksumText ~= "" and not seen[string.lower(key)] then
          parts[#parts + 1] = key .. "=" .. checksumText
        end
      end
    end
    return table.concat(parts, ",")
  end

  DecodeProfileSyncSubchecks = function(domain, text)
    local decoded = {}
    local parentDomain = TrimText(domain)
    for token in string.gmatch(TrimText(text), "[^,%s]+") do
      local key, checksum = token:match("^([^=]+)=(.*)$")
      key = TrimText(key)
      checksum = TrimText(checksum)
      if key ~= "" and checksum ~= "" then
        local resolvedParent = type(GetLootProfileSubdomainParentDomain) == "function"
          and GetLootProfileSubdomainParentDomain(key)
          or ""
        if resolvedParent == "" or resolvedParent == parentDomain then
          decoded[key] = checksum
        end
      end
    end
    return decoded
  end

  local function BuildProfileSyncSubcheckMessageParts(domain, subchecksums, payloadFits)
    local encoded = EncodeProfileSyncSubchecks(domain, subchecksums)
    if encoded == "" then
      if type(payloadFits) == "function" then
        local accepted, reason = payloadFits("")
        if accepted ~= true then
          return nil, reason or "profile_subchecksum_state_envelope_exceeds_payload_limit"
        end
      end
      return { "" }
    end
    local parts = {}
    local current = ""
    local function CanUsePart(partPayload)
      if type(payloadFits) ~= "function" then
        return #partPayload <= profileSyncConfig.subcheckStateChunkLimit
      end
      local accepted, reason = payloadFits(partPayload)
      return accepted == true, reason
    end
    for token in string.gmatch(encoded, "[^,%s]+") do
      if current == "" then
        local tokenAccepted, tokenReason = CanUsePart(token)
        if not tokenAccepted then
          return nil, tokenReason or "profile_subchecksum_state_token_exceeds_payload_limit"
        end
        current = token
      else
        local candidate = current .. "," .. token
        local candidateAccepted = #candidate <= profileSyncConfig.subcheckStateChunkLimit
        if candidateAccepted then
          candidateAccepted = CanUsePart(candidate)
        end
        if candidateAccepted then
          current = candidate
        else
          local tokenAccepted, tokenReason = CanUsePart(token)
          if not tokenAccepted then
            return nil, tokenReason or "profile_subchecksum_state_token_exceeds_payload_limit"
          end
          parts[#parts + 1] = current
          current = token
        end
      end
    end
    if current ~= "" then
      parts[#parts + 1] = current
    end
    if #parts == 0 then
      parts[1] = ""
    end
    if #parts > profileSyncConfig.maxIncomingPreciseMultipartParts then
      return nil, "profile_subchecksum_state_part_limit_exceeded"
    end
    return parts
  end

  local function JoinProfileSyncSubcheckParts(parts, totalParts)
    local joined = {}
    totalParts = math.max(1, tonumber(totalParts) or 1)
    for index = 1, totalParts do
      local part = TrimText(type(parts) == "table" and parts[index] or "")
      if part ~= "" then
        joined[#joined + 1] = part
      end
    end
    return table.concat(joined, ",")
  end

  local function GetMemberSubchecksumSessionCache(sessionId, createIfMissing)
    local resolvedSessionId = string.lower(TrimText(sessionId))
    if resolvedSessionId == "" then
      return nil
    end
    local bucket = profileSyncCaches.memberSubchecksumBySession[resolvedSessionId]
    if not bucket and createIfMissing then
      bucket = {}
      profileSyncCaches.memberSubchecksumBySession[resolvedSessionId] = bucket
    end
    return bucket
  end

  local function GetPendingMemberSubchecksumSessionCache(sessionId, createIfMissing)
    local resolvedSessionId = string.lower(TrimText(sessionId))
    if resolvedSessionId == "" then
      return nil
    end
    local bucket = profileSyncCaches.pendingMemberSubchecksumPartsBySession[resolvedSessionId]
    if not bucket and createIfMissing then
      bucket = {}
      profileSyncCaches.pendingMemberSubchecksumPartsBySession[resolvedSessionId] = bucket
    end
    return bucket
  end

  local function RememberPendingMemberSubchecksumPayload(sessionId, memberKey, domain, token, partIndex, partTotal, payload)
    local receiveNow = GetNow()
    if type(profileSyncLocalOps.prunePendingPreciseMultipartPayloads) == "function"
      and (receiveNow - math.max(0, tonumber(profileSyncCaches.lastPreciseMultipartPruneAt) or 0))
        >= profileSyncConfig.pendingPreciseMultipartPruneIntervalSeconds
    then
      profileSyncCaches.lastPreciseMultipartPruneAt = receiveNow
      profileSyncLocalOps.prunePendingPreciseMultipartPayloads(receiveNow)
    end
    local sessionCache = GetPendingMemberSubchecksumSessionCache(sessionId, true)
    local resolvedMemberKey = string.lower(NormalizeCharacterKey(memberKey))
    local resolvedDomain = string.lower(TrimText(domain))
    local resolvedToken = TrimText(token)
    partIndex = math.max(1, tonumber(partIndex) or 1)
    partTotal = math.max(partIndex, tonumber(partTotal) or 1)
    if not sessionCache or resolvedMemberKey == "" or resolvedDomain == "" or resolvedToken == "" then
      return nil
    end

    if type(sessionCache[resolvedMemberKey]) ~= "table" then
      local pendingMemberCount = 0
      for _ in pairs(sessionCache) do
        pendingMemberCount = pendingMemberCount + 1
      end
      if pendingMemberCount >= profileSyncConfig.maxPendingPreciseMultipartMembers then
        return nil
      end
    end
    sessionCache[resolvedMemberKey] = sessionCache[resolvedMemberKey] or {}
    local bucket = sessionCache[resolvedMemberKey][resolvedDomain]
    if type(bucket) ~= "table" or bucket.token ~= resolvedToken or bucket.total ~= partTotal then
      bucket = {
        token = resolvedToken,
        total = partTotal,
        parts = {},
        receivedCount = 0,
        updatedAt = receiveNow,
      }
      sessionCache[resolvedMemberKey][resolvedDomain] = bucket
    end
    local complete, firstReceipt = INTERNAL_API.LIDCOUNCIL_RecordPreciseMultipartPart_Impl(
      bucket,
      partIndex,
      partTotal,
      TrimText(payload)
    )
    bucket.updatedAt = receiveNow
    if not complete then
      return nil, firstReceipt
    end

    local encoded = JoinProfileSyncSubcheckParts(bucket.parts, partTotal)
    sessionCache[resolvedMemberKey][resolvedDomain] = nil
    if not next(sessionCache[resolvedMemberKey]) then
      sessionCache[resolvedMemberKey] = nil
    end
    return encoded, firstReceipt
  end

  local function GetMemberSubchecksumState(sessionId, memberKey)
    local sessionCache = GetMemberSubchecksumSessionCache(sessionId, false)
    local resolvedMemberKey = string.lower(NormalizeCharacterKey(memberKey))
    if not sessionCache or resolvedMemberKey == "" then
      return nil
    end
    return sessionCache[resolvedMemberKey]
  end

  local function GetMemberItemHistoryDifferenceDiagnostics(sessionId, memberKey)
    local resolvedSessionId = string.lower(TrimText(sessionId))
    local resolvedMemberKey = string.lower(NormalizeCharacterKey(memberKey))
    local sessionCache = profileSyncCaches.itemHistoryDifferenceDiagnosticsBySession[resolvedSessionId]
    if resolvedSessionId == "" or resolvedMemberKey == "" or type(sessionCache) ~= "table" then
      return nil
    end
    return sessionCache[resolvedMemberKey]
  end

  local function GetMemberLootListDifferenceDiagnostics(sessionId, memberKey)
    local resolvedSessionId = string.lower(TrimText(sessionId))
    local resolvedMemberKey = string.lower(NormalizeCharacterKey(memberKey))
    local sessionCache = profileSyncCaches.lootListDifferenceDiagnosticsBySession[resolvedSessionId]
    if resolvedSessionId == "" or resolvedMemberKey == "" or type(sessionCache) ~= "table" then
      return nil
    end
    return sessionCache[resolvedMemberKey]
  end

  local function GetMemberSessionHistoryDifferenceDiagnostics(sessionId, memberKey)
    local resolvedSessionId = string.lower(TrimText(sessionId))
    local resolvedMemberKey = string.lower(NormalizeCharacterKey(memberKey))
    local sessionCache = profileSyncCaches.sessionHistoryDifferenceDiagnosticsBySession[resolvedSessionId]
    if resolvedSessionId == "" or resolvedMemberKey == "" or type(sessionCache) ~= "table" then
      return nil
    end
    return sessionCache[resolvedMemberKey]
  end

  local function RememberMemberSubchecksumState(sessionId, memberKey, profileName, profileId, domain, domainChecksum, subchecksums)
    local sessionCache = GetMemberSubchecksumSessionCache(sessionId, true)
    local resolvedMemberKey = string.lower(NormalizeCharacterKey(memberKey))
    local resolvedDomain = string.lower(TrimText(domain))
    if not sessionCache or resolvedMemberKey == "" or resolvedDomain == "" then
      return nil
    end
    local state = sessionCache[resolvedMemberKey]
    if type(state) ~= "table" then
      state = {
        byDomain = {},
      }
      sessionCache[resolvedMemberKey] = state
    end
    local previousSignature = profileSyncLocalOps.buildMemberSubchecksumStateSignature(state)
    state.profileName = FirstNonEmptyText(profileName, state.profileName)
    state.profileId = FirstNonEmptyText(profileId, state.profileId)
    state.updatedAt = GetNow()
    state.revisionSummary = CaptureSessionMemberRevisionSummary(sessionId, memberKey, state.profileName, state.profileId) or state.revisionSummary
    state.byDomain[resolvedDomain] = {
      checksum = TrimText(domainChecksum),
      subchecksums = DecodeProfileSyncSubchecks(resolvedDomain, EncodeProfileSyncSubchecks(resolvedDomain, subchecksums)),
      updatedAt = GetNow(),
      receivedAt = type(GetTime) == "function" and (tonumber(GetTime()) or 0) or GetNow(),
    }
    profileSyncLocalOps.persistSessionMemberBaseline(sessionId, memberKey, profileName)
    local updatedSignature = profileSyncLocalOps.buildMemberSubchecksumStateSignature(state)
    return state, previousSignature ~= updatedSignature
  end

  local function GetMemberPatchManifestSessionCache(sessionId, createIfMissing)
    local resolvedSessionId = string.lower(TrimText(sessionId))
    if resolvedSessionId == "" then
      return nil
    end
    local bucket = profileSyncCaches.memberPatchManifestBySession[resolvedSessionId]
    if not bucket and createIfMissing then
      bucket = {}
      profileSyncCaches.memberPatchManifestBySession[resolvedSessionId] = bucket
    end
    return bucket
  end

  local function GetPendingMemberPatchManifestSessionCache(sessionId, createIfMissing)
    local resolvedSessionId = string.lower(TrimText(sessionId))
    if resolvedSessionId == "" then
      return nil
    end
    local bucket = profileSyncCaches.pendingMemberPatchManifestPartsBySession[resolvedSessionId]
    if not bucket and createIfMissing then
      bucket = {}
      profileSyncCaches.pendingMemberPatchManifestPartsBySession[resolvedSessionId] = bucket
    end
    return bucket
  end

  local function RememberPendingMemberPatchManifestPayload(sessionId, memberKey, token, partIndex, partTotal, payload)
    local receiveNow = GetNow()
    if type(profileSyncLocalOps.prunePendingPreciseMultipartPayloads) == "function"
      and (receiveNow - math.max(0, tonumber(profileSyncCaches.lastPreciseMultipartPruneAt) or 0))
        >= profileSyncConfig.pendingPreciseMultipartPruneIntervalSeconds
    then
      profileSyncCaches.lastPreciseMultipartPruneAt = receiveNow
      profileSyncLocalOps.prunePendingPreciseMultipartPayloads(receiveNow)
    end
    local sessionCache = GetPendingMemberPatchManifestSessionCache(sessionId, true)
    local resolvedMemberKey = string.lower(NormalizeCharacterKey(memberKey))
    local resolvedToken = TrimText(token)
    partIndex = math.max(1, tonumber(partIndex) or 1)
    partTotal = math.max(partIndex, tonumber(partTotal) or 1)
    if not sessionCache or resolvedMemberKey == "" or resolvedToken == "" then
      return nil
    end

    if type(sessionCache[resolvedMemberKey]) ~= "table" then
      local pendingMemberCount = 0
      for _ in pairs(sessionCache) do
        pendingMemberCount = pendingMemberCount + 1
      end
      if pendingMemberCount >= profileSyncConfig.maxPendingPreciseMultipartMembers then
        return nil
      end
    end
    local bucket = sessionCache[resolvedMemberKey]
    if type(bucket) ~= "table" or bucket.token ~= resolvedToken or bucket.total ~= partTotal then
      bucket = {
        token = resolvedToken,
        total = partTotal,
        parts = {},
        receivedCount = 0,
        updatedAt = receiveNow,
      }
      sessionCache[resolvedMemberKey] = bucket
    end
    local complete = INTERNAL_API.LIDCOUNCIL_RecordPreciseMultipartPart_Impl(
      bucket,
      partIndex,
      partTotal,
      tostring(payload or "")
    )
    bucket.updatedAt = receiveNow
    if not complete then
      return nil
    end

    local combined = table.concat(bucket.parts)
    sessionCache[resolvedMemberKey] = nil
    return combined
  end

  profileSyncLocalOps.prunePendingPreciseMultipartPayloads = function(now)
    local cutoff = math.max(0, tonumber(now) or GetNow()) - profileSyncConfig.pendingPreciseMultipartTtlSeconds
    for sessionId, sessionCache in pairs(profileSyncCaches.pendingMemberSubchecksumPartsBySession) do
      if type(sessionCache) == "table" then
        for memberKey, memberCache in pairs(sessionCache) do
          if type(memberCache) == "table" then
            for domain, bucket in pairs(memberCache) do
              local updatedAt = math.max(0, tonumber(type(bucket) == "table" and bucket.updatedAt or 0) or 0)
              if updatedAt <= 0 or updatedAt < cutoff then
                memberCache[domain] = nil
              end
            end
            if not next(memberCache) then
              sessionCache[memberKey] = nil
            end
          else
            sessionCache[memberKey] = nil
          end
        end
        if not next(sessionCache) then
          profileSyncCaches.pendingMemberSubchecksumPartsBySession[sessionId] = nil
        end
      end
    end
    for sessionId, sessionCache in pairs(profileSyncCaches.pendingMemberPatchManifestPartsBySession) do
      if type(sessionCache) == "table" then
        for memberKey, bucket in pairs(sessionCache) do
          local updatedAt = math.max(0, tonumber(type(bucket) == "table" and bucket.updatedAt or 0) or 0)
          if updatedAt <= 0 or updatedAt < cutoff then
            sessionCache[memberKey] = nil
          end
        end
        if not next(sessionCache) then
          profileSyncCaches.pendingMemberPatchManifestPartsBySession[sessionId] = nil
        end
      end
    end
  end

  local function GetMemberPatchManifestState(sessionId, memberKey)
    local sessionCache = GetMemberPatchManifestSessionCache(sessionId, false)
    local resolvedMemberKey = string.lower(NormalizeCharacterKey(memberKey))
    if not sessionCache or resolvedMemberKey == "" then
      return nil
    end
    return sessionCache[resolvedMemberKey]
  end

  local function RememberMemberPatchManifestState(sessionId, memberKey, profileName, profileId, manifestSummary, manifestToken)
    local sessionCache = GetMemberPatchManifestSessionCache(sessionId, true)
    local resolvedMemberKey = string.lower(NormalizeCharacterKey(memberKey))
    manifestSummary = type(manifestSummary) == "table" and manifestSummary or {}
    if not sessionCache or resolvedMemberKey == "" then
      return nil
    end

    local state = sessionCache[resolvedMemberKey]
    if type(state) ~= "table" then
      state = {
        bySubdomain = {},
        subdomainUpdatedAt = {},
      }
      sessionCache[resolvedMemberKey] = state
    end
    local previousSignature = profileSyncLocalOps.buildMemberPatchManifestStateSignature(state)
    state.profileName = FirstNonEmptyText(profileName, manifestSummary.profileName, state.profileName)
    state.profileId = FirstNonEmptyText(profileId, manifestSummary.profileId, state.profileId)
    state.token = TrimText(manifestToken) ~= "" and TrimText(manifestToken) or state.token
    state.updatedAt = GetNow()
    state.revisionSummary = CaptureSessionMemberRevisionSummary(sessionId, memberKey, state.profileName, state.profileId) or state.revisionSummary
    state.scopeDomains = ResolveProfileRevisionDomainList(manifestSummary.scopeDomains)
    state.scopeSubdomains = CloneProfileSyncSubdomainList(manifestSummary.scopeSubdomains)
    for _, subdomain in ipairs(state.scopeSubdomains) do
      if type(manifestSummary.detailsBySubdomain) == "table" and type(manifestSummary.detailsBySubdomain[subdomain]) == "table" then
        state.bySubdomain[subdomain] = manifestSummary.detailsBySubdomain[subdomain]
        state.subdomainUpdatedAt = type(state.subdomainUpdatedAt) == "table" and state.subdomainUpdatedAt or {}
        state.subdomainUpdatedAt[subdomain] = GetNow()
      end
    end
    profileSyncLocalOps.persistSessionMemberBaseline(sessionId, memberKey, state.profileName)
    local updatedSignature = profileSyncLocalOps.buildMemberPatchManifestStateSignature(state)
    return state, previousSignature ~= updatedSignature
  end

  local function InvalidateMemberPreciseSyncState(sessionId, memberKey, opts)
    opts = type(opts) == "table" and opts or {}
    local resolvedSessionId = string.lower(TrimText(sessionId))
    local resolvedMemberKey = string.lower(NormalizeCharacterKey(memberKey))
    if resolvedSessionId == "" or resolvedMemberKey == "" then
      return false
    end

    local scopedDomains = ResolveProfileRevisionDomainList(opts.domains)
    local scopedSubdomains = CloneProfileSyncSubdomainList(opts.subdomains)
    local scopedDomainLookup = {}
    local scopedSubdomainLookup = {}
    for _, domain in ipairs(scopedDomains) do
      scopedDomainLookup[string.lower(TrimText(domain))] = true
    end
    for _, subdomain in ipairs(scopedSubdomains) do
      local resolvedSubdomain = string.lower(TrimText(subdomain))
      if resolvedSubdomain ~= "" then
        scopedSubdomainLookup[resolvedSubdomain] = true
        local parentDomain = type(GetLootProfileSubdomainParentDomain) == "function"
          and string.lower(TrimText(GetLootProfileSubdomainParentDomain(subdomain)))
          or ""
        if parentDomain ~= "" then
          scopedDomainLookup[parentDomain] = true
        end
      end
    end
    local scoped = next(scopedDomainLookup) ~= nil
    local hasExplicitSubdomains = next(scopedSubdomainLookup) ~= nil
    if not scoped or scopedDomainLookup.session == true then
      local diagnosticCache = profileSyncCaches.itemHistoryDifferenceDiagnosticsBySession[resolvedSessionId]
      if type(diagnosticCache) == "table" then
        diagnosticCache[resolvedMemberKey] = nil
        if not next(diagnosticCache) then
          profileSyncCaches.itemHistoryDifferenceDiagnosticsBySession[resolvedSessionId] = nil
        end
      end
      diagnosticCache = profileSyncCaches.sessionHistoryDifferenceDiagnosticsBySession[resolvedSessionId]
      if type(diagnosticCache) == "table" then
        diagnosticCache[resolvedMemberKey] = nil
        if not next(diagnosticCache) then
          profileSyncCaches.sessionHistoryDifferenceDiagnosticsBySession[resolvedSessionId] = nil
        end
      end
    end
    if not scoped or scopedDomainLookup.loot == true then
      local diagnosticCache = profileSyncCaches.lootListDifferenceDiagnosticsBySession[resolvedSessionId]
      if type(diagnosticCache) == "table" then
        diagnosticCache[resolvedMemberKey] = nil
        if not next(diagnosticCache) then
          profileSyncCaches.lootListDifferenceDiagnosticsBySession[resolvedSessionId] = nil
        end
      end
    end
    local function RefreshRetainedStateRevision(state)
      if type(state) ~= "table" then
        return
      end
      local revisionSummary = type(opts.revisionSummary) == "table"
        and NormalizeRevisionSummary(opts.revisionSummary, state.profileName, state.profileId)
        or CaptureSessionMemberRevisionSummary(sessionId, memberKey, state.profileName, state.profileId)
      if type(revisionSummary) == "table" then
        state.revisionSummary = revisionSummary
      end
      state.updatedAt = GetNow()
    end

    local removed = false
    local subchecksumCache = profileSyncCaches.memberSubchecksumBySession[resolvedSessionId]
    local subchecksumState = type(subchecksumCache) == "table" and subchecksumCache[resolvedMemberKey] or nil
    if type(subchecksumState) == "table" then
      if not scoped then
        subchecksumCache[resolvedMemberKey] = nil
        removed = true
      elseif type(subchecksumState.byDomain) == "table" then
        for domain in pairs(scopedDomainLookup) do
          if subchecksumState.byDomain[domain] ~= nil then
            subchecksumState.byDomain[domain] = nil
            removed = true
          end
        end
        if not next(subchecksumState.byDomain) then
          subchecksumCache[resolvedMemberKey] = nil
        else
          RefreshRetainedStateRevision(subchecksumState)
        end
      end
    end
    local pendingSubchecksumCache = profileSyncCaches.pendingMemberSubchecksumPartsBySession[resolvedSessionId]
    if type(pendingSubchecksumCache) == "table" and pendingSubchecksumCache[resolvedMemberKey] ~= nil then
      pendingSubchecksumCache[resolvedMemberKey] = nil
      removed = true
    end
    local patchManifestCache = profileSyncCaches.memberPatchManifestBySession[resolvedSessionId]
    local patchManifestState = type(patchManifestCache) == "table" and patchManifestCache[resolvedMemberKey] or nil
    if type(patchManifestState) == "table" then
      if not scoped then
        patchManifestCache[resolvedMemberKey] = nil
        removed = true
      elseif type(patchManifestState.bySubdomain) == "table" then
        for subdomain in pairs(patchManifestState.bySubdomain) do
          local resolvedSubdomain = string.lower(TrimText(subdomain))
          local parentDomain = type(GetLootProfileSubdomainParentDomain) == "function"
            and string.lower(TrimText(GetLootProfileSubdomainParentDomain(subdomain)))
            or ""
          if (hasExplicitSubdomains and scopedSubdomainLookup[resolvedSubdomain] == true)
            or (not hasExplicitSubdomains and scopedDomainLookup[parentDomain] == true)
          then
            patchManifestState.bySubdomain[subdomain] = nil
            if type(patchManifestState.subdomainUpdatedAt) == "table" then
              patchManifestState.subdomainUpdatedAt[subdomain] = nil
            end
            removed = true
          end
        end
        if not next(patchManifestState.bySubdomain) then
          patchManifestCache[resolvedMemberKey] = nil
        else
          local retainedSubdomains = {}
          local retainedDomains = {}
          for subdomain in pairs(patchManifestState.bySubdomain) do
            retainedSubdomains[#retainedSubdomains + 1] = subdomain
            local parentDomain = type(GetLootProfileSubdomainParentDomain) == "function"
              and string.lower(TrimText(GetLootProfileSubdomainParentDomain(subdomain)))
              or ""
            if parentDomain ~= "" then
              retainedDomains[#retainedDomains + 1] = parentDomain
            end
          end
          table.sort(retainedSubdomains, function(left, right)
            return string.lower(TrimText(left)) < string.lower(TrimText(right))
          end)
          patchManifestState.scopeSubdomains = CloneProfileSyncSubdomainList(retainedSubdomains)
          patchManifestState.scopeDomains = ResolveProfileRevisionDomainList(retainedDomains)
          RefreshRetainedStateRevision(patchManifestState)
        end
      end
    end
    local pendingPatchManifestCache = profileSyncCaches.pendingMemberPatchManifestPartsBySession[resolvedSessionId]
    if type(pendingPatchManifestCache) == "table" and pendingPatchManifestCache[resolvedMemberKey] ~= nil then
      pendingPatchManifestCache[resolvedMemberKey] = nil
      removed = true
    end

    local requestPrefix = resolvedSessionId .. "|" .. resolvedMemberKey .. "|"
    for stamp in pairs(profileSyncCaches.recentSubchecksumRequests) do
      if stamp:sub(1, #requestPrefix) == requestPrefix then
        profileSyncCaches.recentSubchecksumRequests[stamp] = nil
        removed = true
      end
    end
    for stamp in pairs(profileSyncCaches.recentPatchManifestRequests) do
      if stamp:sub(1, #requestPrefix) == requestPrefix then
        profileSyncCaches.recentPatchManifestRequests[stamp] = nil
        removed = true
      end
    end
    for stamp in pairs(profileSyncCaches.patchManifestRequestTokensByStamp) do
      if stamp:sub(1, #requestPrefix) == requestPrefix then
        profileSyncCaches.patchManifestRequestTokensByStamp[stamp] = nil
        removed = true
      end
    end

    local preciseRequestKey = profileSyncLocalOps.buildSubchecksumRequestQueueKey(sessionId, memberKey)
    if profileSyncCaches.preciseSubchecksumRequestStateByMember[preciseRequestKey] ~= nil then
      profileSyncCaches.preciseSubchecksumRequestStateByMember[preciseRequestKey] = nil
      removed = true
    end

    local detailConflict = type(profileSyncRuntimeState.detailConflict) == "table" and profileSyncRuntimeState.detailConflict or nil
    local shouldClearDetailConflict = not scoped
    if scoped and type(detailConflict) == "table" then
      local conflictDomains = ResolveProfileRevisionDomainList(detailConflict.scopeDomains)
      if #conflictDomains == 0 then
        shouldClearDetailConflict = true
      else
        for _, domain in ipairs(conflictDomains) do
          if scopedDomainLookup[string.lower(TrimText(domain))] == true then
            shouldClearDetailConflict = true
            break
          end
        end
      end
    end
    if shouldClearDetailConflict and type(detailConflict) == "table"
      and string.lower(TrimText(profileSyncRuntimeState.sessionId)) == resolvedSessionId
      and string.lower(NormalizeCharacterKey(detailConflict.memberKey)) == resolvedMemberKey
    then
      ClearRuntimePreviewConflictState()
      removed = true
    end
    return removed
  end

  profileSyncLocalOps.pruneExpiredMemberPreciseStates = function(now)
    local cutoff = math.max(0, tonumber(now) or GetNow()) - profileSyncConfig.preciseMemberStateTtlSeconds
    local removedDomains = 0
    local removedSubdomains = 0
    for sessionId, sessionCache in pairs(profileSyncCaches.memberSubchecksumBySession) do
      if type(sessionCache) == "table" then
        for memberKey, state in pairs(sessionCache) do
          if type(state) == "table" and type(state.byDomain) == "table" then
            for domain, domainState in pairs(state.byDomain) do
              local updatedAt = math.max(0, tonumber(type(domainState) == "table" and domainState.updatedAt or 0) or 0)
              if updatedAt <= 0 or updatedAt < cutoff then
                state.byDomain[domain] = nil
                removedDomains = removedDomains + 1
              end
            end
            if not next(state.byDomain) then
              sessionCache[memberKey] = nil
            end
          else
            sessionCache[memberKey] = nil
          end
        end
        if not next(sessionCache) then
          profileSyncCaches.memberSubchecksumBySession[sessionId] = nil
        end
      end
    end
    for sessionId, sessionCache in pairs(profileSyncCaches.memberPatchManifestBySession) do
      if type(sessionCache) == "table" then
        for memberKey, state in pairs(sessionCache) do
          if type(state) == "table" and type(state.bySubdomain) == "table" then
            state.subdomainUpdatedAt = type(state.subdomainUpdatedAt) == "table" and state.subdomainUpdatedAt or {}
            for subdomain in pairs(state.bySubdomain) do
              local updatedAt = math.max(0, tonumber(state.subdomainUpdatedAt[subdomain] or state.updatedAt) or 0)
              if updatedAt <= 0 or updatedAt < cutoff then
                state.bySubdomain[subdomain] = nil
                state.subdomainUpdatedAt[subdomain] = nil
                removedSubdomains = removedSubdomains + 1
              end
            end
            if not next(state.bySubdomain) then
              sessionCache[memberKey] = nil
            else
              local retainedSubdomains = {}
              local retainedDomains = {}
              for subdomain in pairs(state.bySubdomain) do
                retainedSubdomains[#retainedSubdomains + 1] = subdomain
                local parentDomain = type(GetLootProfileSubdomainParentDomain) == "function"
                  and string.lower(TrimText(GetLootProfileSubdomainParentDomain(subdomain)))
                  or ""
                if parentDomain ~= "" then
                  retainedDomains[#retainedDomains + 1] = parentDomain
                end
              end
              table.sort(retainedSubdomains, function(left, right)
                return string.lower(TrimText(left)) < string.lower(TrimText(right))
              end)
              state.scopeSubdomains = CloneProfileSyncSubdomainList(retainedSubdomains)
              state.scopeDomains = ResolveProfileRevisionDomainList(retainedDomains)
            end
          else
            sessionCache[memberKey] = nil
          end
        end
        if not next(sessionCache) then
          profileSyncCaches.memberPatchManifestBySession[sessionId] = nil
        end
      end
    end
    return removedDomains, removedSubdomains
  end

  local function EnsureCurrentMemberPreciseSyncState(sessionId, memberKey, revisionSummary)
    local normalizedSummary = NormalizeRevisionSummary(revisionSummary, "", "")
    local subchecksumState = GetMemberSubchecksumState(sessionId, memberKey)
    local patchManifestState = GetMemberPatchManifestState(sessionId, memberKey)
    local changedDomains = {}
    local requiresFullInvalidation = false
    local function CollectChangedDomains(state)
      if type(state) ~= "table" or type(state.revisionSummary) ~= "table"
        or DoRevisionSummariesMatch(state.revisionSummary, normalizedSummary, PROFILE_REVISION_DOMAINS)
      then
        return
      end
      local cachedSummary = NormalizeRevisionSummary(state.revisionSummary, "", "")
      if cachedSummary.profileId ~= "" and normalizedSummary.profileId ~= ""
        and string.lower(cachedSummary.profileId) ~= string.lower(normalizedSummary.profileId)
      then
        requiresFullInvalidation = true
        return
      end
      for _, domain in ipairs(PROFILE_REVISION_DOMAINS) do
        if not DoRevisionSummariesMatch(cachedSummary, normalizedSummary, { domain }) then
          changedDomains[#changedDomains + 1] = domain
        end
      end
    end
    CollectChangedDomains(subchecksumState)
    CollectChangedDomains(patchManifestState)
    if requiresFullInvalidation then
      return InvalidateMemberPreciseSyncState(sessionId, memberKey)
    end
    if #changedDomains > 0 then
      return InvalidateMemberPreciseSyncState(sessionId, memberKey, {
        domains = changedDomains,
        revisionSummary = normalizedSummary,
      })
    end
    return false
  end

  local function BuildRemoteMemberRevisionSummary(profileName, member)
    member = type(member) == "table" and member or {}
    return NormalizeRevisionSummary({
      profileName = TrimText(profileName),
      profileId = TrimText(member.sharedProfileId),
      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,
    }, profileName, TrimText(member.sharedProfileId))
  end

  profileSyncLocalOps.persistSessionMemberBaseline = function(sessionId, memberKey, profileName)
    if type(deps.RememberPersistedMemberBaseline) ~= "function" then
      return false
    end
    local activeSession, activeProfileName = GetActiveLootSession()
    local resolvedSessionId = TrimText(sessionId)
    local resolvedProfileName = FirstNonEmptyText(profileName, activeProfileName)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if type(activeSession) ~= "table" or TrimText(activeSession.id) ~= resolvedSessionId or resolvedProfileName == "" or resolvedMemberKey == "" then
      return false
    end
    local localProfileId = TrimText(select(1, GetLootProfileId(resolvedProfileName)) or "")
    local member = type(activeSession.members) == "table" and activeSession.members[resolvedMemberKey] or nil
    if localProfileId == "" or type(member) ~= "table" then
      return false
    end
    return deps.RememberPersistedMemberBaseline(
      localProfileId,
      resolvedMemberKey,
      BuildRemoteMemberRevisionSummary(resolvedProfileName, member),
      GetMemberSubchecksumState(resolvedSessionId, resolvedMemberKey),
      GetMemberPatchManifestState(resolvedSessionId, resolvedMemberKey)
    )
  end

  local function HydratePersistedSessionMemberBaseline(sessionId, localProfileId, profileName, memberKey, revisionSummary)
    if type(deps.GetPersistedMemberBaseline) ~= "function" then
      return nil
    end
    local resolvedSessionId = TrimText(sessionId)
    local resolvedLocalProfileId = TrimText(localProfileId)
    local resolvedProfileName = TrimText(profileName)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if resolvedSessionId == "" or resolvedLocalProfileId == "" or resolvedProfileName == "" or resolvedMemberKey == "" then
      return nil
    end
    local hasSubchecksumState = type(GetMemberSubchecksumState(resolvedSessionId, resolvedMemberKey)) == "table"
    local hasPatchManifestState = type(GetMemberPatchManifestState(resolvedSessionId, resolvedMemberKey)) == "table"
    if hasSubchecksumState and hasPatchManifestState then
      return nil
    end
    local persisted = deps.GetPersistedMemberBaseline(resolvedLocalProfileId, resolvedMemberKey, revisionSummary)
    if type(persisted) ~= "table" then
      return nil
    end
    local persistedProfileId = TrimText(type(persisted.revisionSummary) == "table" and persisted.revisionSummary.profileId or "")
    if not hasSubchecksumState and type(persisted.subchecksumState) == "table" and type(persisted.subchecksumState.byDomain) == "table" then
      for domain, domainState in pairs(persisted.subchecksumState.byDomain) do
        if type(domainState) == "table" then
          RememberMemberSubchecksumState(
            resolvedSessionId,
            resolvedMemberKey,
            resolvedProfileName,
            persistedProfileId,
            domain,
            TrimText(domainState.checksum),
            type(domainState.subchecksums) == "table" and domainState.subchecksums or {}
          )
        end
      end
    end
    if not hasPatchManifestState and type(persisted.patchManifestState) == "table" then
      RememberMemberPatchManifestState(
        resolvedSessionId,
        resolvedMemberKey,
        resolvedProfileName,
        persistedProfileId,
        persisted.patchManifestState,
        TrimText(persisted.patchManifestState.token)
      )
    end
    return persisted
  end

  profileSyncLocalOps.buildCandidateVisibleState = function(candidate)
    candidate = type(candidate) == "table" and candidate or {}
    local effectiveComparison = string.lower(TrimText(candidate.effectiveComparison ~= "" and candidate.effectiveComparison or candidate.comparison))
    if string.upper(TrimText(candidate.applyAckPhase)) == "QUEUED" then
      return "waiting_apply"
    end
    if candidate.generationConverged and effectiveComparison == "same" then
      return "converged"
    end
    if candidate.backgroundOnlyLootDifference and effectiveComparison == "same" then
      return "background"
    end
    if effectiveComparison == "same" then
      return "aligned"
    elseif effectiveComparison == "local_newer" then
      return "host_newer"
    elseif effectiveComparison == "remote_newer" then
      return "member_newer"
    elseif effectiveComparison == "diverged" then
      return "conflict"
    elseif effectiveComparison == "different_lineage" then
      return "lineage"
    end
    return "unknown"
  end

  profileSyncLocalOps.buildCandidateSafeRecommendation = function(candidate)
    candidate = type(candidate) == "table" and candidate or {}
    local effectiveComparison = string.lower(TrimText(candidate.effectiveComparison ~= "" and candidate.effectiveComparison or candidate.comparison))
    local visibleState = string.lower(TrimText(candidate.visibleState))
    local effectiveRemoteNewerDomains = CloneProfileSyncDomainList(
      type(candidate.effectiveRemoteNewerDomains) == "table" and candidate.effectiveRemoteNewerDomains or candidate.remoteNewerDomains
    )
    local effectiveLocalNewerDomains = CloneProfileSyncDomainList(
      type(candidate.effectiveLocalNewerDomains) == "table" and candidate.effectiveLocalNewerDomains or candidate.localNewerDomains
    )
    local effectiveHostRepairDomains = CloneProfileSyncDomainList(
      type(candidate.effectiveHostRepairDomains) == "table" and candidate.effectiveHostRepairDomains or candidate.hostRepairDomains
    )
    local effectiveMemberRepairDomains = CloneProfileSyncDomainList(
      type(candidate.effectiveMemberRepairDomains) == "table" and candidate.effectiveMemberRepairDomains or candidate.memberRepairDomains
    )
    if visibleState == "waiting_apply" then
      return {
        action = "none",
        label = "Waiting for Combat",
        reason = "The member received this update and will apply it after combat ends.",
      }
    end
    if visibleState == "converged" then
      return {
        action = "none",
        label = "Converged",
        reason = "The newest live repair was already acknowledged by this member. Visible sync state is following the latest applied generation.",
      }
    end
    if visibleState == "background" then
      return {
        action = "none",
        label = "Background Sync",
        reason = "Current live loot and roll-ready data are aligned. Only archive or fun-award history is still syncing in the background.",
      }
    end
    if visibleState == "aligned" or effectiveComparison == "same" then
      return {
        action = "none",
        label = "No Action",
        reason = "The host and member shared copies are already aligned.",
      }
    elseif visibleState == "host_newer" or effectiveComparison == "local_newer" then
      return {
        action = "push",
        label = "Recommended: Push",
        reason = candidate.precisePushReady
          and "The host is newer and precise safe scopes are loaded."
          or "The host is newer; a broader host repair is currently the safe action.",
        domains = effectiveHostRepairDomains,
        subdomains = CloneProfileSyncSubdomainList(candidate.precisePushReady and candidate.precisePushSubdomains or {}),
      }
    elseif visibleState == "member_newer" or effectiveComparison == "remote_newer" then
      return {
        action = "pull",
        label = "Recommended: Pull",
        reason = candidate.precisePullReady
          and "The member is newer and precise safe scopes are loaded."
          or "The member is newer; request their shared copy back to the host.",
        domains = effectiveMemberRepairDomains,
        subdomains = CloneProfileSyncSubdomainList(candidate.precisePullReady and candidate.precisePullSubdomains or {}),
      }
    elseif visibleState == "conflict" or effectiveComparison == "diverged" then
      return {
        action = "preview",
        label = "Recommended: Preview",
        reason = "Both sides changed data. Preview first and resolve only the scopes you actually want.",
        domains = MergeProfileRevisionDomains(effectiveRemoteNewerDomains, effectiveLocalNewerDomains),
        subdomains = CloneProfileSyncSubdomainList(candidate.precisePreviewReady and candidate.precisePreviewSubdomains or {}),
      }
    elseif visibleState == "lineage" or effectiveComparison == "different_lineage" then
      return {
        action = "check",
        label = "Review Lineage",
        reason = "The joined member is on a different shared profile lineage. Use a full repair only if that overwrite is intentional.",
      }
    end
    return {
      action = "check",
      label = "Check Differences",
      reason = "More detailed comparison is needed before a safe repair can be chosen.",
    }
  end

  profileSyncLocalOps.buildCandidatePreciseDiffInfo = function(candidate, localManifest, remoteManifest)
    candidate = type(candidate) == "table" and candidate or {}
    local result = {
      scopeDomains = {},
      byDomain = {},
      differentSubdomains = {},
      differentSubdomainsByDomain = {},
      pushSubdomains = {},
      pullSubdomains = {},
      previewSubdomains = {},
    }
    if type(localManifest) ~= "table" or type(remoteManifest) ~= "table" or type(remoteManifest.byDomain) ~= "table" then
      return result
    end
    local comparison = string.lower(TrimText(candidate.comparison))
    if comparison == "different_lineage" or comparison == "unknown" then
      return result
    end

    local candidateChecksumByDomain = {
      settings = TrimText(candidate.settingsChecksum),
      permissions = TrimText(candidate.permissionsChecksum),
      loot = TrimText(candidate.lootChecksum ~= "" and candidate.lootChecksum or candidate.operationalChecksum),
      session = TrimText(candidate.sessionChecksum ~= "" and candidate.sessionChecksum or candidate.operationalChecksum),
    }
    local localChecksums = type(localManifest.checksums) == "table" and localManifest.checksums or {}
    local mergedDomains = MergeProfileRevisionDomains(candidate.remoteNewerDomains, candidate.localNewerDomains)

    for _, domain in ipairs(mergedDomains) do
      local remoteDomain = type(remoteManifest.byDomain[domain]) == "table" and remoteManifest.byDomain[domain] or nil
      local remoteDomainChecksum = TrimText(remoteDomain and remoteDomain.checksum or "")
      if remoteDomainChecksum ~= "" and remoteDomainChecksum == candidateChecksumByDomain[domain] then
        local changed = {}
        local subchecksums = type(remoteDomain.subchecksums) == "table" and remoteDomain.subchecksums or {}
        local comparedSubdomains = {}
        for subdomainKey, _ in pairs(localChecksums) do
          if type(GetLootProfileSubdomainParentDomain) == "function" and GetLootProfileSubdomainParentDomain(subdomainKey) == domain then
            comparedSubdomains[subdomainKey] = true
          end
        end
        for subdomainKey in pairs(subchecksums) do
          if type(GetLootProfileSubdomainParentDomain) == "function" and GetLootProfileSubdomainParentDomain(subdomainKey) == domain then
            comparedSubdomains[subdomainKey] = true
          end
        end
        local orderedSubdomains = {}
        for subdomainKey in pairs(comparedSubdomains) do
          orderedSubdomains[#orderedSubdomains + 1] = subdomainKey
        end
        table.sort(orderedSubdomains, function(left, right)
          local leftLabel = type(GetLootProfileSubdomainLabel) == "function" and GetLootProfileSubdomainLabel(left) or left
          local rightLabel = type(GetLootProfileSubdomainLabel) == "function" and GetLootProfileSubdomainLabel(right) or right
          if string.lower(tostring(leftLabel)) == string.lower(tostring(rightLabel)) then
            return tostring(left) < tostring(right)
          end
          return string.lower(tostring(leftLabel)) < string.lower(tostring(rightLabel))
        end)
        for _, subdomain in ipairs(orderedSubdomains) do
          local localChecksum = TrimText(localChecksums[subdomain])
          local remoteChecksum = TrimText(subchecksums[subdomain])
          if localChecksum ~= remoteChecksum and (localChecksum ~= "" or remoteChecksum ~= "") then
            changed[#changed + 1] = subdomain
            result.differentSubdomains[#result.differentSubdomains + 1] = subdomain
          end
        end
        if #changed > 0 then
          result.scopeDomains[#result.scopeDomains + 1] = domain
          result.byDomain[domain] = {
            domain = domain,
            subdomains = CloneProfileSyncSubdomainList(changed),
            text = "",
          }
          result.differentSubdomainsByDomain[domain] = CloneProfileSyncSubdomainList(changed)
          local labels = {}
          for _, subdomain in ipairs(changed) do
            labels[#labels + 1] = type(GetLootProfileSubdomainLabel) == "function"
              and GetLootProfileSubdomainLabel(subdomain)
              or subdomain
          end
          result.byDomain[domain].text = table.concat(labels, ", ")
        end
      end
    end

    for _, domain in ipairs(candidate.localNewerDomains or {}) do
      for _, subdomain in ipairs(result.differentSubdomainsByDomain[domain] or {}) do
        result.pushSubdomains[#result.pushSubdomains + 1] = subdomain
      end
    end
    for _, domain in ipairs(candidate.remoteNewerDomains or {}) do
      for _, subdomain in ipairs(result.differentSubdomainsByDomain[domain] or {}) do
        result.pullSubdomains[#result.pullSubdomains + 1] = subdomain
      end
    end
    result.previewSubdomains = CloneProfileSyncSubdomainList(result.differentSubdomains)
    return result
  end

  profileSyncLocalOps.buildFilteredCandidateDomains = function(primaryDomains, blockedDomains)
    local filtered = {}
    local blocked = {}
    for _, domain in ipairs(type(blockedDomains) == "table" and blockedDomains or {}) do
      blocked[string.lower(TrimText(domain))] = true
    end
    for _, domain in ipairs(type(primaryDomains) == "table" and primaryDomains or {}) do
      local key = string.lower(TrimText(domain))
      if key ~= "" and not blocked[key] then
        filtered[#filtered + 1] = key
      end
    end
    return filtered
  end

  profileSyncLocalOps.hasPreciseCoverageForDomains = function(domains, preciseByDomain)
    domains = type(domains) == "table" and domains or {}
    preciseByDomain = type(preciseByDomain) == "table" and preciseByDomain or {}
    if #domains == 0 then
      return false
    end
    for _, domain in ipairs(domains) do
      if type(preciseByDomain[domain]) ~= "table" or #(preciseByDomain[domain] or {}) == 0 then
        return false
      end
    end
    return true
  end

  profileSyncLocalOps.buildPatchManifestRequestParts = function(sessionId, profileName, profileId, subdomains, requestToken)
    local normalized = type(FilterLootProfilePatchCapableSubdomains) == "function"
      and FilterLootProfilePatchCapableSubdomains(subdomains)
      or CloneProfileSyncSubdomainList(subdomains)
    if #normalized == 0 then
      return {}
    end

    local parts = {}
    local current = ""
    for _, subdomain in ipairs(normalized) do
      local candidate = current == "" and subdomain or (current .. "," .. subdomain)
      local fits = (#candidate <= profileSyncConfig.patchManifestRequestLimit)
      local fitReason = nil
      if type(sessionRuntimeOps.validateCommPayload) == "function" then
        -- Scope IDs are comma-delimited protocol values. Validate each whole
        -- CSV group against the final escaped envelope; never split an ID.
        fits, fitReason = sessionRuntimeOps.validateCommPayload(
          "PSUBPATCH_REQ",
          TrimText(sessionId),
          TrimText(profileName),
          TrimText(profileId),
          candidate,
          TrimText(requestToken)
        )
      end
      if fits then
        current = candidate
      elseif current ~= "" then
        parts[#parts + 1] = current
        local singleFits, singleReason = true, nil
        if type(sessionRuntimeOps.validateCommPayload) == "function" then
          singleFits, singleReason = sessionRuntimeOps.validateCommPayload(
            "PSUBPATCH_REQ",
            TrimText(sessionId),
            TrimText(profileName),
            TrimText(profileId),
            subdomain,
            TrimText(requestToken)
          )
        end
        if not singleFits then
          return {}, singleReason or "patch_manifest_request_scope_exceeds_limit"
        end
        current = subdomain
      else
        return {}, fitReason or "patch_manifest_request_scope_exceeds_limit"
      end
    end
    if current ~= "" then
      parts[#parts + 1] = current
    end
    return parts
  end

  profileSyncLocalOps.mergePatchManifestRequestSubdomains = function(...)
    local merged = {}
    local seen = {}
    for index = 1, select("#", ...) do
      local normalized = type(FilterLootProfilePatchCapableSubdomains) == "function"
        and FilterLootProfilePatchCapableSubdomains(select(index, ...))
        or CloneProfileSyncSubdomainList(select(index, ...))
      for _, subdomain in ipairs(normalized) do
        if not seen[subdomain] then
          seen[subdomain] = true
          merged[#merged + 1] = subdomain
        end
      end
    end
    return merged
  end

  profileSyncLocalOps.pruneLoadedSubchecksumDomains = function(sessionId, memberKey, domains)
    local state = GetMemberSubchecksumState(sessionId, memberKey)
    local unresolved = {}
    local byDomain = type(state) == "table" and type(state.byDomain) == "table" and state.byDomain or nil
    for _, domain in ipairs(ResolveProfileRevisionDomainList(domains)) do
      if type(byDomain) ~= "table" or type(byDomain[domain]) ~= "table" then
        unresolved[#unresolved + 1] = domain
      end
    end
    return unresolved
  end

  profileSyncLocalOps.getMemberSubchecksumFreshness = function(sessionId, memberKey, domains, requestedAt)
    local resolvedDomains = ResolveProfileRevisionDomainList(domains)
    local state = GetMemberSubchecksumState(sessionId, memberKey)
    local byDomain = type(state) == "table" and type(state.byDomain) == "table" and state.byDomain or {}
    local requiredAt = math.max(0, tonumber(requestedAt) or 0)
    local loadedCount = 0
    local freshCount = 0
    local staleDomains = {}
    for _, domain in ipairs(resolvedDomains) do
      local domainState = type(byDomain) == "table" and byDomain[domain] or nil
      if type(domainState) == "table" then
        loadedCount = loadedCount + 1
        local receivedAt = math.max(0, tonumber(domainState.receivedAt or domainState.updatedAt) or 0)
        if requiredAt <= 0 or receivedAt >= requiredAt then
          freshCount = freshCount + 1
        else
          staleDomains[#staleDomains + 1] = domain
        end
      else
        staleDomains[#staleDomains + 1] = domain
      end
    end
    return {
      complete = #resolvedDomains > 0 and loadedCount == #resolvedDomains,
      fresh = #resolvedDomains > 0 and freshCount == #resolvedDomains,
      loadedCount = loadedCount,
      freshCount = freshCount,
      requestedDomains = CloneProfileSyncDomainList(resolvedDomains),
      staleDomains = CloneProfileSyncDomainList(staleDomains),
    }
  end

  profileSyncLocalOps.getPreciseSubchecksumRequestState = function(sessionId, memberKey)
    local requestKey = profileSyncLocalOps.buildSubchecksumRequestQueueKey(sessionId, memberKey)
    local requestState = profileSyncCaches.preciseSubchecksumRequestStateByMember[requestKey]
    local resolver = INTERNAL_API.LIDCOUNCIL_ResolvePreciseRequestLifecycle_Impl
    local resolved = type(resolver) == "function" and resolver(requestState, GetNow()) or { status = "idle" }
    if type(requestState) == "table" and resolved.status ~= requestState.status then
      requestState.status = resolved.status
      requestState.error = resolved.error
      requestState.updatedAt = GetNow()
    end
    resolved.domains = CloneProfileSyncDomainList(type(requestState) == "table" and requestState.domains or {})
    resolved.requestToken = TrimText(type(requestState) == "table" and requestState.requestToken or "")
    resolved.deadlineAt = math.max(0, tonumber(type(requestState) == "table" and requestState.deadlineAt or 0) or 0)
    resolved.lastProgressAt = math.max(0, tonumber(type(requestState) == "table" and requestState.lastProgressAt or 0) or 0)
    return resolved
  end

  profileSyncLocalOps.rememberPreciseSubchecksumRequest = function(sessionId, memberKey, domains, requestToken, sendError)
    local requestKey = profileSyncLocalOps.buildSubchecksumRequestQueueKey(sessionId, memberKey)
    local resolvedDomains = ResolveProfileRevisionDomainList(domains)
    if requestKey == "" or #resolvedDomains == 0 then
      return nil
    end
    local now = GetNow()
    local existingState = profileSyncCaches.preciseSubchecksumRequestStateByMember[requestKey]
    if TrimText(sendError) == ""
      and type(existingState) == "table"
      and TrimText(existingState.requestToken) == TrimText(requestToken)
    then
      local existingStatus = string.lower(TrimText(existingState.status))
      if existingStatus == "waiting" then
        return existingState
      end
      if existingStatus == "failed" and TrimText(existingState.error) == "response_timeout" then
        existingState.status = "waiting"
        existingState.error = ""
        existingState.domains = CloneProfileSyncDomainList(resolvedDomains)
        existingState.deadlineAt = now + profileSyncConfig.preciseRequestTimeoutSeconds
        existingState.updatedAt = now
        return existingState
      end
    end
    local requestState = {
      status = TrimText(sendError) == "" and "waiting" or "failed",
      domains = CloneProfileSyncDomainList(resolvedDomains),
      receivedDomains = {},
      requestToken = TrimText(requestToken),
      requestedAt = now,
      deadlineAt = now + profileSyncConfig.preciseRequestTimeoutSeconds,
      updatedAt = now,
      error = TrimText(sendError),
    }
    profileSyncCaches.preciseSubchecksumRequestStateByMember[requestKey] = requestState
    if requestState.status == "waiting" and type(Compat) == "table" and type(Compat.After) == "function" then
      local expectedToken = requestState.requestToken
      Compat.After(profileSyncConfig.preciseRequestTimeoutSeconds + 0.1, function()
        local currentState = profileSyncCaches.preciseSubchecksumRequestStateByMember[requestKey]
        if type(currentState) ~= "table" or TrimText(currentState.requestToken) ~= expectedToken then
          return
        end
        local lifecycle = profileSyncLocalOps.getPreciseSubchecksumRequestState(sessionId, memberKey)
        if lifecycle.failed == true and TrimText(lifecycle.error) == "response_timeout" then
          profileSyncLocalOps.emitPreciseProfileSyncLoadNotice({
            sessionId = sessionId,
            sender = memberKey,
            kind = "subchecks_timeout",
          })
        end
      end)
    end
    return requestState
  end

  profileSyncLocalOps.markPreciseSubchecksumProgress = function(sessionId, memberKey, requestToken)
    local requestKey = profileSyncLocalOps.buildSubchecksumRequestQueueKey(sessionId, memberKey)
    local requestState = profileSyncCaches.preciseSubchecksumRequestStateByMember[requestKey]
    return INTERNAL_API.LIDCOUNCIL_AdvancePreciseRequestProgress_Impl(
      requestState,
      requestToken,
      GetNow(),
      profileSyncConfig.preciseRequestProgressTimeoutSeconds
    )
  end

  profileSyncLocalOps.markPreciseSubchecksumResponse = function(sessionId, memberKey, domain, requestToken)
    local requestKey = profileSyncLocalOps.buildSubchecksumRequestQueueKey(sessionId, memberKey)
    local requestState = profileSyncCaches.preciseSubchecksumRequestStateByMember[requestKey]
    local resolvedDomain = string.lower(TrimText(domain))
    if type(requestState) ~= "table" or resolvedDomain == "" then
      return false, false
    end
    if TrimText(requestState.requestToken) ~= "" and TrimText(requestToken) ~= TrimText(requestState.requestToken) then
      return false, false
    end
    requestState.receivedDomains = type(requestState.receivedDomains) == "table" and requestState.receivedDomains or {}
    local firstReceipt = requestState.receivedDomains[resolvedDomain] ~= true
    requestState.receivedDomains[resolvedDomain] = true
    requestState.updatedAt = GetNow()
    local lifecycle = profileSyncLocalOps.getPreciseSubchecksumRequestState(sessionId, memberKey)
    return firstReceipt, lifecycle.complete == true and firstReceipt
  end

  profileSyncLocalOps.buildSubchecksumRequestStamp = function(sessionId, memberKey, domains)
    return string.lower(TrimText(sessionId)) .. "|"
      .. string.lower(NormalizeCharacterKey(memberKey)) .. "|"
      .. EncodeProfileRevisionDomains(domains)
  end

  profileSyncLocalOps.buildSubchecksumRequestQueueKey = function(sessionId, memberKey)
    return string.lower(TrimText(sessionId)) .. "|" .. string.lower(NormalizeCharacterKey(memberKey))
  end

  profileSyncLocalOps.buildProfileSubchecksumResponseSignature = function(profileId, manifest, domains)
    local parts = { TrimText(profileId) }
    local byDomain = type(manifest) == "table" and type(manifest.byDomain) == "table" and manifest.byDomain or {}
    for _, domain in ipairs(ResolveProfileRevisionDomainList(domains)) do
      local domainState = type(byDomain[domain]) == "table" and byDomain[domain] or nil
      parts[#parts + 1] = domain
      parts[#parts + 1] = TrimText(domainState and domainState.checksum or "")
      parts[#parts + 1] = EncodeProfileSyncSubchecks(domain, domainState and domainState.subchecksums or {})
    end
    return table.concat(parts, "\31")
  end

  profileSyncLocalOps.recordRecentSubchecksumRequestSubsets = function(sessionId, memberKey, resolvedDomains, resolvedRequestedAt, subset, startIndex)
    subset = type(subset) == "table" and subset or {}
    resolvedDomains = type(resolvedDomains) == "table" and resolvedDomains or {}
    startIndex = math.max(1, tonumber(startIndex) or 1)
    for index = startIndex, #resolvedDomains do
      subset[#subset + 1] = resolvedDomains[index]
      profileSyncCaches.recentSubchecksumRequests[profileSyncLocalOps.buildSubchecksumRequestStamp(sessionId, memberKey, subset)] = resolvedRequestedAt
      profileSyncLocalOps.recordRecentSubchecksumRequestSubsets(sessionId, memberKey, resolvedDomains, resolvedRequestedAt, subset, index + 1)
      subset[#subset] = nil
    end
  end

  profileSyncLocalOps.recordRecentSubchecksumRequest = function(sessionId, memberKey, domains, requestedAt)
    local resolvedDomains = ResolveProfileRevisionDomainList(domains)
    local resolvedRequestedAt = math.max(0, tonumber(requestedAt) or 0)
    if #resolvedDomains == 0 then
      return
    end

    profileSyncLocalOps.recordRecentSubchecksumRequestSubsets(sessionId, memberKey, resolvedDomains, resolvedRequestedAt, {}, 1)
  end

  profileSyncLocalOps.queueProfileSubchecksumResponse = function(sessionId, profileName, memberKey, domains, requestToken)
    local resolvedSessionId = TrimText(sessionId)
    local resolvedProfileName = TrimText(profileName)
    local resolvedTarget = NormalizeCharacterKey(memberKey)
    local resolvedDomains = ResolveProfileRevisionDomainList(domains)
    if resolvedSessionId == "" or resolvedProfileName == "" or resolvedTarget == "" or #resolvedDomains == 0 then
      return 0
    end

    local now = GetNow()
    PrunePreciseResponseRuntime(now)
    local requestKey = profileSyncLocalOps.buildSubchecksumRequestQueueKey(resolvedSessionId, resolvedTarget)
    local pending = profileSyncResponseRuntime.precise.pendingSubchecksum[requestKey]
    if type(pending) == "table" then
      local existingCsv = EncodeProfileRevisionDomains(pending.domains)
      pending.domains = MergeProfileRevisionDomains(pending.domains, resolvedDomains)
      pending.updatedAt = now
      if TrimText(requestToken) ~= "" then
        pending.requestToken = TrimText(requestToken)
      end
      return EncodeProfileRevisionDomains(pending.domains) ~= existingCsv and 1 or 0
    end

    profileSyncResponseRuntime.precise.pendingSubchecksum[requestKey] = {
      sessionId = resolvedSessionId,
      profileName = resolvedProfileName,
      target = resolvedTarget,
      domains = resolvedDomains,
      queuedAt = now,
      updatedAt = now,
      requestToken = TrimText(requestToken),
    }

    if type(Compat) == "table" and type(Compat.After) == "function" then
      profileSyncResponseRuntime.precise.timerToken = math.max(0, tonumber(profileSyncResponseRuntime.precise.timerToken) or 0) + 1
      local timerToken = profileSyncResponseRuntime.precise.timerToken
      profileSyncResponseRuntime.precise.pendingSubchecksum[requestKey].timerToken = timerToken
      Compat.After(profileSyncConfig.subcheckRequestCoalesceDelaySeconds, function()
        profileSyncLocalOps.flushQueuedProfileSubchecksumResponse(requestKey, timerToken)
      end)
      return 1
    end

    return profileSyncLocalOps.flushQueuedProfileSubchecksumResponse(requestKey)
  end

  profileSyncLocalOps.flushQueuedProfileSubchecksumResponse = function(requestKey, expectedTimerToken)
    local pending = profileSyncResponseRuntime.precise.pendingSubchecksum[TrimText(requestKey)]
    if type(pending) ~= "table" then
      return 0
    end
    if expectedTimerToken ~= nil and math.max(0, tonumber(pending.timerToken) or 0) ~= math.max(0, tonumber(expectedTimerToken) or 0) then
      return 0
    end
    profileSyncResponseRuntime.precise.pendingSubchecksum[requestKey] = nil

    local activeSession, activeProfileName = GetActiveLootSession()
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    local resolvedSessionId = TrimText(pending.sessionId)
    local resolvedProfileName = TrimText(pending.profileName)
    local resolvedTarget = NormalizeCharacterKey(pending.target)
    if resolvedSessionId == ""
      or resolvedProfileName == ""
      or resolvedTarget == ""
      or not sessionRuntimeOps.doesSessionMatch(activeSession, activeProfileName, resolvedSessionId, resolvedProfileName)
      or not sessionRuntimeOps.isHostSender(activeSession, resolvedTarget)
      or selfKey == ""
      or not sessionRuntimeOps.isJoinedCharacter(activeSession, selfKey)
    then
      return 0
    end

    local resolvedDomains = ResolveProfileRevisionDomainList(pending.domains)
    if #resolvedDomains == 0 then
      return 0
    end

    local localProfileId = TrimText(select(1, GetLootProfileId(activeProfileName)) or "")
    if localProfileId == "" then
      return 0
    end
    local manifest = type(GetLootProfileSubchecksumManifest) == "function"
      and GetLootProfileSubchecksumManifest(activeProfileName, resolvedDomains)
      or nil
    if type(manifest) ~= "table" or type(manifest.byDomain) ~= "table" then
      return 0
    end

    local requestStamp = profileSyncLocalOps.buildSubchecksumRequestStamp(resolvedSessionId, resolvedTarget, resolvedDomains)
    local responseSignature = profileSyncLocalOps.buildProfileSubchecksumResponseSignature(localProfileId, manifest, resolvedDomains)
    local now = GetNow()
    local recentState = profileSyncResponseRuntime.precise.recentSubchecksum[requestStamp]
    local shouldSuppressResponse = INTERNAL_API.LIDCOUNCIL_ShouldSuppressPreciseResponse_Impl
    if type(shouldSuppressResponse) == "function" and shouldSuppressResponse(
      recentState,
      responseSignature,
      pending.requestToken,
      now,
      profileSyncConfig.localProfileStateDedupeSeconds
    ) then
      return 0
    end

    local sentCount = 0
    local allSent = true
    local responseTokens = {}
    for _, domain in ipairs(resolvedDomains) do
      local domainState = type(manifest.byDomain[domain]) == "table" and manifest.byDomain[domain] or nil
      local generatedResponseToken = string.format("PSC-%d-%d", tonumber(time and time() or 0) or 0, math.random(1000, 9999))
      local responseToken = generatedResponseToken
      local resolveResponseToken = INTERNAL_API.LIDCOUNCIL_ResolvePreciseResponseToken_Impl
      if type(resolveResponseToken) == "function" then
        responseToken = select(1, resolveResponseToken(
          recentState,
          responseSignature,
          pending.requestToken,
          domain,
          generatedResponseToken
        ))
      end
      responseTokens[domain] = responseToken
      local maxPartField = tostring(profileSyncConfig.maxIncomingPreciseMultipartParts)
      local messageParts, splitError = BuildProfileSyncSubcheckMessageParts(
        domain,
        domainState and domainState.subchecksums or {},
        function(partPayload)
          if type(sessionRuntimeOps.validateCommPayload) ~= "function" then
            return true
          end
          local payloadSafe, payloadReason, payloadBytes = sessionRuntimeOps.validateCommPayload(
            "PSUB_STATE",
            resolvedSessionId,
            resolvedProfileName,
            localProfileId,
            domain,
            TrimText(domainState and domainState.checksum or ""),
            partPayload,
            responseToken,
            maxPartField,
            maxPartField,
            TrimText(pending.requestToken)
          )
          if payloadSafe and payloadBytes > profileSyncConfig.subcheckStatePayloadTargetBytes then
            return false, "profile_subchecksum_state_repack_for_payload_headroom"
          end
          return payloadSafe, payloadReason
        end
      )
      local domainSent = true
      if type(messageParts) ~= "table" or #messageParts <= 0 then
        if type(sessionRuntimeOps.recordOutboundPayloadReject) == "function" then
          sessionRuntimeOps.recordOutboundPayloadReject("PSUB_STATE", splitError or "response_split_failed", 0, {
            sessionId = resolvedSessionId,
            target = resolvedTarget,
          })
        end
        domainSent = false
        allSent = false
        break
      end
      if type(sessionRuntimeOps.validateCommPayload) == "function" then
        for partIndex, partPayload in ipairs(messageParts) do
          local payloadSafe, payloadReason, payloadBytes = sessionRuntimeOps.validateCommPayload(
            "PSUB_STATE",
            resolvedSessionId,
            resolvedProfileName,
            localProfileId,
            domain,
            TrimText(domainState and domainState.checksum or ""),
            partPayload,
            responseToken,
            tostring(partIndex),
            tostring(#messageParts),
            TrimText(pending.requestToken)
          )
          if not payloadSafe then
            if type(sessionRuntimeOps.recordOutboundPayloadReject) == "function" then
              sessionRuntimeOps.recordOutboundPayloadReject("PSUB_STATE", payloadReason, payloadBytes, {
                sessionId = resolvedSessionId,
                target = resolvedTarget,
              })
            end
            domainSent = false
            allSent = false
            break
          end
        end
      end
      if not domainSent then
        break
      end
      for partIndex, partPayload in ipairs(messageParts) do
        local sent = SendComm(
          "PSUB_STATE",
          "WHISPER",
          resolvedTarget,
          resolvedSessionId,
          resolvedProfileName,
          localProfileId,
          domain,
          TrimText(domainState and domainState.checksum or ""),
          partPayload,
          responseToken,
          tostring(partIndex),
          tostring(#messageParts),
          TrimText(pending.requestToken)
        )
        if not sent then
          domainSent = false
          allSent = false
          break
        end
      end
      if domainSent then
        sentCount = sentCount + 1
      end
    end
    if allSent and sentCount == #resolvedDomains then
      profileSyncResponseRuntime.precise.recentSubchecksum[requestStamp] = {
        signature = responseSignature,
        requestToken = TrimText(pending.requestToken),
        responseTokens = responseTokens,
        sentAt = now,
      }
    end
    if sentCount > 0 then
      profileSyncLocalOps.emitPreciseProfileSyncSendNotice({
        sessionId = resolvedSessionId,
        profileName = activeProfileName,
        sender = resolvedTarget,
        kind = "subchecks",
      })
    end
    return sentCount
  end

  profileSyncLocalOps.queueProfileSubchecksumRequest = function(sessionId, profileName, memberKey, domains, options)
    options = type(options) == "table" and options or {}
    local resolvedSessionId = TrimText(sessionId)
    local resolvedProfileName = TrimText(profileName)
    local resolvedTarget = NormalizeCharacterKey(memberKey)
    local resolvedDomains = ResolveProfileRevisionDomainList(domains)
    if resolvedSessionId == "" or resolvedProfileName == "" or resolvedTarget == "" or #resolvedDomains == 0 then
      return 0
    end

    local requestKey = profileSyncLocalOps.buildSubchecksumRequestQueueKey(resolvedSessionId, resolvedTarget)
    local requestedToken = TrimText(options.requestToken)
    if #requestedToken > profileSyncConfig.maxIncomingPreciseRequestTokenBytes then
      requestedToken = ""
    end
    local pending = profileSyncCaches.pendingSubchecksumRequests[requestKey]
    if type(pending) == "table" then
      local existingCsv = EncodeProfileRevisionDomains(pending.domains)
      pending.domains = MergeProfileRevisionDomains(pending.domains, resolvedDomains)
      pending.force = pending.force == true or options.force == true
      if requestedToken ~= "" then
        pending.requestToken = requestedToken
      elseif EncodeProfileRevisionDomains(pending.domains) ~= existingCsv or options.force == true then
        pending.requestToken = profileSyncLocalOps.createPreciseRequestToken("PSUB")
      end
      profileSyncLocalOps.rememberPreciseSubchecksumRequest(
        resolvedSessionId,
        resolvedTarget,
        pending.domains,
        pending.requestToken
      )
      return EncodeProfileRevisionDomains(pending.domains) ~= existingCsv and 1 or 0
    end

    profileSyncCaches.pendingSubchecksumRequests[requestKey] = {
      sessionId = resolvedSessionId,
      profileName = resolvedProfileName,
      target = resolvedTarget,
      domains = resolvedDomains,
      force = options.force == true,
      requestToken = requestedToken ~= "" and requestedToken or profileSyncLocalOps.createPreciseRequestToken("PSUB"),
    }
    profileSyncLocalOps.rememberPreciseSubchecksumRequest(
      resolvedSessionId,
      resolvedTarget,
      resolvedDomains,
      profileSyncCaches.pendingSubchecksumRequests[requestKey].requestToken
    )

    if type(Compat) == "table" and type(Compat.After) == "function" then
      Compat.After(profileSyncConfig.subcheckRequestCoalesceDelaySeconds, function()
        profileSyncLocalOps.flushQueuedProfileSubchecksumRequest(requestKey)
      end)
      return 1
    end

    return profileSyncLocalOps.flushQueuedProfileSubchecksumRequest(requestKey)
  end

  profileSyncLocalOps.sendProfileSubchecksumRequests = function(targetMemberKey, domains, options)
    options = type(options) == "table" and options or {}
    local activeSession, profileName = GetActiveLootSession()
    if not activeSession or not profileName then
      return 0
    end

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

    local resolvedTarget = NormalizeCharacterKey(targetMemberKey)
    local resolvedDomains = ResolveProfileRevisionDomainList(domains)
    if resolvedTarget == "" or #resolvedDomains == 0 or not sessionRuntimeOps.isJoinedCharacter(activeSession, resolvedTarget) then
      return 0
    end

    if not options.force then
      resolvedDomains = profileSyncLocalOps.pruneLoadedSubchecksumDomains(activeSession.id, resolvedTarget, resolvedDomains)
    end
    if #resolvedDomains == 0 then
      return 0
    end

    local requestStamp = profileSyncLocalOps.buildSubchecksumRequestStamp(activeSession.id, resolvedTarget, resolvedDomains)
    local now = GetNow()
    local lastRequestedAt = tonumber(profileSyncCaches.recentSubchecksumRequests[requestStamp]) or 0
    if not options.force and (now - lastRequestedAt) < profileSyncConfig.subcheckRequestDedupeSeconds then
      return 0
    end

    return profileSyncLocalOps.queueProfileSubchecksumRequest(activeSession.id, profileName, resolvedTarget, resolvedDomains, options)
  end

  profileSyncLocalOps.flushQueuedProfileSubchecksumRequest = function(requestKey)
    local pending = profileSyncCaches.pendingSubchecksumRequests[TrimText(requestKey)]
    if type(pending) ~= "table" then
      return 0
    end
    profileSyncCaches.pendingSubchecksumRequests[requestKey] = nil

    local activeSession, profileName = GetActiveLootSession()
    if not activeSession or not profileName then
      return 0
    end

    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    local resolvedSessionId = TrimText(pending.sessionId)
    local resolvedProfileName = TrimText(pending.profileName)
    local resolvedTarget = NormalizeCharacterKey(pending.target)
    if resolvedSessionId == ""
      or resolvedProfileName == ""
      or resolvedTarget == ""
      or not sessionRuntimeOps.isHostSender(activeSession, selfKey)
      or TrimText(activeSession.id) ~= resolvedSessionId
      or string.lower(TrimText(profileName)) ~= string.lower(resolvedProfileName)
      or not sessionRuntimeOps.isJoinedCharacter(activeSession, resolvedTarget)
    then
      return 0
    end

    local resolvedDomains = ResolveProfileRevisionDomainList(pending.domains)
    if not pending.force then
      resolvedDomains = profileSyncLocalOps.pruneLoadedSubchecksumDomains(resolvedSessionId, resolvedTarget, resolvedDomains)
    end
    if #resolvedDomains == 0 then
      return 0
    end

    local requestStamp = profileSyncLocalOps.buildSubchecksumRequestStamp(resolvedSessionId, resolvedTarget, resolvedDomains)
    local now = GetNow()
    local lastRequestedAt = tonumber(profileSyncCaches.recentSubchecksumRequests[requestStamp]) or 0
    if not pending.force and (now - lastRequestedAt) < profileSyncConfig.subcheckRequestDedupeSeconds then
      return 0
    end

    local profileId = TrimText(select(1, GetLootProfileId(resolvedProfileName)) or "")
    local sent = SendComm(
      "PSUB_REQ",
      "WHISPER",
      resolvedTarget,
      resolvedSessionId,
      resolvedProfileName,
      profileId,
      EncodeProfileRevisionDomains(resolvedDomains),
      TrimText(pending.requestToken)
    )
    if sent then
      profileSyncLocalOps.recordRecentSubchecksumRequest(resolvedSessionId, resolvedTarget, resolvedDomains, now)
      profileSyncLocalOps.rememberPreciseResponseToken(
        resolvedSessionId,
        resolvedTarget,
        "PSUB",
        resolvedDomains,
        pending.requestToken
      )
      profileSyncLocalOps.rememberPreciseSubchecksumRequest(
        resolvedSessionId,
        resolvedTarget,
        resolvedDomains,
        pending.requestToken
      )
      return 1
    end
    profileSyncLocalOps.rememberPreciseSubchecksumRequest(
      resolvedSessionId,
      resolvedTarget,
      resolvedDomains,
      pending.requestToken,
      "request_send_failed"
    )
    profileSyncLocalOps.emitPreciseProfileSyncLoadNotice({
      sessionId = resolvedSessionId,
      profileName = resolvedProfileName,
      sender = resolvedTarget,
      kind = "subchecks_send_failed",
    })
    return 0
  end

  profileSyncLocalOps.hasLoadedPatchManifestSubdomains = function(sessionId, memberKey, subdomains)
    local state = GetMemberPatchManifestState(sessionId, memberKey)
    if type(state) ~= "table" or type(state.bySubdomain) ~= "table" then
      return false
    end
    for _, subdomain in ipairs(type(FilterLootProfilePatchCapableSubdomains) == "function"
      and FilterLootProfilePatchCapableSubdomains(subdomains)
      or CloneProfileSyncSubdomainList(subdomains)) do
      if type(state.bySubdomain[subdomain]) ~= "table" then
        return false
      end
    end
    return true
  end

  profileSyncLocalOps.pruneLoadedPatchManifestSubdomains = function(sessionId, memberKey, subdomains)
    local state = GetMemberPatchManifestState(sessionId, memberKey)
    local unresolved = {}
    local bySubdomain = type(state) == "table" and type(state.bySubdomain) == "table" and state.bySubdomain or nil
    for _, subdomain in ipairs(type(FilterLootProfilePatchCapableSubdomains) == "function"
      and FilterLootProfilePatchCapableSubdomains(subdomains)
      or CloneProfileSyncSubdomainList(subdomains)) do
      if type(bySubdomain) ~= "table" or type(bySubdomain[subdomain]) ~= "table" then
        unresolved[#unresolved + 1] = subdomain
      end
    end
    return unresolved
  end

  profileSyncLocalOps.buildPreparedTransferPatchManifestSummary = function(profileName, subdomains)
    local patchCapableSubdomains = type(FilterLootProfilePatchCapableSubdomains) == "function"
      and FilterLootProfilePatchCapableSubdomains(subdomains)
      or CloneProfileSyncSubdomainList(subdomains)
    if #patchCapableSubdomains == 0
      or type(snapshotTransferOps.exportPatchManifest) ~= "function"
      or type(snapshotTransferOps.previewPatchManifest) ~= "function"
    then
      return nil
    end
    local manifestData = snapshotTransferOps.exportPatchManifest(profileName, patchCapableSubdomains)
    if type(manifestData) ~= "string" or manifestData == "" then
      return nil
    end
    local manifestSummary = snapshotTransferOps.previewPatchManifest(manifestData)
    if type(manifestSummary) ~= "table" then
      return nil
    end
    manifestSummary.scopeDomains = ResolveProfileRevisionDomainList(manifestSummary.scopeDomains)
    manifestSummary.scopeSubdomains = CloneProfileSyncSubdomainList(
      type(FilterLootProfilePatchCapableSubdomains) == "function"
        and FilterLootProfilePatchCapableSubdomains(
          type(manifestSummary.scopeSubdomains) == "table" and manifestSummary.scopeSubdomains or patchCapableSubdomains
        )
        or (type(manifestSummary.scopeSubdomains) == "table" and manifestSummary.scopeSubdomains or patchCapableSubdomains)
    )
    return manifestSummary
  end

  profileSyncLocalOps.buildPatchManifestRequestStamp = function(sessionId, memberKey, subdomains)
    return string.lower(TrimText(sessionId)) .. "|"
      .. string.lower(NormalizeCharacterKey(memberKey)) .. "|"
      .. table.concat(type(FilterLootProfilePatchCapableSubdomains) == "function"
        and FilterLootProfilePatchCapableSubdomains(subdomains)
        or CloneProfileSyncSubdomainList(subdomains), ",")
  end

  profileSyncLocalOps.getRememberedPatchManifestRequestToken = function(sessionId, memberKey, subdomains)
    PrunePreciseResponseRuntime(GetNow())
    local requestStamp = profileSyncLocalOps.buildPatchManifestRequestStamp(sessionId, memberKey, subdomains)
    local tokenState = requestStamp ~= "" and profileSyncCaches.patchManifestRequestTokensByStamp[requestStamp] or nil
    return TrimText(type(tokenState) == "table" and tokenState.token or "")
  end

  profileSyncLocalOps.buildPatchManifestRequestQueueKey = function(sessionId, memberKey)
    return string.lower(TrimText(sessionId)) .. "|" .. string.lower(NormalizeCharacterKey(memberKey))
  end

  profileSyncLocalOps.buildAutoPatchManifestTimerKey = function(sessionId, memberKey)
    return string.lower(TrimText(sessionId)) .. "|" .. string.lower(NormalizeCharacterKey(memberKey))
  end

  profileSyncLocalOps.queuePatchManifestRequest = function(sessionId, profileName, memberKey, subdomains, options)
    options = type(options) == "table" and options or {}
    local resolvedSessionId = TrimText(sessionId)
    local resolvedProfileName = TrimText(profileName)
    local resolvedTarget = NormalizeCharacterKey(memberKey)
    local resolvedSubdomains = type(FilterLootProfilePatchCapableSubdomains) == "function"
      and FilterLootProfilePatchCapableSubdomains(subdomains)
      or CloneProfileSyncSubdomainList(subdomains)
    if resolvedSessionId == "" or resolvedProfileName == "" or resolvedTarget == "" or #resolvedSubdomains == 0 then
      return 0
    end

    local requestedToken = TrimText(options.requestToken)
    if #requestedToken > profileSyncConfig.maxIncomingPreciseRequestTokenBytes then
      requestedToken = ""
    end
    if requestedToken == "" and options.auto == true then
      requestedToken = profileSyncLocalOps.getRememberedPatchManifestRequestToken(
        resolvedSessionId,
        resolvedTarget,
        resolvedSubdomains
      )
    end
    local requestKey = profileSyncLocalOps.buildPatchManifestRequestQueueKey(resolvedSessionId, resolvedTarget)
    local pending = profileSyncCaches.pendingPatchManifestRequests[requestKey]
    if type(pending) == "table" then
      local existingCsv = table.concat(pending.subdomains, ",")
      pending.subdomains = profileSyncLocalOps.mergePatchManifestRequestSubdomains(pending.subdomains, resolvedSubdomains)
      pending.force = pending.force == true or options.force == true
      local scopeChanged = table.concat(pending.subdomains, ",") ~= existingCsv
      if scopeChanged or options.manualRearm == true then
        pending.requestToken = requestedToken ~= ""
          and requestedToken
          or profileSyncLocalOps.createPreciseRequestToken("PSUBPATCH")
      elseif TrimText(pending.requestToken) == "" and requestedToken ~= "" then
        pending.requestToken = requestedToken
      end
      return scopeChanged and 1 or 0
    end

    profileSyncCaches.pendingPatchManifestRequests[requestKey] = {
      sessionId = resolvedSessionId,
      profileName = resolvedProfileName,
      target = resolvedTarget,
      subdomains = resolvedSubdomains,
      force = options.force == true,
      requestToken = requestedToken ~= ""
        and requestedToken
        or profileSyncLocalOps.createPreciseRequestToken("PSUBPATCH"),
    }

    if type(Compat) == "table" and type(Compat.After) == "function" then
      Compat.After(profileSyncConfig.patchManifestRequestCoalesceDelaySeconds, function()
        profileSyncLocalOps.flushQueuedPatchManifestRequest(requestKey)
      end)
      return 1
    end

    return profileSyncLocalOps.flushQueuedPatchManifestRequest(requestKey)
  end

  profileSyncLocalOps.sendPatchManifestRequests = function(targetMemberKey, subdomains, options)
    options = type(options) == "table" and options or {}
    local activeSession, profileName = GetActiveLootSession()
    if not activeSession or not profileName then
      return 0
    end

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

    local resolvedTarget = NormalizeCharacterKey(targetMemberKey)
    local resolvedSubdomains = type(FilterLootProfilePatchCapableSubdomains) == "function"
      and FilterLootProfilePatchCapableSubdomains(subdomains)
      or CloneProfileSyncSubdomainList(subdomains)
    if resolvedTarget == "" or #resolvedSubdomains == 0 or not sessionRuntimeOps.isJoinedCharacter(activeSession, resolvedTarget) then
      return 0
    end

    if not options.force then
      resolvedSubdomains = profileSyncLocalOps.pruneLoadedPatchManifestSubdomains(activeSession.id, resolvedTarget, resolvedSubdomains)
    end
    if #resolvedSubdomains == 0 then
      return 0
    end

    local requestStamp = profileSyncLocalOps.buildPatchManifestRequestStamp(activeSession.id, resolvedTarget, resolvedSubdomains)
    local now = GetNow()
    local lastRequestedAt = tonumber(profileSyncCaches.recentPatchManifestRequests[requestStamp]) or 0
    if not options.force and (now - lastRequestedAt) < profileSyncConfig.patchManifestDedupeSeconds then
      return 0
    end

    return profileSyncLocalOps.queuePatchManifestRequest(activeSession.id, profileName, resolvedTarget, resolvedSubdomains, options)
  end

  profileSyncLocalOps.flushQueuedPatchManifestRequest = function(requestKey)
    local pending = profileSyncCaches.pendingPatchManifestRequests[TrimText(requestKey)]
    if type(pending) ~= "table" then
      return 0
    end
    profileSyncCaches.pendingPatchManifestRequests[requestKey] = nil

    local activeSession, profileName = GetActiveLootSession()
    if not activeSession or not profileName then
      return 0
    end

    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    local resolvedSessionId = TrimText(pending.sessionId)
    local resolvedProfileName = TrimText(pending.profileName)
    local resolvedTarget = NormalizeCharacterKey(pending.target)
    if resolvedSessionId == ""
      or resolvedProfileName == ""
      or resolvedTarget == ""
      or not sessionRuntimeOps.isHostSender(activeSession, selfKey)
      or TrimText(activeSession.id) ~= resolvedSessionId
      or string.lower(TrimText(profileName)) ~= string.lower(resolvedProfileName)
      or not sessionRuntimeOps.isJoinedCharacter(activeSession, resolvedTarget)
    then
      return 0
    end

    local resolvedSubdomains = type(FilterLootProfilePatchCapableSubdomains) == "function"
      and FilterLootProfilePatchCapableSubdomains(pending.subdomains)
      or CloneProfileSyncSubdomainList(pending.subdomains)
    if not pending.force then
      resolvedSubdomains = profileSyncLocalOps.pruneLoadedPatchManifestSubdomains(resolvedSessionId, resolvedTarget, resolvedSubdomains)
    end
    if #resolvedSubdomains == 0 then
      return 0
    end

    local requestStamp = profileSyncLocalOps.buildPatchManifestRequestStamp(resolvedSessionId, resolvedTarget, resolvedSubdomains)
    local now = GetNow()
    local lastRequestedAt = tonumber(profileSyncCaches.recentPatchManifestRequests[requestStamp]) or 0
    if not pending.force and (now - lastRequestedAt) < profileSyncConfig.patchManifestDedupeSeconds then
      return 0
    end

    local profileId = TrimText(select(1, GetLootProfileId(resolvedProfileName)) or "")
    local parts, splitError = profileSyncLocalOps.buildPatchManifestRequestParts(
      resolvedSessionId,
      resolvedProfileName,
      profileId,
      resolvedSubdomains,
      pending.requestToken
    )
    if #parts == 0 then
      if type(sessionRuntimeOps.recordOutboundPayloadReject) == "function" then
        sessionRuntimeOps.recordOutboundPayloadReject("PSUBPATCH_REQ", splitError or "request_split_failed", 0, {
          sessionId = resolvedSessionId,
          target = resolvedTarget,
        })
      end
      return 0
    end

    local sentCount = 0
    for _, part in ipairs(parts) do
      local sent = SendComm(
        "PSUBPATCH_REQ",
        "WHISPER",
        resolvedTarget,
        resolvedSessionId,
        resolvedProfileName,
        profileId,
        part,
        TrimText(pending.requestToken)
      )
      if sent then
        sentCount = sentCount + 1
      end
    end
    if sentCount > 0 then
      profileSyncCaches.recentPatchManifestRequests[requestStamp] = now
      profileSyncCaches.patchManifestRequestTokensByStamp[requestStamp] = {
        token = TrimText(pending.requestToken),
        updatedAt = now,
      }
      profileSyncLocalOps.rememberPreciseResponseToken(
        resolvedSessionId,
        resolvedTarget,
        "PSUBPATCH",
        resolvedSubdomains,
        pending.requestToken
      )
    end
    return sentCount
  end

  profileSyncLocalOps.queueAutoPatchManifestRequest = function(memberKey, subdomains)
    local activeSession, profileName = GetActiveLootSession()
    if not activeSession or not profileName then
      return
    end
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if not sessionRuntimeOps.isHostSender(activeSession, selfKey) then
      return
    end
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    local normalizedSubdomains = type(FilterLootProfilePatchCapableSubdomains) == "function"
      and FilterLootProfilePatchCapableSubdomains(subdomains)
      or CloneProfileSyncSubdomainList(subdomains)
    if resolvedMemberKey == "" or #normalizedSubdomains == 0 or not sessionRuntimeOps.isJoinedCharacter(activeSession, resolvedMemberKey) then
      return
    end
    local pendingKey = profileSyncLocalOps.buildAutoPatchManifestTimerKey(activeSession.id, resolvedMemberKey)
    local pendingState = profileSyncCaches.pendingAutoPatchManifestTimers[pendingKey]
    if type(pendingState) == "table" then
      pendingState.subdomains = profileSyncLocalOps.mergePatchManifestRequestSubdomains(pendingState.subdomains, normalizedSubdomains)
      return
    end
    local token = string.format("APMR-%d-%d", tonumber(time and time() or 0) or 0, math.random(1000, 9999))
    profileSyncCaches.pendingAutoPatchManifestTimers[pendingKey] = {
      token = token,
      sessionId = TrimText(activeSession.id),
      profileName = TrimText(profileName),
      target = resolvedMemberKey,
      subdomains = CloneProfileSyncSubdomainList(normalizedSubdomains),
    }
    profileSyncLocalOps.runPendingAutoPatchManifestRequest = profileSyncLocalOps.runPendingAutoPatchManifestRequest or function(requestKey, requestToken)
      local currentPending = profileSyncCaches.pendingAutoPatchManifestTimers[TrimText(requestKey)]
      if type(currentPending) ~= "table" or currentPending.token ~= TrimText(requestToken) then
        return
      end
      profileSyncCaches.pendingAutoPatchManifestTimers[requestKey] = nil
      local activeSession, profileName = GetActiveLootSession()
      local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
      if not activeSession
        or not profileName
        or not sessionRuntimeOps.isHostSender(activeSession, selfKey)
        or TrimText(activeSession.id) ~= TrimText(currentPending.sessionId)
        or string.lower(TrimText(profileName)) ~= string.lower(TrimText(currentPending.profileName))
        or not sessionRuntimeOps.isJoinedCharacter(activeSession, NormalizeCharacterKey(currentPending.target))
      then
        return
      end
      profileSyncLocalOps.sendPatchManifestRequests(currentPending.target, currentPending.subdomains, {
        auto = true,
      })
    end
    if type(Compat) == "table" and type(Compat.After) == "function" then
      Compat.After(profileSyncConfig.autoPatchManifestDelaySeconds, function()
        profileSyncLocalOps.runPendingAutoPatchManifestRequest(pendingKey, token)
      end)
    else
      profileSyncLocalOps.runPendingAutoPatchManifestRequest(pendingKey, token)
    end
  end

  profileSyncLocalOps.compareProfileRevisionSummaries = function(localSummary, remoteSummary, domains)
    local remoteNewer = {}
    local localNewer = {}
    local left = NormalizeRevisionSummary(localSummary)
    local right = NormalizeRevisionSummary(remoteSummary)
    for _, domain in ipairs(ResolveProfileRevisionDomainList(domains)) do
      local localRevision = math.max(0, tonumber(left[domain]) or 0)
      local remoteRevision = math.max(0, tonumber(right[domain]) or 0)
      local checksumKey = domain .. "Checksum"
      local localChecksum = TrimText(left[checksumKey])
      local remoteChecksum = TrimText(right[checksumKey])
      local haveChecksums = localChecksum ~= "" and remoteChecksum ~= ""
      if haveChecksums and localChecksum == remoteChecksum then
        -- Matching checksums mean the domain content is aligned even if older clients bumped a revision counter.
      elseif haveChecksums and localChecksum ~= remoteChecksum then
        if remoteRevision > localRevision then
          remoteNewer[#remoteNewer + 1] = domain
        elseif localRevision > remoteRevision then
          localNewer[#localNewer + 1] = domain
        else
          remoteNewer[#remoteNewer + 1] = domain
          localNewer[#localNewer + 1] = domain
        end
      elseif remoteRevision > localRevision then
        remoteNewer[#remoteNewer + 1] = domain
      elseif localRevision > remoteRevision then
        localNewer[#localNewer + 1] = domain
      end
    end
    return remoteNewer, localNewer
  end

  profileSyncLocalOps.formatProfileRevisionDomains = function(domains)
    if type(domains) ~= "table" or #domains == 0 then
      return "none"
    end
    local labels = {}
    for _, domain in ipairs(domains) do
      labels[#labels + 1] = PROFILE_REVISION_DOMAIN_LABELS[domain] or tostring(domain)
    end
    return table.concat(labels, ", ")
  end

  profileSyncLocalOps.sendLocalProfileStateToHost = function(sessionId, profileName, targetProfileName, options)
    options = type(options) == "table" and options or {}
    if type(SendComm) ~= "function" then
      return false
    end
    local activeSession = GetActiveLootSession()
    if type(activeSession) ~= "table" or TrimText(activeSession.id) ~= TrimText(sessionId) then
      return false
    end
    local host = NormalizeCharacterKey(activeSession.host)
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if host == "" or selfKey == "" or string.lower(host) == string.lower(selfKey) then
      return false
    end

    local localProfileName = TrimText(targetProfileName)
    if localProfileName == "" then
      localProfileName = TrimText(profileName)
    end
    local profileId = TrimText(select(1, GetLootProfileId(localProfileName)) or "")
    local summary = NormalizeRevisionSummary(GetLootProfileRevisionSummary(localProfileName), localProfileName, profileId)
    local archiveManifest = type(GetLootProfileSubchecksumManifest) == "function"
      and GetLootProfileSubchecksumManifest(localProfileName, { "loot", "session" })
      or nil
    local liveLootChecksum = profileSyncLocalOps.buildLiveLootChecksum(archiveManifest, activeSession)
    local archiveLootChecksum = profileSyncLocalOps.buildProfileSyncArchiveLootChecksum(
      archiveManifest,
      activeSession
    )
    local archiveScopeChecksums = profileSyncLocalOps.buildProfileSyncArchiveScopeChecksums(archiveManifest, activeSession)
    summary.liveLootChecksum = liveLootChecksum
    summary.archiveLootChecksum = archiveLootChecksum
    local now = GetNow()
    PruneRecentLocalProfileStateSends(now)
    local stateKey = profileSyncLocalOps.buildLocalProfileStateSendKey(host, sessionId, profileName, selfKey)
    local stateSignature = profileSyncLocalOps.buildLocalProfileStateSendSignature(
      profileId,
      summary,
      liveLootChecksum,
      archiveLootChecksum,
      archiveScopeChecksums
    )
    local recentState = stateKey ~= "" and profileSyncCaches.recentLocalProfileStateSends[stateKey] or nil
    if INTERNAL_API.LIDCOUNCIL_ShouldSuppressLocalProfileStateSend_Impl(
      recentState,
      stateSignature,
      now,
      profileSyncConfig.localProfileStateDedupeSeconds,
      options.force
    ) then
      return true
    end
    local stateArgs = {
      TrimText(sessionId),
      TrimText(profileName),
      selfKey,
      profileId,
      tostring(summary.settings or 0),
      tostring(summary.permissions or 0),
      tostring(summary.operational or 0),
      tostring(summary.updatedAt or 0),
      TrimText(summary.settingsChecksum),
      TrimText(summary.permissionsChecksum),
      TrimText(summary.operationalChecksum),
      tostring(summary.loot or summary.operational or 0),
      tostring(summary.session or summary.operational or 0),
      TrimText(summary.lootChecksum),
      TrimText(summary.sessionChecksum),
      liveLootChecksum,
      archiveLootChecksum,
      tostring(type(sessionRuntimeOps.buildProtocolMarker) == "function" and sessionRuntimeOps.buildProtocolMarker() or ""),
      TrimText(archiveScopeChecksums.lootList),
      TrimText(archiveScopeChecksums.itemHistory),
      TrimText(archiveScopeChecksums.sessionHistory),
      TrimText(archiveScopeChecksums.funAwards)
    }
    local stateParts = nil
    local statePartToken = ""
    local payloadReason = ""
    local payloadBytes = 0
    if type(sessionRuntimeOps.validateCommPayload) == "function" then
      local payloadSafe
      payloadSafe, payloadReason, payloadBytes = sessionRuntimeOps.validateCommPayload("PSTATE", unpack(stateArgs))
      if not payloadSafe and TrimText(payloadReason) == "comm_payload_exceeds_safe_limit"
        and type(sessionRuntimeOps.buildPayload) == "function"
        and type(sessionRuntimeOps.splitCommPayloadField) == "function"
      then
        profileSyncCaches.profileStateMultipartSequence =
          (math.max(0, tonumber(profileSyncCaches.profileStateMultipartSequence) or 0) % 999999) + 1
        statePartToken = "PST-" .. tostring(GetNow()) .. "-" .. tostring(profileSyncCaches.profileStateMultipartSequence)
        local encodedState = sessionRuntimeOps.buildPayload("PSTATE", unpack(stateArgs))
        stateParts, payloadReason = sessionRuntimeOps.splitCommPayloadField(
          "PSTATE_PART",
          encodedState,
          {
            TrimText(sessionId),
            TrimText(profileName),
            selfKey,
            profileId,
            statePartToken,
            "99",
            "99",
          },
          {},
          profileSyncConfig.profileStatePartChunkBytes,
          profileSyncConfig.profileStatePartPayloadTargetBytes
        )
        local statePartCount = type(stateParts) == "table" and #stateParts or 0
        if statePartCount <= 0 or statePartCount > profileSyncConfig.maxProfileStateParts then
          local partFailureReason = statePartCount > profileSyncConfig.maxProfileStateParts
            and "profile_state_part_count_exceeds_limit"
            or FirstNonEmptyText(payloadReason, "profile_state_fragmentation_failed")
          stateParts = nil
          payloadReason = partFailureReason
        else
          for index, statePart in ipairs(stateParts) do
            local partSafe, partReason, partBytes = sessionRuntimeOps.validateCommPayload(
              "PSTATE_PART",
              TrimText(sessionId),
              TrimText(profileName),
              selfKey,
              profileId,
              statePartToken,
              tostring(index),
              tostring(#stateParts),
              statePart
            )
            if not partSafe then
              stateParts = nil
              payloadReason = FirstNonEmptyText(partReason, "profile_state_part_validation_failed")
              payloadBytes = math.max(0, tonumber(partBytes) or payloadBytes)
              break
            end
          end
        end
        payloadSafe = type(stateParts) == "table" and #stateParts > 0
      end
      if not payloadSafe then
        if type(sessionRuntimeOps.recordOutboundPayloadReject) == "function" then
          sessionRuntimeOps.recordOutboundPayloadReject("PSTATE", payloadReason, payloadBytes, {
            sessionId = sessionId,
            target = host,
          })
        end
        if type(RecordProfileSyncDecision) == "function" then
          RecordProfileSyncDecision("send_profile_state", {
            action = "failed",
            sessionId = TrimText(sessionId),
            profileName = TrimText(profileName),
            target = host,
            reason = TrimText(payloadReason),
            error = "Profile state could not be transported without dropping convergence evidence.",
          })
        end
        return false
      end
    end
    local sent = true
    if type(stateParts) == "table" and #stateParts > 0 then
      for index, statePart in ipairs(stateParts) do
        local partSent = SendComm(
          "PSTATE_PART",
          "WHISPER",
          host,
          TrimText(sessionId),
          TrimText(profileName),
          selfKey,
          profileId,
          statePartToken,
          tostring(index),
          tostring(#stateParts),
          statePart
        )
        if not partSent then
          sent = false
          break
        end
      end
    else
      sent = SendComm("PSTATE", "WHISPER", host, unpack(stateArgs))
    end
    if sent and stateKey ~= "" then
      profileSyncCaches.recentLocalProfileStateSends[stateKey] = {
        signature = stateSignature,
        sentAt = now,
      }
    end
    return sent
  end

  profileSyncLocalOps.resolveProfileSyncComparison = function(localSummary, remoteSummary)
    local remoteNewerDomains, localNewerDomains = profileSyncLocalOps.compareProfileRevisionSummaries(localSummary, remoteSummary)
    local localProfileId = TrimText(type(localSummary) == "table" and localSummary.profileId or "")
    local remoteProfileId = TrimText(type(remoteSummary) == "table" and remoteSummary.profileId or "")
    return profileSyncLocalOps.resolveProfileSyncComparisonFromDomains(localProfileId, remoteProfileId, remoteNewerDomains, localNewerDomains),
      remoteNewerDomains,
      localNewerDomains
  end

  profileSyncLocalOps.resolveProfileSyncComparisonFromDomains = function(localProfileId, remoteProfileId, remoteNewerDomains, localNewerDomains)
    local comparison = "same"

    if remoteProfileId == "" then
      if #remoteNewerDomains > 0 and #localNewerDomains > 0 then
        comparison = "diverged"
      elseif #remoteNewerDomains > 0 then
        comparison = "remote_newer"
      elseif #localNewerDomains > 0 then
        comparison = "local_newer"
      else
        comparison = "unknown"
      end
    elseif localProfileId ~= "" and string.lower(localProfileId) ~= string.lower(remoteProfileId) then
      comparison = "different_lineage"
    elseif #remoteNewerDomains > 0 and #localNewerDomains > 0 then
      comparison = "diverged"
    elseif #remoteNewerDomains > 0 then
      comparison = "remote_newer"
    elseif #localNewerDomains > 0 then
      comparison = "local_newer"
    end

    return comparison, remoteNewerDomains, localNewerDomains
  end

  profileSyncLocalOps.addCharacterToRosterLookup = function(rosterLookup, characterKey)
    rosterLookup = type(rosterLookup) == "table" and rosterLookup or {}
    local resolvedKey = NormalizeCharacterKey(characterKey)
    if resolvedKey ~= "" then
      rosterLookup[string.lower(resolvedKey)] = true
    end
    return rosterLookup
  end

  profileSyncLocalOps.buildProfileSyncLiveRosterLookup = function(session)
    local rosterLookup = {}
    if type(session) == "table" then
      profileSyncLocalOps.addCharacterToRosterLookup(rosterLookup, session.host)
      for memberKey, member in pairs(session.members or {}) do
        if type(member) == "table" and string.upper(TrimText(member.status or "JOINED")) == "JOINED" then
          profileSyncLocalOps.addCharacterToRosterLookup(rosterLookup, memberKey)
        end
      end
    end
    return rosterLookup
  end

  profileSyncLocalOps.buildLiveLootChecksum = function(manifest, activeSession)
    if type(manifest) ~= "table" or type(CalculateStableChecksum) ~= "function" then
      return ""
    end
    local rosterLookup = profileSyncLocalOps.buildProfileSyncLiveRosterLookup(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 profileSyncLocalOps.classifyLootSubdomainTier(resolvedSubdomain, rosterLookup) == "live" then
        liveChecksums[resolvedSubdomain] = TrimText(checksum)
      end
    end
    if next(liveChecksums) == nil then
      return ""
    end
    return TrimText(CalculateStableChecksum(liveChecksums))
  end

  profileSyncLocalOps.buildProfileSyncArchiveLootChecksum = function(manifest, activeSession)
    if type(manifest) ~= "table" or type(CalculateStableChecksum) ~= "function" then
      return ""
    end
    local rosterLookup = profileSyncLocalOps.buildProfileSyncLiveRosterLookup(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 = type(activeSession) == "table" and TrimText(activeSession.id) ~= ""
      and ("ssr:id%3a" .. TrimText(activeSession.id))
      or ""
    for subdomain, checksum in pairs(subchecksums) do
      local resolvedSubdomain = TrimText(subdomain)
      if resolvedSubdomain ~= "" and profileSyncLocalOps.classifyLootSubdomainTier(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(CalculateStableChecksum(archiveChecksums))
  end

  profileSyncLocalOps.buildProfileSyncArchiveScopeChecksums = function(manifest, activeSession)
    if type(manifest) ~= "table" or type(CalculateStableChecksum) ~= "function" then
      return {}
    end
    local rosterLookup = profileSyncLocalOps.buildProfileSyncLiveRosterLookup(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 = profileSyncLocalOps.classifyLootSubdomainTier(resolvedSubdomain, rosterLookup)
      if tier == "stats" then
        buckets.funAwards[resolvedSubdomain] = TrimText(checksum)
      elseif tier ~= "" then
        -- The detailed Loot List receipt covers every character row, including
        -- currently joined raiders whose rows also participate in P2.
        buckets.lootList[resolvedSubdomain] = TrimText(checksum)
      end
    end
    local currentSessionSubdomain = ""
    if type(activeSession) == "table" and TrimText(activeSession.id) ~= "" then
      currentSessionSubdomain = "ssr:id%3a" .. TrimText(activeSession.id)
    end
    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(CalculateStableChecksum(buckets.lootList)),
      itemHistory = TrimText(CalculateStableChecksum(buckets.itemHistory)),
      sessionHistory = TrimText(CalculateStableChecksum(buckets.sessionHistory)),
      funAwards = TrimText(CalculateStableChecksum(buckets.funAwards)),
    }
  end

  profileSyncLocalOps.buildLootListDifferenceDiagnostics = function(localManifest, remoteState, activeSession)
    local diagnostics = {
      available = false,
      count = 0,
      leaves = {},
      aggregateDiffers = false,
      localArchiveChecksum = "",
      remoteArchiveChecksum = "",
    }
    local localByDomain = type(localManifest) == "table" and type(localManifest.byDomain) == "table"
      and localManifest.byDomain
      or {}
    local localLoot = type(localByDomain.loot) == "table" and localByDomain.loot or {}
    local remoteByDomain = type(remoteState) == "table" and type(remoteState.byDomain) == "table"
      and remoteState.byDomain
      or {}
    local remoteLoot = type(remoteByDomain.loot) == "table" and remoteByDomain.loot or nil
    if type(remoteLoot) ~= "table" then
      return diagnostics
    end

    diagnostics.available = true
    local localScopeChecksums = profileSyncLocalOps.buildProfileSyncArchiveScopeChecksums(localManifest, activeSession)
    local remoteScopeChecksums = profileSyncLocalOps.buildProfileSyncArchiveScopeChecksums(remoteState, activeSession)
    diagnostics.localArchiveChecksum = TrimText(localScopeChecksums.lootList)
    diagnostics.remoteArchiveChecksum = TrimText(remoteScopeChecksums.lootList)
    diagnostics.aggregateDiffers = diagnostics.localArchiveChecksum ~= ""
      and diagnostics.remoteArchiveChecksum ~= ""
      and string.lower(diagnostics.localArchiveChecksum) ~= string.lower(diagnostics.remoteArchiveChecksum)

    local localSubchecksums = type(localLoot.subchecksums) == "table" and localLoot.subchecksums or {}
    local remoteSubchecksums = type(remoteLoot.subchecksums) == "table" and remoteLoot.subchecksums or {}
    local leavesByIdentity = {}
    local function IsLootListLeaf(subdomain)
      local resolvedSubdomain = string.lower(TrimText(subdomain))
      if resolvedSubdomain == "" or resolvedSubdomain == "lrsr" or resolvedSubdomain == "lrsv"
        or resolvedSubdomain:find("^lre:", 1, false)
        or resolvedSubdomain:find("^lve:", 1, false)
      then
        return false
      end
      return true
    end
    local function RememberSide(source, side)
      for subdomain, checksum in pairs(type(source) == "table" and source or {}) do
        local resolvedSubdomain = TrimText(subdomain)
        local lowerSubdomain = string.lower(resolvedSubdomain)
        if IsLootListLeaf(resolvedSubdomain) then
          local leaf = leavesByIdentity[lowerSubdomain]
          if type(leaf) ~= "table" then
            local resolvedLabel = type(GetLootProfileSubdomainLabel) == "function"
              and GetLootProfileSubdomainLabel(resolvedSubdomain)
              or ""
            leaf = {
              subdomain = resolvedSubdomain,
              label = TrimText(resolvedLabel) ~= "" and resolvedLabel or resolvedSubdomain,
              localChecksum = "",
              remoteChecksum = "",
              localSubdomain = "",
              remoteSubdomain = "",
              localAliases = {},
              remoteAliases = {},
            }
            leavesByIdentity[lowerSubdomain] = leaf
          end
          local checksumField = side .. "Checksum"
          local subdomainField = side .. "Subdomain"
          local aliasesField = side .. "Aliases"
          if TrimText(leaf[subdomainField]) == "" then
            leaf[subdomainField] = resolvedSubdomain
            leaf[checksumField] = TrimText(checksum)
          elseif leaf[subdomainField] ~= resolvedSubdomain then
            if #leaf[aliasesField] == 0 then
              leaf[aliasesField][#leaf[aliasesField] + 1] = leaf[subdomainField]
            end
            leaf[aliasesField][#leaf[aliasesField] + 1] = resolvedSubdomain
          end
          if side == "local" or TrimText(leaf.subdomain) == "" then
            leaf.subdomain = resolvedSubdomain
          end
        end
      end
    end
    RememberSide(localSubchecksums, "local")
    RememberSide(remoteSubchecksums, "remote")

    for _, leaf in pairs(leavesByIdentity) do
      if #leaf.localAliases > 0 or #leaf.remoteAliases > 0 then
        if #leaf.localAliases > 0 and #leaf.remoteAliases > 0 then
          leaf.kind = "duplicate_identity_both"
          leaf.status = "Duplicate identity on host and member"
        elseif #leaf.localAliases > 0 then
          leaf.kind = "duplicate_local_identity"
          leaf.status = "Duplicate identity on host"
        else
          leaf.kind = "duplicate_remote_identity"
          leaf.status = "Duplicate identity on member"
        end
        local details = {}
        if #leaf.localAliases > 0 then
          details[#details + 1] = "Host: " .. table.concat(leaf.localAliases, ", ")
        end
        if #leaf.remoteAliases > 0 then
          details[#details + 1] = "Member: " .. table.concat(leaf.remoteAliases, ", ")
        end
        leaf.detail = table.concat(details, " | ")
      elseif TrimText(leaf.localChecksum) == "" then
        leaf.kind = "missing_local"
        leaf.status = "Missing on host"
      elseif TrimText(leaf.remoteChecksum) == "" then
        leaf.kind = "missing_remote"
        leaf.status = "Missing on member"
      elseif string.lower(TrimText(leaf.localChecksum)) ~= string.lower(TrimText(leaf.remoteChecksum)) then
        leaf.kind = "checksum_mismatch"
        leaf.status = "Checksum differs"
      elseif leaf.localSubdomain ~= leaf.remoteSubdomain then
        leaf.kind = "identity_case_mismatch"
        leaf.status = "Identity casing differs"
        leaf.detail = "Host: " .. leaf.localSubdomain .. " | Member: " .. leaf.remoteSubdomain
      end
      if TrimText(leaf.kind) ~= "" then
        diagnostics.leaves[#diagnostics.leaves + 1] = leaf
      end
    end
    table.sort(diagnostics.leaves, function(left, right)
      local leftLabel = string.lower(TrimText(type(left) == "table" and left.label or ""))
      local rightLabel = string.lower(TrimText(type(right) == "table" and right.label or ""))
      if leftLabel == rightLabel then
        return string.lower(TrimText(type(left) == "table" and left.subdomain or ""))
          < string.lower(TrimText(type(right) == "table" and right.subdomain or ""))
      end
      return leftLabel < rightLabel
    end)
    diagnostics.count = #diagnostics.leaves
    return diagnostics
  end

  profileSyncLocalOps.buildItemHistoryDifferenceDiagnostics = function(localManifest, remoteState)
    local diagnostics = {
      available = false,
      count = 0,
      leaves = {},
    }
    local localByDomain = type(localManifest) == "table" and type(localManifest.byDomain) == "table"
      and localManifest.byDomain
      or {}
    local localSession = type(localByDomain.session) == "table" and localByDomain.session or {}
    local remoteByDomain = type(remoteState) == "table" and type(remoteState.byDomain) == "table"
      and remoteState.byDomain
      or {}
    local remoteSession = type(remoteByDomain.session) == "table" and remoteByDomain.session or nil
    if type(remoteSession) ~= "table" then
      return diagnostics
    end

    diagnostics.available = true
    local localSubchecksums = type(localSession.subchecksums) == "table" and localSession.subchecksums or {}
    local remoteSubchecksums = type(remoteSession.subchecksums) == "table" and remoteSession.subchecksums or {}
    local leavesByIdentity = {}
    local function RememberSide(source, side)
      for subdomain, checksum in pairs(type(source) == "table" and source or {}) do
        local resolvedSubdomain = TrimText(subdomain)
        local lowerSubdomain = string.lower(resolvedSubdomain)
        if lowerSubdomain:find("^slb:", 1, false) then
          local leaf = leavesByIdentity[lowerSubdomain]
          if type(leaf) ~= "table" then
            leaf = {
              subdomain = resolvedSubdomain,
              label = type(GetLootProfileSubdomainLabel) == "function"
                and GetLootProfileSubdomainLabel(resolvedSubdomain)
                or resolvedSubdomain,
              localChecksum = "",
              remoteChecksum = "",
            }
            leavesByIdentity[lowerSubdomain] = leaf
          end
          if side == "local" then
            leaf.localChecksum = TrimText(checksum)
            leaf.subdomain = resolvedSubdomain
          else
            leaf.remoteChecksum = TrimText(checksum)
            if TrimText(leaf.subdomain) == "" then
              leaf.subdomain = resolvedSubdomain
            end
          end
        end
      end
    end
    RememberSide(localSubchecksums, "local")
    RememberSide(remoteSubchecksums, "remote")

    for _, leaf in pairs(leavesByIdentity) do
      if string.lower(TrimText(leaf.localChecksum)) ~= string.lower(TrimText(leaf.remoteChecksum)) then
        if TrimText(leaf.localChecksum) == "" then
          leaf.kind = "missing_local"
          leaf.status = "Missing locally"
        elseif TrimText(leaf.remoteChecksum) == "" then
          leaf.kind = "missing_remote"
          leaf.status = "Missing remotely"
        else
          leaf.kind = "checksum_mismatch"
          leaf.status = "Checksum differs"
        end
        diagnostics.leaves[#diagnostics.leaves + 1] = leaf
      end
    end
    table.sort(diagnostics.leaves, function(left, right)
      local leftLabel = string.lower(TrimText(type(left) == "table" and left.label or ""))
      local rightLabel = string.lower(TrimText(type(right) == "table" and right.label or ""))
      if leftLabel == rightLabel then
        return string.lower(TrimText(type(left) == "table" and left.subdomain or ""))
          < string.lower(TrimText(type(right) == "table" and right.subdomain or ""))
      end
      return leftLabel < rightLabel
    end)
    diagnostics.count = #diagnostics.leaves
    return diagnostics
  end

  profileSyncLocalOps.buildSessionHistoryDifferenceDiagnostics = function(localManifest, remoteState, activeSession)
    local diagnostics = {
      available = false,
      count = 0,
      leaves = {},
    }
    local localByDomain = type(localManifest) == "table" and type(localManifest.byDomain) == "table"
      and localManifest.byDomain
      or {}
    local localSession = type(localByDomain.session) == "table" and localByDomain.session or {}
    local remoteByDomain = type(remoteState) == "table" and type(remoteState.byDomain) == "table"
      and remoteState.byDomain
      or {}
    local remoteSession = type(remoteByDomain.session) == "table" and remoteByDomain.session or nil
    if type(remoteSession) ~= "table" then
      return diagnostics
    end

    diagnostics.available = true
    local currentSessionSubdomain = ""
    if type(activeSession) == "table" and TrimText(activeSession.id) ~= "" then
      currentSessionSubdomain = string.lower("ssr:id%3a" .. TrimText(activeSession.id))
    end
    local localSubchecksums = type(localSession.subchecksums) == "table" and localSession.subchecksums or {}
    local remoteSubchecksums = type(remoteSession.subchecksums) == "table" and remoteSession.subchecksums or {}
    local leavesByIdentity = {}
    local function RememberSide(source, side)
      for subdomain, checksum in pairs(type(source) == "table" and source or {}) do
        local resolvedSubdomain = TrimText(subdomain)
        local lowerSubdomain = string.lower(resolvedSubdomain)
        if lowerSubdomain:find("^ssr:", 1, false) and lowerSubdomain ~= currentSessionSubdomain then
          local leaf = leavesByIdentity[lowerSubdomain]
          if type(leaf) ~= "table" then
            leaf = {
              subdomain = resolvedSubdomain,
              label = type(GetLootProfileSubdomainLabel) == "function"
                and GetLootProfileSubdomainLabel(resolvedSubdomain)
                or resolvedSubdomain,
              localChecksum = "",
              remoteChecksum = "",
            }
            leavesByIdentity[lowerSubdomain] = leaf
          end
          if side == "local" then
            leaf.localChecksum = TrimText(checksum)
            leaf.subdomain = resolvedSubdomain
          else
            leaf.remoteChecksum = TrimText(checksum)
            if TrimText(leaf.subdomain) == "" then
              leaf.subdomain = resolvedSubdomain
            end
          end
        end
      end
    end
    RememberSide(localSubchecksums, "local")
    RememberSide(remoteSubchecksums, "remote")

    for _, leaf in pairs(leavesByIdentity) do
      if string.lower(TrimText(leaf.localChecksum)) ~= string.lower(TrimText(leaf.remoteChecksum)) then
        if TrimText(leaf.localChecksum) == "" then
          leaf.kind = "missing_local"
          leaf.status = "Missing on host"
        elseif TrimText(leaf.remoteChecksum) == "" then
          leaf.kind = "missing_remote"
          leaf.status = "Missing on member"
        else
          leaf.kind = "checksum_mismatch"
          leaf.status = "Checksum differs"
        end
        diagnostics.leaves[#diagnostics.leaves + 1] = leaf
      end
    end
    table.sort(diagnostics.leaves, function(left, right)
      local leftLabel = string.lower(TrimText(type(left) == "table" and left.label or ""))
      local rightLabel = string.lower(TrimText(type(right) == "table" and right.label or ""))
      if leftLabel == rightLabel then
        return string.lower(TrimText(type(left) == "table" and left.subdomain or ""))
          < string.lower(TrimText(type(right) == "table" and right.subdomain or ""))
      end
      return leftLabel < rightLabel
    end)
    diagnostics.count = #diagnostics.leaves
    return diagnostics
  end

  profileSyncLocalOps.updateMemberItemHistoryDifferenceDiagnostics = function(activeSession, profileName, memberKey)
    if type(activeSession) ~= "table" or type(GetLootProfileSubchecksumManifest) ~= "function" then
      return nil
    end
    local resolvedSessionId = TrimText(activeSession.id)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    local resolvedProfileName = TrimText(profileName)
    if resolvedSessionId == "" or resolvedMemberKey == "" or resolvedProfileName == "" then
      return nil
    end
    local remoteState = GetMemberSubchecksumState(resolvedSessionId, resolvedMemberKey)
    local localManifest = GetLootProfileSubchecksumManifest(resolvedProfileName, { "session" })
    local diagnostics = profileSyncLocalOps.buildItemHistoryDifferenceDiagnostics(localManifest, remoteState)
    if diagnostics.available ~= true then
      return diagnostics
    end
    local resolvedSessionKey = string.lower(resolvedSessionId)
    local resolvedMemberCacheKey = string.lower(resolvedMemberKey)
    profileSyncCaches.itemHistoryDifferenceDiagnosticsBySession[resolvedSessionKey] =
      profileSyncCaches.itemHistoryDifferenceDiagnosticsBySession[resolvedSessionKey] or {}
    profileSyncCaches.itemHistoryDifferenceDiagnosticsBySession[resolvedSessionKey][resolvedMemberCacheKey] = diagnostics
    return diagnostics
  end

  profileSyncLocalOps.updateMemberSessionHistoryDifferenceDiagnostics = function(activeSession, profileName, memberKey)
    if type(activeSession) ~= "table" or type(GetLootProfileSubchecksumManifest) ~= "function" then
      return nil
    end
    local resolvedSessionId = TrimText(activeSession.id)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    local resolvedProfileName = TrimText(profileName)
    if resolvedSessionId == "" or resolvedMemberKey == "" or resolvedProfileName == "" then
      return nil
    end
    local remoteState = GetMemberSubchecksumState(resolvedSessionId, resolvedMemberKey)
    local localManifest = GetLootProfileSubchecksumManifest(resolvedProfileName, { "session" })
    local diagnostics = profileSyncLocalOps.buildSessionHistoryDifferenceDiagnostics(
      localManifest,
      remoteState,
      activeSession
    )
    if diagnostics.available ~= true then
      return diagnostics
    end
    local resolvedSessionKey = string.lower(resolvedSessionId)
    local resolvedMemberCacheKey = string.lower(resolvedMemberKey)
    profileSyncCaches.sessionHistoryDifferenceDiagnosticsBySession[resolvedSessionKey] =
      profileSyncCaches.sessionHistoryDifferenceDiagnosticsBySession[resolvedSessionKey] or {}
    profileSyncCaches.sessionHistoryDifferenceDiagnosticsBySession[resolvedSessionKey][resolvedMemberCacheKey] = diagnostics
    return diagnostics
  end

  profileSyncLocalOps.updateMemberLootListDifferenceDiagnostics = function(activeSession, profileName, memberKey)
    if type(activeSession) ~= "table" or type(GetLootProfileSubchecksumManifest) ~= "function" then
      return nil
    end
    local resolvedSessionId = TrimText(activeSession.id)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    local resolvedProfileName = TrimText(profileName)
    if resolvedSessionId == "" or resolvedMemberKey == "" or resolvedProfileName == "" then
      return nil
    end
    local remoteState = GetMemberSubchecksumState(resolvedSessionId, resolvedMemberKey)
    local localManifest = GetLootProfileSubchecksumManifest(resolvedProfileName, { "loot" })
    local diagnostics = profileSyncLocalOps.buildLootListDifferenceDiagnostics(
      localManifest,
      remoteState,
      activeSession
    )
    if diagnostics.available ~= true then
      return diagnostics
    end
    local resolvedSessionKey = string.lower(resolvedSessionId)
    local resolvedMemberCacheKey = string.lower(resolvedMemberKey)
    profileSyncCaches.lootListDifferenceDiagnosticsBySession[resolvedSessionKey] =
      profileSyncCaches.lootListDifferenceDiagnosticsBySession[resolvedSessionKey] or {}
    profileSyncCaches.lootListDifferenceDiagnosticsBySession[resolvedSessionKey][resolvedMemberCacheKey] = diagnostics
    return diagnostics
  end

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

  profileSyncLocalOps.filterProfileSyncDomainList = function(list, excludedDomain)
    local excluded = string.lower(TrimText(excludedDomain))
    local filtered = {}
    for _, domain in ipairs(type(list) == "table" and list or {}) do
      local resolved = string.lower(TrimText(domain))
      if resolved ~= "" and resolved ~= excluded then
        filtered[#filtered + 1] = resolved
      end
    end
    return filtered
  end

  profileSyncLocalOps.filterProfileSyncDomains = function(list, excludedDomains)
    local excludedLookup = {}
    for _, domain in ipairs(type(excludedDomains) == "table" and excludedDomains or {}) do
      local resolved = string.lower(TrimText(domain))
      if resolved ~= "" then
        excludedLookup[resolved] = true
      end
    end
    local filtered = {}
    for _, domain in ipairs(type(list) == "table" and list or {}) do
      local resolved = string.lower(TrimText(domain))
      if resolved ~= "" and not excludedLookup[resolved] then
        filtered[#filtered + 1] = resolved
      end
    end
    return filtered
  end

  profileSyncLocalOps.buildEffectiveCandidateComparison = function(candidate, activeSession)
    candidate = type(candidate) == "table" and candidate or {}
    local preciseByDomain = type(candidate.preciseDifferentSubdomainsByDomain) == "table"
      and candidate.preciseDifferentSubdomainsByDomain
      or {}
    local lootSubdomains = type(preciseByDomain.loot) == "table" and preciseByDomain.loot or {}
    local rosterLookup = profileSyncLocalOps.buildProfileSyncLiveRosterLookup(activeSession)
    local liveLootDifferentSubdomains = {}
    local statsLootDifferentSubdomains = {}
    local archiveLootDifferentSubdomains = {}

    for _, subdomain in ipairs(lootSubdomains) do
      local tier = profileSyncLocalOps.classifyLootSubdomainTier(subdomain, rosterLookup)
      if tier == "live" then
        liveLootDifferentSubdomains[#liveLootDifferentSubdomains + 1] = subdomain
      elseif tier == "stats" then
        statsLootDifferentSubdomains[#statsLootDifferentSubdomains + 1] = subdomain
      else
        archiveLootDifferentSubdomains[#archiveLootDifferentSubdomains + 1] = subdomain
      end
    end

    local effectiveRemoteNewerDomains = CloneProfileSyncDomainList(candidate.remoteNewerDomains)
    local effectiveLocalNewerDomains = CloneProfileSyncDomainList(candidate.localNewerDomains)
    local rawComparison = string.lower(TrimText(candidate.comparison))
    local localLiveLootChecksum = TrimText(candidate.localLiveLootChecksum)
    local remoteLiveLootChecksum = TrimText(candidate.remoteLiveLootChecksum)
    local localArchiveLootChecksum = TrimText(candidate.localArchiveLootChecksum)
    local remoteArchiveLootChecksum = TrimText(candidate.remoteArchiveLootChecksum)
    local hasBackgroundOnlyLootDifference = false
    local liveLootChecksMatch = localLiveLootChecksum ~= ""
      and remoteLiveLootChecksum ~= ""
      and string.lower(localLiveLootChecksum) == string.lower(remoteLiveLootChecksum)
    local archiveLootChecksDiffer = localArchiveLootChecksum ~= ""
      and remoteArchiveLootChecksum ~= ""
      and string.lower(localArchiveLootChecksum) ~= string.lower(remoteArchiveLootChecksum)
    if liveLootChecksMatch and archiveLootChecksDiffer
      and (profileSyncLocalOps.hasComparedDomain(candidate.remoteNewerDomains, "loot") or profileSyncLocalOps.hasComparedDomain(candidate.localNewerDomains, "loot"))
    then
      effectiveRemoteNewerDomains = profileSyncLocalOps.filterProfileSyncDomainList(effectiveRemoteNewerDomains, "loot")
      effectiveLocalNewerDomains = profileSyncLocalOps.filterProfileSyncDomainList(effectiveLocalNewerDomains, "loot")
      hasBackgroundOnlyLootDifference = true
    elseif liveLootChecksMatch
      and (profileSyncLocalOps.hasComparedDomain(candidate.remoteNewerDomains, "loot") or profileSyncLocalOps.hasComparedDomain(candidate.localNewerDomains, "loot"))
    then
      effectiveRemoteNewerDomains = profileSyncLocalOps.filterProfileSyncDomainList(effectiveRemoteNewerDomains, "loot")
      effectiveLocalNewerDomains = profileSyncLocalOps.filterProfileSyncDomainList(effectiveLocalNewerDomains, "loot")
      hasBackgroundOnlyLootDifference = true
    elseif type(preciseByDomain.loot) == "table" and #liveLootDifferentSubdomains == 0
      and (profileSyncLocalOps.hasComparedDomain(candidate.remoteNewerDomains, "loot") or profileSyncLocalOps.hasComparedDomain(candidate.localNewerDomains, "loot"))
    then
      effectiveRemoteNewerDomains = profileSyncLocalOps.filterProfileSyncDomainList(effectiveRemoteNewerDomains, "loot")
      effectiveLocalNewerDomains = profileSyncLocalOps.filterProfileSyncDomainList(effectiveLocalNewerDomains, "loot")
      hasBackgroundOnlyLootDifference = (#statsLootDifferentSubdomains + #archiveLootDifferentSubdomains) > 0
    end

    local effectiveComparison = rawComparison
    if rawComparison == "same" or rawComparison == "local_newer" or rawComparison == "remote_newer" or rawComparison == "diverged" then
      effectiveComparison = profileSyncLocalOps.resolveProfileSyncComparisonFromDomains(
        TrimText(candidate.localProfileId),
        TrimText(candidate.profileId),
        effectiveRemoteNewerDomains,
        effectiveLocalNewerDomains
      )
    end

    local generationState = generationOps.GetMemberTransferGenerationState(type(activeSession) == "table" and activeSession.id or "", candidate.memberKey)
    local liveLaneState = {
      sent = type(generationState.sent) == "table" and generationState.sent.live or nil,
      applied = type(generationState.applied) == "table" and generationState.applied.live or nil,
    }
    local generationConverged = false
    local liveLaneConverged = generationOps.HasRecentGenerationConvergence(candidate, liveLaneState)
    local hasBootstrapCriticalDifference = profileSyncLocalOps.hasComparedDomain(effectiveRemoteNewerDomains, "settings")
      or profileSyncLocalOps.hasComparedDomain(effectiveRemoteNewerDomains, "permissions")
      or profileSyncLocalOps.hasComparedDomain(effectiveLocalNewerDomains, "settings")
      or profileSyncLocalOps.hasComparedDomain(effectiveLocalNewerDomains, "permissions")
    local hasComparedLootDomain = profileSyncLocalOps.hasComparedDomain(candidate.remoteNewerDomains, "loot")
      or profileSyncLocalOps.hasComparedDomain(candidate.localNewerDomains, "loot")
    local liveStateAligned = (not hasComparedLootDomain) or liveLootChecksMatch
    if liveLaneConverged and liveStateAligned and not hasBootstrapCriticalDifference then
      local convergedRemoteDomains = profileSyncLocalOps.filterProfileSyncDomains(effectiveRemoteNewerDomains, { "loot", "session" })
      local convergedLocalDomains = profileSyncLocalOps.filterProfileSyncDomains(effectiveLocalNewerDomains, { "loot", "session" })
      local convergedComparison = profileSyncLocalOps.resolveProfileSyncComparisonFromDomains(
        TrimText(candidate.localProfileId),
        TrimText(candidate.profileId),
        convergedRemoteDomains,
        convergedLocalDomains
      )
      if convergedComparison == "same" then
        effectiveRemoteNewerDomains = convergedRemoteDomains
        effectiveLocalNewerDomains = convergedLocalDomains
        effectiveComparison = "same"
        generationConverged = true
      end
    end

    return {
      comparison = effectiveComparison,
      remoteNewerDomains = effectiveRemoteNewerDomains,
      localNewerDomains = effectiveLocalNewerDomains,
      liveLootDifferentSubdomains = CloneProfileSyncSubdomainList(liveLootDifferentSubdomains),
      statsLootDifferentSubdomains = CloneProfileSyncSubdomainList(statsLootDifferentSubdomains),
      archiveLootDifferentSubdomains = CloneProfileSyncSubdomainList(archiveLootDifferentSubdomains),
      backgroundOnlyLootDifference = hasBackgroundOnlyLootDifference,
      liveLootAligned = liveLootChecksMatch,
      generationConverged = generationConverged,
      transferGenerations = generationState,
    }
  end

  profileSyncLocalOps.hasComparedDomain = function(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

  profileSyncLocalOps.resolveBootstrapCandidateState = function(candidate)
    candidate = type(candidate) == "table" and candidate or {}
    local comparison = string.lower(TrimText(candidate.comparison))
    if comparison == "different_lineage" then
      return "lineage"
    end
    if comparison == "unknown" or TrimText(candidate.profileId) == "" then
      return "pending"
    end

    local settingsRemote = profileSyncLocalOps.hasComparedDomain(candidate.remoteNewerDomains, "settings")
    local settingsLocal = profileSyncLocalOps.hasComparedDomain(candidate.localNewerDomains, "settings")
    local permissionsRemote = profileSyncLocalOps.hasComparedDomain(candidate.remoteNewerDomains, "permissions")
    local permissionsLocal = profileSyncLocalOps.hasComparedDomain(candidate.localNewerDomains, "permissions")

    if not settingsRemote and not settingsLocal and not permissionsRemote and not permissionsLocal then
      return "ready"
    end
    if settingsRemote or permissionsRemote then
      return "review"
    end
    if settingsLocal or permissionsLocal then
      return "pending"
    end
    return "unknown"
  end

  profileSyncLocalOps.buildLocalProfileRevisionContext = function(profileName, activeSession)
    local resolvedProfileName = TrimText(profileName)
    local localProfileId = resolvedProfileName ~= "" and TrimText(select(1, GetLootProfileId(resolvedProfileName)) or "") or ""
    local localRevisionSummary = NormalizeRevisionSummary(
      resolvedProfileName ~= "" and GetLootProfileRevisionSummary(resolvedProfileName) or nil,
      resolvedProfileName,
      localProfileId
    )
    local localSubchecksumManifest = resolvedProfileName ~= "" and type(GetLootProfileSubchecksumManifest) == "function"
      and GetLootProfileSubchecksumManifest(resolvedProfileName)
      or nil
    local localLiveLootChecksum = profileSyncLocalOps.buildLiveLootChecksum(localSubchecksumManifest, activeSession)
    local localArchiveLootChecksum = profileSyncLocalOps.buildProfileSyncArchiveLootChecksum(localSubchecksumManifest, activeSession)
    localRevisionSummary.liveLootChecksum = localLiveLootChecksum
    localRevisionSummary.archiveLootChecksum = localArchiveLootChecksum
    local localRevisionSignature = 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")
    return {
      profileName = resolvedProfileName,
      profileId = localProfileId,
      revisionSummary = localRevisionSummary,
      subchecksumManifest = localSubchecksumManifest,
      liveLootChecksum = localLiveLootChecksum,
      archiveLootChecksum = localArchiveLootChecksum,
      revisionSignature = localRevisionSignature,
    }
  end

  local function GetActiveProfileSyncCandidates()
    profileSyncLocalOps.pruneExpiredMemberPreciseStates(GetNow())
    local activeSession, profileName = GetActiveLootSession()
    if not activeSession or not profileName then
      return {}
    end

    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    local hostKey = NormalizeCharacterKey(activeSession.host or "")
    local isHostView = hostKey ~= "" and string.lower(hostKey) == string.lower(selfKey)
    local localRevisionContext = profileSyncLocalOps.buildLocalProfileRevisionContext(profileName, activeSession)
    local localProfileId = TrimText(type(localRevisionContext) == "table" and localRevisionContext.profileId or "")
    local localRevisionSummary = type(localRevisionContext) == "table" and localRevisionContext.revisionSummary or BuildEmptyRevisionSummary(profileName, localProfileId)
    local localSubchecksumManifest = type(localRevisionContext) == "table" and localRevisionContext.subchecksumManifest or nil
    local localLiveLootChecksum = TrimText(type(localRevisionContext) == "table" and localRevisionContext.liveLootChecksum or "")
    local localArchiveLootChecksum = TrimText(type(localRevisionContext) == "table" and localRevisionContext.archiveLootChecksum or "")
    local localRevisionSignature = TrimText(type(localRevisionContext) == "table" and localRevisionContext.revisionSignature or "")

    local candidates = {}
    for memberKey, member in pairs(activeSession.members or {}) do
      local resolvedKey = NormalizeCharacterKey(memberKey)
      local shouldCompareMember = resolvedKey ~= ""
        and resolvedKey ~= selfKey
        and type(member) == "table"
        and tostring(member.status or "JOINED") == "JOINED"
        and (isHostView or hostKey == "" or string.lower(resolvedKey) == string.lower(hostKey))
      if shouldCompareMember then
        local remoteRevisionSummary = BuildRemoteMemberRevisionSummary(profileName, member)
        local comparison, remoteNewerDomains, localNewerDomains = profileSyncLocalOps.resolveProfileSyncComparison(localRevisionSummary, remoteRevisionSummary)
        local candidate = {
          memberKey = resolvedKey,
          isSessionHost = string.lower(TrimText(activeSession.host or "")) == string.lower(resolvedKey),
          role = TrimText(member.role),
          addonVersion = TrimText(member.addonVersion),
          className = TrimText(member.className),
          classFile = TrimText(member.classFile),
          specName = TrimText(member.specName),
          specIcon = TrimText(member.specIcon),
          profileId = remoteRevisionSummary.profileId,
          settings = remoteRevisionSummary.settings,
          permissions = remoteRevisionSummary.permissions,
          operational = remoteRevisionSummary.operational,
          loot = remoteRevisionSummary.loot,
          session = remoteRevisionSummary.session,
          settingsChecksum = remoteRevisionSummary.settingsChecksum,
          permissionsChecksum = remoteRevisionSummary.permissionsChecksum,
          operationalChecksum = remoteRevisionSummary.operationalChecksum,
          lootChecksum = remoteRevisionSummary.lootChecksum,
          sessionChecksum = remoteRevisionSummary.sessionChecksum,
          updatedAt = remoteRevisionSummary.updatedAt,
          localLiveLootChecksum = localLiveLootChecksum,
          localArchiveLootChecksum = localArchiveLootChecksum,
          remoteLiveLootChecksum = TrimText(type(member) == "table" and member.liveLootChecksum or ""),
          remoteArchiveLootChecksum = TrimText(type(member) == "table" and member.archiveLootChecksum or ""),
          applyAckPhase = TrimText(type(member) == "table" and member.profileApplyAckPhase or ""),
          applyQueuedAt = math.max(0, tonumber(type(member) == "table" and member.profileApplyQueuedAt or 0) or 0),
          applyPendingId = TrimText(type(member) == "table" and member.profileApplyPendingId or ""),
          applyPendingKind = TrimText(type(member) == "table" and member.profileApplyPendingKind or ""),
          comparison = comparison,
          remoteNewerDomains = remoteNewerDomains,
          localNewerDomains = localNewerDomains,
          remoteDomainText = profileSyncLocalOps.formatProfileRevisionDomains(remoteNewerDomains),
          localDomainText = profileSyncLocalOps.formatProfileRevisionDomains(localNewerDomains),
        }
        candidate.localProfileId = localProfileId
        candidate.localRevisionSignature = localRevisionSignature
        candidate.bootstrapState = profileSyncLocalOps.resolveBootstrapCandidateState(candidate)
        if comparison == "different_lineage" or comparison == "unknown" or TrimText(remoteRevisionSummary.profileId) == "" then
          InvalidateMemberPreciseSyncState(activeSession.id, resolvedKey)
        else
          EnsureCurrentMemberPreciseSyncState(activeSession.id, resolvedKey, remoteRevisionSummary)
        end
        HydratePersistedSessionMemberBaseline(activeSession.id, localProfileId, profileName, resolvedKey, remoteRevisionSummary)
        local memberSubchecksumState = GetMemberSubchecksumState(activeSession.id, resolvedKey)
        local preciseRequestState = profileSyncLocalOps.getPreciseSubchecksumRequestState(activeSession.id, resolvedKey)
        local preciseDiff = profileSyncLocalOps.buildCandidatePreciseDiffInfo(
          candidate,
          localSubchecksumManifest,
          memberSubchecksumState
        )
        -- A reply can be valid while containing no leaf-level differences. Keep
        -- that distinct from a member that has not answered the detail request.
        INTERNAL_API.LIDCOUNCIL_ProjectPreciseRequestState_Impl(candidate, preciseRequestState)
        candidate.preciseScopeDomains = preciseDiff.scopeDomains
        candidate.preciseDifferentSubdomains = preciseDiff.differentSubdomains
        candidate.preciseDifferentSubdomainsByDomain = preciseDiff.differentSubdomainsByDomain
        candidate.hostRepairDomains = profileSyncLocalOps.buildFilteredCandidateDomains(candidate.localNewerDomains, candidate.remoteNewerDomains)
        candidate.memberRepairDomains = profileSyncLocalOps.buildFilteredCandidateDomains(candidate.remoteNewerDomains, candidate.localNewerDomains)
        candidate.precisePushSubdomains = {}
        for _, domain in ipairs(candidate.hostRepairDomains) do
          for _, subdomain in ipairs(preciseDiff.differentSubdomainsByDomain[domain] or {}) do
            candidate.precisePushSubdomains[#candidate.precisePushSubdomains + 1] = subdomain
          end
        end
        candidate.precisePullSubdomains = {}
        for _, domain in ipairs(candidate.memberRepairDomains) do
          for _, subdomain in ipairs(preciseDiff.differentSubdomainsByDomain[domain] or {}) do
            candidate.precisePullSubdomains[#candidate.precisePullSubdomains + 1] = subdomain
          end
        end
        candidate.precisePreviewSubdomains = preciseDiff.previewSubdomains
        candidate.preciseScopeTextByDomain = {}
        candidate.preciseDetailLoaded = #preciseDiff.scopeDomains > 0
        candidate.preciseNoDifferences = preciseRequestState.complete == true and #preciseDiff.differentSubdomains == 0
        candidate.preciseActionable = preciseRequestState.complete == true and #preciseDiff.differentSubdomains > 0
        for domain, domainInfo in pairs(preciseDiff.byDomain or {}) do
          candidate.preciseScopeTextByDomain[domain] = TrimText(type(domainInfo) == "table" and domainInfo.text or "")
        end
        candidate.precisePushReady = profileSyncLocalOps.hasPreciseCoverageForDomains(candidate.hostRepairDomains, preciseDiff.differentSubdomainsByDomain)
        candidate.precisePullReady = profileSyncLocalOps.hasPreciseCoverageForDomains(candidate.memberRepairDomains, preciseDiff.differentSubdomainsByDomain)
        candidate.precisePreviewReady = profileSyncLocalOps.hasPreciseCoverageForDomains(
          MergeProfileRevisionDomains(candidate.remoteNewerDomains, candidate.localNewerDomains),
          preciseDiff.differentSubdomainsByDomain
        )
        candidate.precisePushText = ""
        candidate.precisePullText = ""
        candidate.precisePreviewText = ""
        if candidate.precisePushReady then
          local labels = {}
          for _, subdomain in ipairs(candidate.precisePushSubdomains) do
            labels[#labels + 1] = type(GetLootProfileSubdomainLabel) == "function"
              and GetLootProfileSubdomainLabel(subdomain)
              or subdomain
          end
          candidate.precisePushText = table.concat(labels, ", ")
        end
        if candidate.precisePullReady then
          local labels = {}
          for _, subdomain in ipairs(candidate.precisePullSubdomains) do
            labels[#labels + 1] = type(GetLootProfileSubdomainLabel) == "function"
              and GetLootProfileSubdomainLabel(subdomain)
              or subdomain
          end
          candidate.precisePullText = table.concat(labels, ", ")
        end
        if candidate.precisePreviewReady then
          local labels = {}
          for _, subdomain in ipairs(candidate.precisePreviewSubdomains) do
            labels[#labels + 1] = type(GetLootProfileSubdomainLabel) == "function"
              and GetLootProfileSubdomainLabel(subdomain)
              or subdomain
          end
          candidate.precisePreviewText = table.concat(labels, ", ")
        end
        local patchManifestState = GetMemberPatchManifestState(activeSession.id, resolvedKey)
        candidate.patchPushSubdomains = type(FilterLootProfilePatchCapableSubdomains) == "function"
          and FilterLootProfilePatchCapableSubdomains(candidate.precisePushSubdomains)
          or {}
        candidate.patchPullSubdomains = type(FilterLootProfilePatchCapableSubdomains) == "function"
          and FilterLootProfilePatchCapableSubdomains(candidate.precisePullSubdomains)
          or {}
        candidate.patchPreviewSubdomains = type(FilterLootProfilePatchCapableSubdomains) == "function"
          and FilterLootProfilePatchCapableSubdomains(candidate.precisePreviewSubdomains)
          or {}
        candidate.patchPushReady = candidate.precisePushReady
          and profileSyncLocalOps.hasLoadedPatchManifestSubdomains(activeSession.id, resolvedKey, candidate.patchPushSubdomains)
        candidate.patchDetailLoaded = type(patchManifestState) == "table" and type(patchManifestState.bySubdomain) == "table"
        candidate.patchPushText = ""
        if #candidate.patchPushSubdomains > 0 then
          local labels = {}
          for _, subdomain in ipairs(candidate.patchPushSubdomains) do
            labels[#labels + 1] = type(GetLootProfileSubdomainLabel) == "function"
              and GetLootProfileSubdomainLabel(subdomain)
              or subdomain
          end
          candidate.patchPushText = table.concat(labels, ", ")
        end
        candidate.patchPullText = ""
        if #candidate.patchPullSubdomains > 0 then
          local labels = {}
          for _, subdomain in ipairs(candidate.patchPullSubdomains) do
            labels[#labels + 1] = type(GetLootProfileSubdomainLabel) == "function"
              and GetLootProfileSubdomainLabel(subdomain)
              or subdomain
          end
          candidate.patchPullText = table.concat(labels, ", ")
        end
        candidate.patchPreviewText = ""
        if #candidate.patchPreviewSubdomains > 0 then
          local labels = {}
          for _, subdomain in ipairs(candidate.patchPreviewSubdomains) do
            labels[#labels + 1] = type(GetLootProfileSubdomainLabel) == "function"
              and GetLootProfileSubdomainLabel(subdomain)
              or subdomain
          end
          candidate.patchPreviewText = table.concat(labels, ", ")
        end
        local effectiveComparison = profileSyncLocalOps.buildEffectiveCandidateComparison(candidate, activeSession)
        candidate.effectiveComparison = TrimText(type(effectiveComparison) == "table" and effectiveComparison.comparison or comparison)
        candidate.effectiveRemoteNewerDomains = CloneProfileSyncDomainList(
          type(effectiveComparison) == "table" and effectiveComparison.remoteNewerDomains or remoteNewerDomains
        )
        candidate.effectiveLocalNewerDomains = CloneProfileSyncDomainList(
          type(effectiveComparison) == "table" and effectiveComparison.localNewerDomains or localNewerDomains
        )
        candidate.effectiveRemoteDomainText = profileSyncLocalOps.formatProfileRevisionDomains(candidate.effectiveRemoteNewerDomains)
        candidate.effectiveLocalDomainText = profileSyncLocalOps.formatProfileRevisionDomains(candidate.effectiveLocalNewerDomains)
        candidate.effectiveHostRepairDomains = profileSyncLocalOps.buildFilteredCandidateDomains(
          candidate.effectiveLocalNewerDomains,
          candidate.effectiveRemoteNewerDomains
        )
        candidate.effectiveMemberRepairDomains = profileSyncLocalOps.buildFilteredCandidateDomains(
          candidate.effectiveRemoteNewerDomains,
          candidate.effectiveLocalNewerDomains
        )
        candidate.liveLootDifferentSubdomains = CloneProfileSyncSubdomainList(
          type(effectiveComparison) == "table" and effectiveComparison.liveLootDifferentSubdomains or {}
        )
        candidate.statsLootDifferentSubdomains = CloneProfileSyncSubdomainList(
          type(effectiveComparison) == "table" and effectiveComparison.statsLootDifferentSubdomains or {}
        )
        candidate.archiveLootDifferentSubdomains = CloneProfileSyncSubdomainList(
          type(effectiveComparison) == "table" and effectiveComparison.archiveLootDifferentSubdomains or {}
        )
        candidate.backgroundOnlyLootDifference = type(effectiveComparison) == "table"
          and effectiveComparison.backgroundOnlyLootDifference == true
          or false
        candidate.liveLootAligned = type(effectiveComparison) == "table"
          and effectiveComparison.liveLootAligned == true
          or false
        candidate.generationConverged = type(effectiveComparison) == "table"
          and effectiveComparison.generationConverged == true
          or false
        candidate.visibleState = profileSyncLocalOps.buildCandidateVisibleState(candidate)
        candidate.transferGenerations = type(effectiveComparison) == "table"
          and type(effectiveComparison.transferGenerations) == "table"
          and effectiveComparison.transferGenerations
          or generationOps.GetMemberTransferGenerationState(activeSession.id, resolvedKey)
        candidate.safeRecommendation = profileSyncLocalOps.buildCandidateSafeRecommendation(candidate)
        candidates[#candidates + 1] = candidate
      end
    end

    local comparisonPriority = {
      remote_newer = 1,
      diverged = 2,
      unknown = 3,
      different_lineage = 4,
      same = 5,
      local_newer = 6,
    }
    table.sort(candidates, function(a, b)
      if (a.isSessionHost and not b.isSessionHost) or (b.isSessionHost and not a.isSessionHost) then
        return a.isSessionHost == true
      end
      local aPriority = comparisonPriority[TrimText(a.effectiveComparison ~= "" and a.effectiveComparison or a.comparison)] or 99
      local bPriority = comparisonPriority[TrimText(b.effectiveComparison ~= "" and b.effectiveComparison or b.comparison)] or 99
      if aPriority ~= bPriority then
        return aPriority < bPriority
      end
      return string.lower(tostring(a.memberKey or "")) < string.lower(tostring(b.memberKey or ""))
    end)

    return candidates
  end

  profileSyncLocalOps.buildEmptyProfileSyncCounts = function()
    return {
      remote_newer = 0,
      diverged = 0,
      local_newer = 0,
      same = 0,
      waiting_apply = 0,
      unknown = 0,
      different_lineage = 0,
    }, {
      ready = 0,
      pending = 0,
      review = 0,
      lineage = 0,
      unknown = 0,
    }
  end

  profileSyncLocalOps.accumulateProfileSyncCandidateCounts = function(precomputedCandidates)
    local counts, bootstrapCounts = profileSyncLocalOps.buildEmptyProfileSyncCounts()
    local candidates = type(precomputedCandidates) == "table" and precomputedCandidates or GetActiveProfileSyncCandidates()
    for _, candidate in ipairs(candidates or {}) do
      local comparison = TrimText(candidate.effectiveComparison ~= "" and candidate.effectiveComparison or candidate.comparison)
      if string.upper(TrimText(candidate.applyAckPhase)) == "QUEUED" then
        counts.waiting_apply = counts.waiting_apply + 1
      elseif counts[comparison] ~= nil then
        counts[comparison] = counts[comparison] + 1
      end
      local bootstrapState = TrimText(candidate.bootstrapState)
      if bootstrapCounts[bootstrapState] ~= nil then
        bootstrapCounts[bootstrapState] = bootstrapCounts[bootstrapState] + 1
      else
        bootstrapCounts.unknown = bootstrapCounts.unknown + 1
      end
    end
    return counts, bootstrapCounts
  end

  profileSyncLocalOps.buildRuntimeStatusSnapshot = function(activeSession, activeProfileName, isHost, counts, bootstrapCounts)
    local recentRosterEvents = {}
    for _, event in ipairs(type(profileSyncRuntimeState.recentRosterEvents) == "table"
      and profileSyncRuntimeState.recentRosterEvents or {}) do
      if type(event) == "table" then
        recentRosterEvents[#recentRosterEvents + 1] = {
          action = TrimText(event.action),
          memberKey = TrimText(event.memberKey),
          at = math.max(0, tonumber(event.at) or 0),
        }
      end
    end
    return {
      activeSession = activeSession ~= nil,
      sessionId = TrimText(activeSession and activeSession.id or ""),
      profileName = TrimText(activeProfileName or (activeSession and activeSession.profileName) or ""),
      isHost = isHost and true or false,
      candidateCounts = type(counts) == "table" and counts or {},
      bootstrapCounts = type(bootstrapCounts) == "table" and bootstrapCounts or {},
      mode = TrimText(profileSyncRuntimeState.mode),
      severity = TrimText(profileSyncRuntimeState.severity),
      message = TrimText(profileSyncRuntimeState.message),
      sender = TrimText(profileSyncRuntimeState.sender),
      updatedAt = tonumber(profileSyncRuntimeState.updatedAt) or 0,
      remoteDomains = CloneProfileSyncDomainList(profileSyncRuntimeState.remoteDomains),
      localDomains = CloneProfileSyncDomainList(profileSyncRuntimeState.localDomains),
      detailDiff = type(profileSyncRuntimeState.detailDiff) == "table" and profileSyncRuntimeState.detailDiff or nil,
      detailConflict = type(profileSyncRuntimeState.detailConflict) == "table" and profileSyncRuntimeState.detailConflict or nil,
      recentRosterEvents = recentRosterEvents,
    }
  end

  profileSyncLocalOps.pruneExpiredRuntimeStatusDetail = function(status)
    if type(status) ~= "table" then
      return status
    end
    if type(status.detailConflict) == "table"
      and math.max(0, GetNow() - math.max(0, tonumber(status.updatedAt) or 0)) > profileSyncConfig.previewConflictTtlSeconds
    then
      ClearRuntimePreviewConflictState()
      status.detailDiff = nil
      status.detailConflict = nil
    end
    return status
  end

  profileSyncLocalOps.shouldNormalizeRuntimeStatusToIdle = function(status)
    if type(status) ~= "table" then
      return false
    end
    return status.activeSession ~= true
      or status.sessionId ~= TrimText(profileSyncRuntimeState.sessionId)
      or status.profileName ~= TrimText(profileSyncRuntimeState.profileName)
  end

  profileSyncLocalOps.resetRuntimeStatusToIdle = function(status)
    status = type(status) == "table" and status or {}
    status.mode = "idle"
    status.severity = "info"
    status.message = ""
    status.sender = ""
    status.updatedAt = 0
    status.remoteDomains = {}
    status.localDomains = {}
    status.detailDiff = nil
    status.detailConflict = nil
    return status
  end

  profileSyncLocalOps.getActiveProfileSyncStatus = function(precomputedCandidates)
    local activeSession, activeProfileName = GetActiveLootSession()
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    local isHost = activeSession and NormalizeCharacterKey(activeSession.host or "") == selfKey or false
    local counts, bootstrapCounts = profileSyncLocalOps.buildEmptyProfileSyncCounts()
    if isHost then
      counts, bootstrapCounts = profileSyncLocalOps.accumulateProfileSyncCandidateCounts(precomputedCandidates)
    end
    local status = profileSyncLocalOps.buildRuntimeStatusSnapshot(activeSession, activeProfileName, isHost, counts, bootstrapCounts)
    profileSyncLocalOps.pruneExpiredRuntimeStatusDetail(status)
    if profileSyncLocalOps.shouldNormalizeRuntimeStatusToIdle(status) then
      profileSyncLocalOps.resetRuntimeStatusToIdle(status)
    end
    return status
  end

  profileSyncLocalOps.buildCurrentSessionCandidateLookup = function(precomputedCandidates)
    local candidateByMemberKey = {}
    for _, candidate in ipairs(type(precomputedCandidates) == "table" and precomputedCandidates or GetActiveProfileSyncCandidates() or {}) do
      local candidateKey = NormalizeCharacterKey(type(candidate) == "table" and candidate.memberKey or "")
      if candidateKey ~= "" then
        candidateByMemberKey[candidateKey] = candidate
      end
    end
    return candidateByMemberKey
  end

  profileSyncLocalOps.findSessionMember = function(session, memberKey)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if resolvedMemberKey == "" or type(session) ~= "table" or type(session.members) ~= "table" then
      return nil
    end
    local direct = session.members[resolvedMemberKey]
    if type(direct) == "table" then
      return direct
    end
    for storedKey, member in pairs(session.members or {}) do
      if NormalizeCharacterKey(storedKey) == resolvedMemberKey and type(member) == "table" then
        return member
      end
    end
    return nil
  end

  profileSyncLocalOps.resolveCandidateCurrentSessionSyncState = function(candidate)
    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 blockingDomains = {}
    for _, domain in ipairs(type(candidate.effectiveRemoteNewerDomains) == "table" and candidate.effectiveRemoteNewerDomains or candidate.remoteNewerDomains or {}) do
      blockingDomains[string.lower(TrimText(domain))] = true
    end
    for _, domain in ipairs(type(candidate.effectiveLocalNewerDomains) == "table" and candidate.effectiveLocalNewerDomains or candidate.localNewerDomains or {}) do
      blockingDomains[string.lower(TrimText(domain))] = true
    end
    if blockingDomains.settings or blockingDomains.permissions then
      return "PARTIAL"
    end
    if candidate.generationConverged == true then
      return "SYNCED"
    end
    if not blockingDomains.loot then
      return "SYNCED"
    end
    if candidate.liveLootAligned == true then
      return "SYNCED"
    end
    if candidate.preciseDetailLoaded ~= true then
      return nil
    end
    return #(type(candidate.liveLootDifferentSubdomains) == "table" and candidate.liveLootDifferentSubdomains or {}) > 0
      and "PARTIAL"
      or "SYNCED"
  end

  profileSyncLocalOps.resolveSessionMemberSyncAgainstReference = function(member, referenceMember)
    if type(member) ~= "table" or type(referenceMember) ~= "table" then
      return nil
    end

    local referenceProfileId = TrimText(referenceMember.sharedProfileId)
    local memberProfileId = TrimText(member.sharedProfileId)
    if referenceProfileId == "" or memberProfileId == "" then
      return nil
    end
    if string.lower(referenceProfileId) ~= string.lower(memberProfileId) then
      return "PARTIAL"
    end

    local referenceOperationalRevision = math.max(0, tonumber(referenceMember.operationalRevision) or 0)
    local referenceLootRevision = math.max(0, tonumber(referenceMember.lootRevision) or referenceOperationalRevision)
    local referenceSettingsRevision = math.max(0, tonumber(referenceMember.settingsRevision) or 0)
    local referencePermissionsRevision = math.max(0, tonumber(referenceMember.permissionsRevision) or 0)
    local referenceSettingsChecksum = TrimText(referenceMember.settingsChecksum)
    local referencePermissionsChecksum = TrimText(referenceMember.permissionsChecksum)
    local referenceOperationalChecksum = TrimText(referenceMember.operationalChecksum)
    local referenceLootChecksum = TrimText(referenceMember.lootChecksum)
    if referenceLootChecksum == "" then
      referenceLootChecksum = referenceOperationalChecksum
    end
    local referenceLiveLootChecksum = TrimText(referenceMember.liveLootChecksum)

    local memberOperationalRevision = math.max(0, tonumber(member.operationalRevision) or 0)
    local memberLootRevision = math.max(0, tonumber(member.lootRevision) or memberOperationalRevision)
    local memberSettingsRevision = math.max(0, tonumber(member.settingsRevision) or 0)
    local memberPermissionsRevision = math.max(0, tonumber(member.permissionsRevision) or 0)
    local memberSettingsChecksum = TrimText(member.settingsChecksum)
    local memberPermissionsChecksum = TrimText(member.permissionsChecksum)
    local memberOperationalChecksum = TrimText(member.operationalChecksum)
    local memberLootChecksum = TrimText(member.lootChecksum)
    if memberLootChecksum == "" then
      memberLootChecksum = memberOperationalChecksum
    end
    local memberLiveLootChecksum = TrimText(member.liveLootChecksum)

    local hasSettingsChecksum = referenceSettingsChecksum ~= "" and memberSettingsChecksum ~= ""
    local hasPermissionsChecksum = referencePermissionsChecksum ~= "" and memberPermissionsChecksum ~= ""
    local hasLootChecksum = referenceLootChecksum ~= "" and memberLootChecksum ~= ""

    if hasSettingsChecksum and referenceSettingsChecksum ~= memberSettingsChecksum then
      return "PARTIAL"
    end
    if hasPermissionsChecksum and referencePermissionsChecksum ~= memberPermissionsChecksum then
      return "PARTIAL"
    end
    if referenceLiveLootChecksum ~= "" and memberLiveLootChecksum ~= "" and referenceLiveLootChecksum == memberLiveLootChecksum then
      return "SYNCED"
    end
    if hasLootChecksum and referenceLootChecksum ~= 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

  profileSyncLocalOps.resolveBootstrapDomainMatch = function(localRevision, localChecksum, memberRevision, memberChecksum)
    local resolvedLocalChecksum = TrimText(localChecksum)
    local resolvedMemberChecksum = TrimText(memberChecksum)
    if resolvedLocalChecksum ~= "" and resolvedMemberChecksum ~= "" then
      return string.lower(resolvedLocalChecksum) == string.lower(resolvedMemberChecksum)
    end
    return math.max(0, tonumber(localRevision) or 0) == math.max(0, tonumber(memberRevision) or 0)
  end

  profileSyncLocalOps.buildCurrentSessionDisplayContext = function(session, profileName, precomputedCandidates)
    if type(session) ~= "table" then
      return nil
    end
    local resolvedProfileName = FirstNonEmptyText(profileName, session.profileName, session.remoteProfileName)
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    local sessionHost = NormalizeCharacterKey(session.host or "")
    local isHostView = selfKey ~= "" and sessionHost ~= "" and selfKey == sessionHost
    local localRevisionContext = profileSyncLocalOps.buildLocalProfileRevisionContext(resolvedProfileName, session)
    local localProfileId = TrimText(type(localRevisionContext) == "table" and localRevisionContext.profileId or "")
    local localSummary = type(localRevisionContext) == "table" and localRevisionContext.revisionSummary or BuildEmptyRevisionSummary(resolvedProfileName, localProfileId)
    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 localLootRevision = math.max(0, tonumber(type(localSummary) == "table" and localSummary.loot) or tonumber(type(localSummary) == "table" and localSummary.operational) or 0)
    local localSettingsChecksum = TrimText(type(localSummary) == "table" and localSummary.settingsChecksum or "")
    local localPermissionsChecksum = TrimText(type(localSummary) == "table" and localSummary.permissionsChecksum or "")
    local localLootChecksum = TrimText(type(localSummary) == "table" and localSummary.lootChecksum or "")
    local localLiveLootChecksum = TrimText(type(localRevisionContext) == "table" and localRevisionContext.liveLootChecksum or "")
    if localLootChecksum == "" then
      localLootChecksum = TrimText(type(localSummary) == "table" and localSummary.operationalChecksum or "")
    end

    return {
      session = session,
      resolvedProfileName = resolvedProfileName,
      selfKey = selfKey,
      sessionHost = sessionHost,
      isHostView = isHostView,
      localProfileId = localProfileId,
      localSettingsRevision = localSettingsRevision,
      localPermissionsRevision = localPermissionsRevision,
      localLootRevision = localLootRevision,
      localSettingsChecksum = localSettingsChecksum,
      localPermissionsChecksum = localPermissionsChecksum,
      localLootChecksum = localLootChecksum,
      localLiveLootChecksum = localLiveLootChecksum,
      candidateByMemberKey = profileSyncLocalOps.buildCurrentSessionCandidateLookup(precomputedCandidates),
    }
  end

  profileSyncLocalOps.resolveCurrentSessionSyncState = function(context, member, memberKey)
    if type(context) ~= "table" or type(member) ~= "table" then
      return "PENDING"
    end
    local status = string.upper(TrimText(member.status or "JOINED"))
    if status == "DECLINED" then
      return "DECLINED"
    end

    local resolvedKey = NormalizeCharacterKey(memberKey ~= "" and memberKey or member.name or "")
    local isHostRow = resolvedKey ~= "" and resolvedKey == context.sessionHost
    if tonumber(member.lastSyncAt) and isHostRow then
      return "SYNCED"
    end

    if tonumber(member.lastSyncAt) and TrimText(member.addonVersion) ~= "" then
      if not context.isHostView then
        if resolvedKey == context.selfKey and context.sessionHost ~= "" then
          local selfVsHostState = profileSyncLocalOps.resolveCandidateCurrentSessionSyncState(context.candidateByMemberKey[context.sessionHost])
          if selfVsHostState ~= nil then
            return selfVsHostState
          end
        end

        local hostReferenceState = profileSyncLocalOps.resolveSessionMemberSyncAgainstReference(
          member,
          profileSyncLocalOps.findSessionMember(context.session, context.sessionHost)
        )
        if hostReferenceState ~= nil then
          return hostReferenceState
        end
        return "PENDING"
      end

      local memberProfileId = TrimText(member.sharedProfileId)
      if context.localProfileId == "" or memberProfileId == "" or string.lower(context.localProfileId) ~= string.lower(memberProfileId) then
        return "PARTIAL"
      end

      local candidateState = profileSyncLocalOps.resolveCandidateCurrentSessionSyncState(context.candidateByMemberKey[resolvedKey])
      if candidateState ~= nil then
        return candidateState
      end

      local memberSettingsChecksum = TrimText(member.settingsChecksum)
      local memberPermissionsChecksum = TrimText(member.permissionsChecksum)
      local memberOperationalChecksum = TrimText(member.operationalChecksum)
      local memberLootChecksum = TrimText(member.lootChecksum)
      if memberLootChecksum == "" then
        memberLootChecksum = memberOperationalChecksum
      end
      local memberLiveLootChecksum = TrimText(member.liveLootChecksum)
      local hasSettingsChecksum = context.localSettingsChecksum ~= "" and memberSettingsChecksum ~= ""
      local hasPermissionsChecksum = context.localPermissionsChecksum ~= "" and memberPermissionsChecksum ~= ""
      local hasLootChecksum = context.localLootChecksum ~= "" and memberLootChecksum ~= ""

      if hasSettingsChecksum and context.localSettingsChecksum ~= memberSettingsChecksum then
        return "PARTIAL"
      end
      if hasPermissionsChecksum and context.localPermissionsChecksum ~= memberPermissionsChecksum then
        return "PARTIAL"
      end
      if context.localLiveLootChecksum ~= "" and memberLiveLootChecksum ~= "" and context.localLiveLootChecksum == memberLiveLootChecksum then
        return "SYNCED"
      end
      if hasLootChecksum and context.localLootChecksum ~= memberLootChecksum then
        return "PARTIAL"
      end
      if hasSettingsChecksum and hasPermissionsChecksum and hasLootChecksum then
        return "SYNCED"
      end

      if context.localSettingsRevision == math.max(0, tonumber(member.settingsRevision) or 0)
          and context.localPermissionsRevision == math.max(0, tonumber(member.permissionsRevision) or 0)
          and context.localLootRevision == math.max(0, tonumber(member.lootRevision) or tonumber(member.operationalRevision) or 0) then
        return "SYNCED"
      end
      return "PARTIAL"
    end
    if tonumber(member.lastSyncAt) then
      return "PARTIAL"
    end
    return "PENDING"
  end

  profileSyncLocalOps.resolveCurrentSessionBootstrapState = function(context, member, memberKey)
    if type(context) ~= "table" or type(member) ~= "table" then
      return "PENDING"
    end
    local status = string.upper(TrimText(member.status or "JOINED"))
    if status == "DECLINED" then
      return "DECLINED"
    end

    local resolvedKey = NormalizeCharacterKey(memberKey ~= "" and memberKey or member.name or "")
    if resolvedKey ~= "" and resolvedKey == context.sessionHost then
      return "READY"
    end
    if resolvedKey ~= "" and resolvedKey == context.selfKey then
      if context.session.sharedProfileReady == false then
        return "PENDING"
      end
      return "READY"
    end
    if not tonumber(member.lastSyncAt) then
      return "PENDING"
    end

    if TrimText(member.addonVersion) == "" or context.resolvedProfileName == "" or context.localProfileId == "" then
      return "PENDING"
    end

    local memberProfileId = TrimText(member.sharedProfileId)
    if memberProfileId == "" then
      return "PENDING"
    end
    if string.lower(context.localProfileId) ~= string.lower(memberProfileId) then
      return "REVIEW"
    end

    local settingsMatch = profileSyncLocalOps.resolveBootstrapDomainMatch(
      context.localSettingsRevision,
      context.localSettingsChecksum,
      tonumber(member.settingsRevision) or 0,
      member.settingsChecksum
    )
    local permissionsMatch = profileSyncLocalOps.resolveBootstrapDomainMatch(
      context.localPermissionsRevision,
      context.localPermissionsChecksum,
      tonumber(member.permissionsRevision) or 0,
      member.permissionsChecksum
    )
    if settingsMatch and permissionsMatch then
      return "READY"
    end

    if (tonumber(member.settingsRevision) or 0) > context.localSettingsRevision
      or (tonumber(member.permissionsRevision) or 0) > context.localPermissionsRevision
    then
      return "REVIEW"
    end
    return "PENDING"
  end

  local function BuildCurrentSessionDisplaySignature(session, profileName, precomputedCandidates)
    if type(session) ~= "table" then
      return ""
    end

    local context = profileSyncLocalOps.buildCurrentSessionDisplayContext(session, profileName, precomputedCandidates)
    if type(context) ~= "table" then
      return ""
    end

    local signatureParts = {
      session.sharedProfileReady == false and "0" or "1",
    }
    local memberEntries = {}
    for memberKey, member in pairs(type(session.members) == "table" and session.members or {}) do
      if type(member) == "table" then
        local resolvedMemberKey = NormalizeCharacterKey(memberKey ~= "" and memberKey or member.name or "")
        local memberStatus = string.upper(TrimText(member.status or "JOINED"))
        if resolvedMemberKey ~= "" and memberStatus ~= "REMOVED" then
          memberEntries[#memberEntries + 1] = table.concat({
            resolvedMemberKey,
            memberStatus,
            profileSyncLocalOps.resolveCurrentSessionSyncState(context, member, resolvedMemberKey),
            profileSyncLocalOps.resolveCurrentSessionBootstrapState(context, member, resolvedMemberKey),
          }, "\30")
        end
      end
    end
    table.sort(memberEntries)
    for _, entry in ipairs(memberEntries) do
      signatureParts[#signatureParts + 1] = entry
    end
    return table.concat(signatureParts, "\31")
  end

  profileSyncLocalOps.buildCandidateRevisionSummary = function(candidate, profileName)
    candidate = type(candidate) == "table" and candidate or {}
    return NormalizeRevisionSummary({
      profileName = TrimText(profileName),
      profileId = TrimText(candidate.profileId),
      settings = tonumber(candidate.settings) or 0,
      permissions = tonumber(candidate.permissions) or 0,
      operational = tonumber(candidate.operational) or 0,
      loot = tonumber(candidate.loot) or tonumber(candidate.operational) or 0,
      session = tonumber(candidate.session) or tonumber(candidate.operational) or 0,
      settingsChecksum = TrimText(candidate.settingsChecksum),
      permissionsChecksum = TrimText(candidate.permissionsChecksum),
      operationalChecksum = TrimText(candidate.operationalChecksum),
      lootChecksum = TrimText(candidate.lootChecksum),
      sessionChecksum = TrimText(candidate.sessionChecksum),
      updatedAt = tonumber(candidate.updatedAt) or 0,
    }, profileName, TrimText(candidate.profileId))
  end

  profileSyncLocalOps.getActiveProfileSyncConflictPreview = function(memberKey)
    local detailConflict = type(profileSyncRuntimeState.detailConflict) == "table" and profileSyncRuntimeState.detailConflict or nil
    if type(detailConflict) ~= "table" then
      return nil
    end
    if math.max(0, GetNow() - math.max(0, tonumber(profileSyncRuntimeState.updatedAt) or 0)) > profileSyncConfig.previewConflictTtlSeconds then
      ClearRuntimePreviewConflictState()
      return nil
    end
    local requestedKey = NormalizeCharacterKey(memberKey)
    if requestedKey ~= "" and requestedKey ~= NormalizeCharacterKey(detailConflict.memberKey) then
      return nil
    end
    return detailConflict
  end

  local function ApplyActiveProfilePreviewConflictResolution(memberKey, resolution)
    local activeSession, activeProfileName = GetActiveLootSession()
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if type(activeSession) ~= "table" or TrimText(activeProfileName) == "" then
      return profileSyncLocalOps.failPreviewResolutionGuard("no_active_session")
    end
    if NormalizeCharacterKey(activeSession.host or "") ~= selfKey then
      return profileSyncLocalOps.failPreviewResolutionGuard("not_host")
    end

    local detailConflict = type(profileSyncRuntimeState.detailConflict) == "table" and profileSyncRuntimeState.detailConflict or nil
    local detailSnapshotData = type(profileSyncRuntimeState.detailSnapshotData) == "string" and profileSyncRuntimeState.detailSnapshotData or nil
    local detailPreviewSummary = type(profileSyncRuntimeState.detailPreviewSummary) == "table" and profileSyncRuntimeState.detailPreviewSummary or nil
    local detailBaseSummary = type(profileSyncRuntimeState.detailBaseSummary) == "table" and profileSyncRuntimeState.detailBaseSummary or nil
    local requestedMemberKey = NormalizeCharacterKey(memberKey)
    if type(detailConflict) ~= "table" or type(detailSnapshotData) ~= "string" or type(detailPreviewSummary) ~= "table" or type(detailBaseSummary) ~= "table" then
      return profileSyncLocalOps.failPreviewResolutionGuard("missing_preview_state")
    end
    if TrimText(profileSyncRuntimeState.sessionId) ~= TrimText(activeSession.id)
      or TrimText(profileSyncRuntimeState.profileName) ~= TrimText(activeProfileName) then
      ClearRuntimePreviewConflictState()
      return profileSyncLocalOps.failPreviewResolutionGuard("stale_preview_state")
    end
    local previewAge = math.max(0, GetNow() - math.max(0, tonumber(profileSyncRuntimeState.updatedAt) or 0))
    if previewAge > profileSyncConfig.previewConflictTtlSeconds then
      ClearRuntimePreviewConflictState()
      return profileSyncLocalOps.failPreviewResolutionGuard("preview_expired")
    end
    if requestedMemberKey == "" or requestedMemberKey ~= NormalizeCharacterKey(detailConflict.memberKey) then
      return profileSyncLocalOps.failPreviewResolutionGuard("member_mismatch")
    end

    local currentLocalSummary = type(GetLootProfileRevisionSummary) == "function"
      and GetLootProfileRevisionSummary(activeProfileName)
      or BuildEmptyRevisionSummary(activeProfileName, TrimText(detailPreviewSummary.profileId))
    if not DoRevisionSummariesMatch(currentLocalSummary, detailBaseSummary, detailConflict.scopeDomains) then
      ClearRuntimePreviewConflictState()
      return profileSyncLocalOps.failPreviewResolutionGuard("local_changed_after_preview")
    end

    local matchedCandidate = nil
    for _, candidate in ipairs(GetActiveProfileSyncCandidates() or {}) do
      if NormalizeCharacterKey(type(candidate) == "table" and candidate.memberKey or "") == requestedMemberKey then
        matchedCandidate = candidate
        break
      end
    end
    if type(matchedCandidate) ~= "table" then
      ClearRuntimePreviewConflictState()
      return profileSyncLocalOps.failPreviewResolutionGuard("member_unavailable")
    end
    if not DoRevisionSummariesMatch(profileSyncLocalOps.buildCandidateRevisionSummary(matchedCandidate, activeProfileName), detailPreviewSummary, detailConflict.scopeDomains) then
      InvalidateMemberPreciseSyncState(activeSession.id, requestedMemberKey)
      ClearRuntimePreviewConflictState()
      return profileSyncLocalOps.failPreviewResolutionGuard("member_changed_after_preview")
    end

    local rowMapsBySubdomain = {}
    for _, leaf in ipairs(type(detailConflict.leaves) == "table" and detailConflict.leaves or {}) do
      if type(leaf) == "table" and TrimText(leaf.subdomain) ~= "" and type(leaf.rowMap) == "table" then
        rowMapsBySubdomain[TrimText(leaf.subdomain)] = leaf.rowMap
      end
    end

    profileSyncLocalOps.pushUndoSnapshotIfSupported(
      activeProfileName,
      "preview_resolution",
      requestedMemberKey,
      TrimText(detailConflict.profileId) ~= "" and TrimText(detailConflict.profileId) or TrimText(detailPreviewSummary.profileId),
      profileSyncLocalOps.buildUndoSnapshotSummary("applying selected preview rows", requestedMemberKey)
    )

    local ok, result = deps.ApplyLootProfileTransferConflictResolution(activeProfileName, detailSnapshotData, resolution, {
      expectedProfileId = TrimText(detailConflict.profileId) ~= "" and TrimText(detailConflict.profileId) or TrimText(detailPreviewSummary.profileId),
      sourceCharacter = requestedMemberKey,
    })
    if not ok then
      profileSyncLocalOps.printResolvedFailure(result, "Could not apply preview conflict selections.")
      return false, result
    end

    local previousCurrentSessionDisplay = BuildCurrentSessionDisplaySignature(activeSession, activeProfileName)
    local activeProfile = type(sessionRuntimeOps.getProfile) == "function" and select(1, sessionRuntimeOps.getProfile(activeProfileName)) or nil
    if type(activeProfile) == "table" and type(deps.NormalizeLootRollOptions) == "function" then
      activeSession.rollOptions = deps.NormalizeLootRollOptions(activeProfile.settings and activeProfile.settings.rollOptions)
    end
    if type(activeSession.members) == "table" then
      for storedMemberKey, member in pairs(activeSession.members) do
        if type(member) == "table" then
          member.profileMaster = type(deps.GetLootProfileMaster) == "function" and deps.GetLootProfileMaster(activeProfileName) or member.profileMaster
          member.role = type(deps.GetLootProfileRole) == "function" and deps.GetLootProfileRole(activeProfileName, storedMemberKey) or member.role
        end
      end
    end
    activeSession.sharedProfileReady = true
    activeSession.__sharedProfilePendingNoticeShown = nil
    profileSyncLocalOps.refreshHostSessionMemberState(activeProfileName, activeSession.id, {
      suppressCheckpoint = true,
    })
    local currentSectionStateChanged = previousCurrentSessionDisplay ~= BuildCurrentSessionDisplaySignature(activeSession, activeProfileName)
    ClearRuntimePreviewConflictState()

    local appliedSubdomains = type(result) == "table" and type(result.subdomains) == "table" and result.subdomains or {}
    local appliedDomains = type(result) == "table" and type(result.domains) == "table" and result.domains or {}
    if #appliedDomains > 0 or #appliedSubdomains > 0 then
      -- Applying selected member leaves changes the host baseline. The old
      -- precise proof must not satisfy the next explicit comparison request;
      -- otherwise the user has to reopen the lobby before remaining host-only
      -- leaves can be discovered and pushed.
      InvalidateMemberPreciseSyncState(activeSession.id, requestedMemberKey, {
        domains = appliedDomains,
        subdomains = appliedSubdomains,
      })
    end
    local domainCount = #appliedDomains
    local rowCount = tonumber(type(result) == "table" and result.appliedRows or 0) or 0
    local subdomainCount = tonumber(type(result) == "table" and result.appliedSubdomains or 0) or 0
    local queuedDirectRepair, directRepairStats = false, nil
    local appliedSelectionsBySubdomain = {}
    local appliedLookup = {}
    for _, subdomain in ipairs(appliedSubdomains) do
      appliedLookup[string.lower(TrimText(subdomain))] = true
    end
    for subdomain, selectedRows in pairs(type(resolution.selectionsBySubdomain) == "table" and resolution.selectionsBySubdomain or {}) do
      if appliedLookup[string.lower(TrimText(subdomain))] and type(selectedRows) == "table" and #selectedRows > 0 then
        appliedSelectionsBySubdomain[subdomain] = selectedRows
      end
    end
    if type(profileSyncLocalOps.queueSelectedPreviewRepairPropagation) == "function" and #appliedSubdomains > 0 then
      queuedDirectRepair, directRepairStats = profileSyncLocalOps.queueSelectedPreviewRepairPropagation(
        activeSession,
        activeProfileName,
        requestedMemberKey,
        appliedSubdomains,
        appliedSelectionsBySubdomain,
        rowMapsBySubdomain
      )
    end
    local resolutionMessage = profileSyncLocalOps.buildPreviewResolutionMessage(
      requestedMemberKey,
      rowCount,
      subdomainCount,
      queuedDirectRepair,
      directRepairStats
    )
    profileSyncLocalOps.recordRepairHistoryIfSupported({
      profileName = activeProfileName,
      sessionId = TrimText(activeSession.id),
      memberKey = requestedMemberKey,
      kind = "preview_resolution",
      summary = resolutionMessage,
      createdAt = GetNow(),
    })
    SetProfileSyncRuntimeState(activeSession.id, activeProfileName, "preview_resolution_applied", "success",
      resolutionMessage, {
        sender = requestedMemberKey,
        remoteDomains = domainCount > 0 and result.domains or {},
        localDomains = {},
        refreshEditor = false,
      })
    profileSyncLocalOps.printTextIfSupported(profileSyncLocalOps.buildPreviewResolutionNoticeText(requestedMemberKey, queuedDirectRepair, directRepairStats))
    profileSyncLocalOps.refreshCurrentAndSyncSections(currentSectionStateChanged, {
      defer = true,
    })
    return true, result
  end

  local function BuildUniqueLocalProfileName(preferredName, profileMaster)
    local root = deps.RootDB()
    local baseName = TrimText(preferredName)
    if baseName == "" then
      baseName = "Shared Profile"
    end
    if not root.profiles[baseName] then
      return baseName
    end

    local suffixBase = baseName
    local masterLabel = TrimText(profileMaster)
    if masterLabel ~= "" then
      masterLabel = TrimText(masterLabel:match("^[^-]+") or masterLabel)
      if masterLabel ~= "" then
        suffixBase = string.format("%s [%s]", baseName, masterLabel)
        if not root.profiles[suffixBase] then
          return suffixBase
        end
      end
    end

    local counter = 2
    while true do
      local candidate = string.format("%s (%d)", suffixBase, counter)
      if not root.profiles[candidate] then
        return candidate
      end
      counter = counter + 1
    end
  end

  local function ActivateLocalSessionProfile(profileName)
    local root = deps.RootDB()
    local resolvedProfileName = TrimText(profileName)
    if resolvedProfileName == "" or type(root.profiles) ~= "table" or type(root.profiles[resolvedProfileName]) ~= "table" then
      return false
    end

    for otherName, otherProfile in pairs(root.profiles or {}) do
      if type(otherProfile) == "table" then
        otherProfile.settings = type(otherProfile.settings) == "table" and otherProfile.settings or {}
        otherProfile.settings.enabled = tostring(otherName) == tostring(resolvedProfileName)
      end
    end

    root.currentProfile = resolvedProfileName
    root.ui = type(root.ui) == "table" and root.ui or {}
    if resolvedProfileName ~= "Simulation" then
      root.ui.lastNonSimulationProfile = resolvedProfileName
    end
    return true
  end

  profileSyncLocalOps.tryImportIncomingProfileSnapshot = function(targetProfileName, snapshotData, profileId, senderKey, transferKind, opts)
    opts = type(opts) == "table" and opts or {}
    local ok, result = profileSyncLocalOps.importTransferSnapshot(
      targetProfileName,
      snapshotData,
      profileId,
      senderKey,
      transferKind,
      opts
    )
    if not ok and opts.printFailure ~= false then
      profileSyncLocalOps.printResolvedFailure(result, FirstNonEmptyText(opts.failureText, "Could not apply incoming profile snapshot."))
    end
    return ok, result
  end

  profileSyncLocalOps.finalizeIncomingProfileApplySuccess = function(opts)
    opts = type(opts) == "table" and opts or {}
    local targetProfileName = TrimText(opts.targetProfileName)
    local sessionId = TrimText(opts.sessionId)
    local profileName = TrimText(opts.profileName)
    local runtimeStateKey = TrimText(opts.runtimeStateKey)
    local runtimeStateMessage = TrimText(opts.runtimeStateMessage)
    local senderKey = NormalizeSenderKey(opts.sender)
    local currentSectionChanged = opts.currentSectionChanged == true

    ActivateLocalSessionProfile(targetProfileName)
    local runtimeStateChanged = SetProfileSyncRuntimeState(sessionId, profileName, runtimeStateKey, TrimText(opts.runtimeStateLevel) ~= "" and TrimText(opts.runtimeStateLevel) or "success",
      runtimeStateMessage, {
        sender = senderKey,
        remoteDomains = CloneProfileSyncDomainList(opts.remoteDomains or {}),
        localDomains = CloneProfileSyncDomainList(opts.localDomains or {}),
        detailDiff = opts.detailDiff,
        skipIfSame = opts.skipIfSame == true,
        refreshEditor = false,
      })
    profileSyncLocalOps.printTextIfSupported(opts.printMessage)
    if opts.refreshSections ~= false then
      profileSyncLocalOps.refreshCurrentAndSyncSections(currentSectionChanged, {
        defer = opts.deferRefresh ~= false,
      })
    end
    return runtimeStateChanged, currentSectionChanged
  end

  profileSyncLocalOps.finalizeIncomingProfileApplyFailure = function(result, opts)
    opts = type(opts) == "table" and opts or {}
    local activeSession = type(opts.activeSession) == "table" and opts.activeSession or nil
    local sessionId = TrimText(opts.sessionId)
    local profileName = TrimText(opts.profileName)
    local targetProfileName = TrimText(opts.targetProfileName)
    local senderKey = NormalizeSenderKey(opts.sender)
    local currentSectionChanged = false

    if type(activeSession) == "table" and activeSession.id == sessionId then
      activeSession.sharedProfileReady = false
    end
    local runtimeStateChanged = SetProfileSyncRuntimeState(sessionId, profileName, TrimText(opts.runtimeStateKey), TrimText(opts.runtimeStateLevel) ~= "" and TrimText(opts.runtimeStateLevel) or "warn",
      TrimText(opts.runtimeStateMessage), {
        sender = senderKey,
        skipIfSame = opts.skipIfSame ~= false,
        refreshEditor = false,
      })
    if TrimText(opts.previousCurrentSectionState) ~= "" then
      currentSectionChanged = TrimText(opts.previousCurrentSectionState) ~= BuildCurrentSessionDisplaySignature(activeSession, targetProfileName)
    end
    if opts.refreshSections ~= false and (opts.forceRefresh == true or runtimeStateChanged or currentSectionChanged) then
      profileSyncLocalOps.refreshCurrentAndSyncSections(currentSectionChanged, {
        defer = opts.deferRefresh ~= false,
      })
    end
    if runtimeStateChanged or opts.printFailureWhenRuntimeUnchanged == true then
      profileSyncLocalOps.printResolvedFailure(result, FirstNonEmptyText(opts.failureText, "Could not apply incoming profile snapshot."))
    end
    return false, runtimeStateChanged, currentSectionChanged
  end

  profileSyncLocalOps.emitProfileSyncRuntimeNotice = function(opts)
    opts = type(opts) == "table" and opts or {}
    local sessionId = TrimText(opts.sessionId)
    local profileName = TrimText(opts.profileName)
    local runtimeStateKey = TrimText(opts.runtimeStateKey)
    local runtimeStateMessage = TrimText(opts.runtimeStateMessage)
    local runtimeStateLevel = TrimText(opts.runtimeStateLevel) ~= "" and TrimText(opts.runtimeStateLevel) or "info"
    local senderKey = NormalizeSenderKey(opts.sender)

    local runtimeStateChanged = SetProfileSyncRuntimeState(sessionId, profileName, runtimeStateKey, runtimeStateLevel,
      runtimeStateMessage, {
        sender = senderKey,
        remoteDomains = CloneProfileSyncDomainList(opts.remoteDomains or {}),
        localDomains = CloneProfileSyncDomainList(opts.localDomains or {}),
        detailDiff = opts.detailDiff,
        detailConflict = opts.detailConflict,
        detailSnapshotData = opts.detailSnapshotData,
        detailPreviewSummary = opts.detailPreviewSummary,
        detailBaseSummary = opts.detailBaseSummary,
        skipIfSame = opts.skipIfSame == true,
        refreshEditor = false,
      })
    if runtimeStateChanged or opts.printWhenUnchanged == true then
      profileSyncLocalOps.printTextIfSupported(opts.printMessage)
    end
    return runtimeStateChanged
  end

  profileSyncLocalOps.buildIncomingProfileSyncValidationPrintMessage = function(reason)
    local resolvedReason = TrimText(reason)
    if resolvedReason == "inspect_failed" then
      return "Could not inspect the incoming shared profile snapshot."
    end
    if resolvedReason == "identity_mismatch" then
      return "Ignored incoming shared profile snapshot because the profile identity did not match."
    end
    return ""
  end

  profileSyncLocalOps.printIncomingProfileSyncValidationNotice = function(reason)
    local message = profileSyncLocalOps.buildIncomingProfileSyncValidationPrintMessage(reason)
    return profileSyncLocalOps.printTextIfSupported(message)
  end

  profileSyncLocalOps.buildIncomingProfileApplyRuntimeMessage = function(mode, profileName, senderKey)
    local resolvedMode = TrimText(mode)
    local resolvedProfileName = TrimText(profileName)
    local resolvedSenderKey = NormalizeSenderKey(senderKey)
    if resolvedSenderKey == "" then
      resolvedSenderKey = tostring(senderKey or "Unknown")
    end

    if resolvedMode == "accepted" then
      return "Accepted the host shared profile update."
    end
    if resolvedMode == "review_snapshot_applied" then
      return "Applied requested shared-profile update from " .. tostring(resolvedSenderKey) .. "."
    end
    if resolvedMode == "received_missing_copy" then
      return "Received a missing shared profile copy from the session."
    end
    if resolvedMode == "background_host_applied" then
      return "Applied background shared-profile data from the session host."
    end
    if resolvedMode == "host_override_applied" then
      return "Applied the selected shared-profile data from the session host."
    end
    if resolvedMode == "live_update_applied" then
      return "Applied a live shared profile update from " .. tostring(resolvedSenderKey) .. "."
    end
    if resolvedProfileName ~= "" then
      return "Applied incoming shared profile update for \"" .. tostring(resolvedProfileName) .. "\"."
    end
    return "Applied incoming shared profile update."
  end

  profileSyncLocalOps.buildIncomingProfileApplyPrintMessage = function(mode, profileName, senderKey)
    local resolvedMode = TrimText(mode)
    local resolvedProfileName = TrimText(profileName)
    local resolvedSenderKey = NormalizeSenderKey(senderKey)
    if resolvedSenderKey == "" then
      resolvedSenderKey = tostring(senderKey or "Unknown")
    end

    if resolvedMode == "accepted" then
      return "Accepted newer shared profile update for \"" .. tostring(resolvedProfileName) .. "\" from " .. tostring(resolvedSenderKey) .. "."
    end
    if resolvedMode == "review_snapshot_applied" then
      return "Applied requested shared-profile update from " .. tostring(resolvedSenderKey) .. "."
    end
    if resolvedMode == "received_missing_copy" then
      return "Received shared profile \"" .. tostring(resolvedProfileName) .. "\" from " .. tostring(resolvedSenderKey) .. "."
    end
    if resolvedMode == "background_host_applied" then
      return "Applied background shared-profile data from " .. tostring(resolvedSenderKey) .. "."
    end
    if resolvedMode == "host_override_applied" then
      return "Applied a host-authoritative shared-profile update from " .. tostring(resolvedSenderKey) .. "."
    end
    if resolvedMode == "live_update_applied" then
      return "Applied a live shared profile update from " .. tostring(resolvedSenderKey) .. "."
    end
    return ""
  end

  local function AreCharacterKeysSame(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

  local function FindSharedReplicaProfileName(preferredName, profileId, profileMaster)
    local root = deps.RootDB()
    local cleanName = TrimText(preferredName)
    local resolvedProfileId = string.lower(TrimText(profileId))
    local resolvedMaster = string.lower(NormalizeCharacterKey(profileMaster))

    for profileName, profile in pairs(root.profiles or {}) do
      if type(profile) == "table" then
        local meta = type(profile.meta) == "table" and profile.meta or {}
        local syncState = type(meta.sync) == "table" and meta.sync or {}
        local profileIdMatch = resolvedProfileId ~= ""
          and (
            string.lower(TrimText(meta.profileId)) == resolvedProfileId
            or string.lower(TrimText(syncState.sharedSourceProfileId)) == resolvedProfileId
          )
        if profileIdMatch then
          return tostring(profileName)
        end

        local isSharedReplica = string.upper(TrimText(syncState.mode)) == "SHARED"
        local sourceNameMatches = cleanName ~= ""
          and (
            string.lower(tostring(profileName)) == string.lower(cleanName)
            or string.lower(TrimText(syncState.sharedSourceProfileName)) == string.lower(cleanName)
          )
        local sourceMaster = string.lower(NormalizeCharacterKey(syncState.sharedSourceCharacter))
        local sourceMasterMatches = resolvedMaster == ""
          or sourceMaster == ""
          or AreCharacterKeysSame(sourceMaster, resolvedMaster)
        if isSharedReplica and sourceNameMatches and sourceMasterMatches then
          return tostring(profileName)
        end
      end
    end

    return ""
  end

  local function RememberSharedReplicaPlaceholder(profileName, remoteProfileName, profileId, profileMaster)
    local resolvedName = TrimText(profileName)
    local resolvedProfileId = TrimText(profileId)
    if resolvedName == "" or type(sessionRuntimeOps.getProfile) ~= "function" then
      return false
    end

    local profile = select(1, sessionRuntimeOps.getProfile(resolvedName))
    if type(profile) ~= "table" then
      return false
    end

    profile.meta = type(profile.meta) == "table" and profile.meta or {}
    profile.meta.sync = type(profile.meta.sync) == "table" and profile.meta.sync or {}
    local syncState = profile.meta.sync
    syncState.mode = "SHARED"
    if TrimText(syncState.origin) == "" then
      syncState.origin = "SESSION_INVITE"
    end
    if resolvedProfileId ~= "" then
      syncState.sharedSourceProfileId = resolvedProfileId
    end
    syncState.sharedSourceProfileName = FirstNonEmptyText(remoteProfileName, profileName)
    syncState.sharedSourceCharacter = NormalizeCharacterKey(profileMaster)
    syncState.sharedAppliedAt = tonumber(syncState.sharedAppliedAt) or (time and time() or 0)
    return true
  end

  local function ResolveLocalSharedProfileName(preferredName, profileId, profileMaster)
    local resolvedProfileId = TrimText(profileId)
    if resolvedProfileId ~= "" then
      local existingName = TrimText(deps.FindLootProfileNameById(resolvedProfileId) or "")
      if existingName ~= "" then
        return existingName
      end
    end

    local existingReplicaName = FindSharedReplicaProfileName(preferredName, profileId, profileMaster)
    if existingReplicaName ~= "" then
      return existingReplicaName
    end

    local root = deps.RootDB()
    local cleanName = TrimText(preferredName)
    if cleanName == "" then
      cleanName = "Shared Profile"
    end

    local existingProfile = root.profiles[cleanName]
    if type(existingProfile) ~= "table" then
      return cleanName
    end

    local existingProfileId = TrimText(select(1, GetLootProfileId(cleanName)) or "")
    if existingProfileId ~= "" and resolvedProfileId ~= "" and string.lower(existingProfileId) == string.lower(resolvedProfileId) then
      return cleanName
    end

    return BuildUniqueLocalProfileName(cleanName, profileMaster)
  end

  local function EnsureProfileSyncPopup()
    if type(StaticPopupDialogs) ~= "table" or StaticPopupDialogs.LIDCOUNCIL_PROFILE_SYNC_UPDATE then
      return
    end

    StaticPopupDialogs.LIDCOUNCIL_PROFILE_SYNC_UPDATE = {
      text = "Shared profile update available.",
      button1 = "Accept Update",
      button2 = "Keep Mine",
      timeout = 0,
      whileDead = 1,
      hideOnEscape = 1,
      preferredIndex = 3,
      OnAccept = function(self, data)
        local prompt = data or self.data
        if not prompt then
          return
        end
        local ok, _ = profileSyncLocalOps.tryImportIncomingProfileSnapshot(
          prompt.targetProfileName,
          prompt.snapshotData,
          prompt.profileId,
          prompt.sender,
          prompt.transferKind
        )
        if not ok then
          return
        end
        profileSyncLocalOps.finalizeIncomingProfileApplySuccess({
          targetProfileName = prompt.targetProfileName,
          sessionId = prompt.sessionId,
          profileName = prompt.profileName,
          runtimeStateKey = "accepted",
          runtimeStateLevel = "success",
          runtimeStateMessage = profileSyncLocalOps.buildIncomingProfileApplyRuntimeMessage("accepted", prompt.profileName, prompt.sender),
          sender = prompt.sender,
          remoteDomains = prompt.remoteDomains,
          currentSectionChanged = true,
          deferRefresh = true,
          printMessage = profileSyncLocalOps.buildIncomingProfileApplyPrintMessage("accepted", prompt.profileName, prompt.sender),
        })
      end,
      OnCancel = function(self, data)
        local prompt = data or self.data
        if prompt then
          profileSyncLocalOps.emitProfileSyncRuntimeNotice({
            sessionId = prompt.sessionId,
            profileName = prompt.profileName,
            runtimeStateKey = "kept_local",
            runtimeStateLevel = "warn",
            runtimeStateMessage = "Kept your local shared profile copy.",
            sender = prompt.sender,
            remoteDomains = prompt.remoteDomains,
            printMessage = "Kept your local shared profile copy for \"" .. tostring(prompt.profileName) .. "\".",
            printWhenUnchanged = true,
          })
        end
        profileSyncLocalOps.refreshSyncManagementSection({
          defer = true,
        })
      end,
    }
  end

  local function ShowProfileSyncPopup(prompt)
    EnsureProfileSyncPopup()
    if type(StaticPopup_Show) ~= "function" then
      return
    end
    local dialog = StaticPopup_Show("LIDCOUNCIL_PROFILE_SYNC_UPDATE")
    if not dialog then
      return
    end
    dialog.data = prompt
    if dialog.text and dialog.text.SetText then
      dialog.text:SetText(string.format(
        "The session host %s has newer shared profile data for \"%s\".\n\nNewer domains: %s.\n\nAccept Update replaces only your local shared copy for this shared profile lineage. Keep Mine leaves your current local copy unchanged.\n\nDo you want to apply the host update now?",
        tostring(prompt.sender or "Unknown"),
        tostring(prompt.profileName or "Unknown"),
        tostring(prompt.remoteDomainText or "none")
      ))
    end
  end

  local function BuildProfileSnapshotChunks(snapshot)
    local chunks = {}
    local text = tostring(snapshot or "")
    local chunkSize = math.max(1, tonumber(type(deps.GetProfileSnapshotChunkSize) == "function" and deps.GetProfileSnapshotChunkSize() or 120) or 120)
    local textLength = #text
    local index = 1
    while index <= textLength do
      chunks[#chunks + 1] = text:sub(index, index + chunkSize - 1)
      index = index + chunkSize
    end
    if #chunks == 0 then
      chunks[1] = ""
    end
    return chunks
  end

  profileSyncLocalOps.previewTransferSnapshot = function(snapshotData)
    local previewSummary = type(deps.PreviewLootProfileSnapshot) == "function" and deps.PreviewLootProfileSnapshot(snapshotData) or nil
    if type(previewSummary) == "table" then
      local normalized = NormalizeRevisionSummary(previewSummary, previewSummary.profileName, previewSummary.profileId)
      normalized.scopeDomains = ResolveProfileRevisionDomainList(previewSummary.scopeDomains)
      normalized.transferKind = "FULL"
      normalized.exportedAt = tonumber(previewSummary.exportedAt) or nil
      return normalized
    end

    previewSummary = type(snapshotTransferOps.previewSubdomain) == "function" and snapshotTransferOps.previewSubdomain(snapshotData) or nil
    if type(previewSummary) == "table" then
      local normalized = NormalizeRevisionSummary(previewSummary, previewSummary.profileName, previewSummary.profileId)
      normalized.scopeDomains = ResolveProfileRevisionDomainList(previewSummary.scopeDomains)
      normalized.scopeSubdomains = NormalizeProfileSyncSubdomainList(previewSummary.scopeSubdomains, previewSummary.scopeDomains)
      normalized.transferKind = "SUBDOMAINS"
      normalized.exportedAt = tonumber(previewSummary.exportedAt) or nil
      INTERNAL_API.LIDCOUNCIL_CopyProfileSyncArchivePreviewMetadata_Impl(normalized, previewSummary, TrimText)
      return normalized
    end

    previewSummary = type(snapshotTransferOps.previewPatch) == "function" and snapshotTransferOps.previewPatch(snapshotData) or nil
    if type(previewSummary) == "table" then
      local normalized = NormalizeRevisionSummary(previewSummary, previewSummary.profileName, previewSummary.profileId)
      normalized.scopeDomains = ResolveProfileRevisionDomainList(previewSummary.scopeDomains)
      normalized.scopeSubdomains = NormalizeProfileSyncSubdomainList(previewSummary.scopeSubdomains, previewSummary.scopeDomains)
      normalized.transferKind = "PATCHES"
      normalized.exportedAt = tonumber(previewSummary.exportedAt) or nil
      return normalized
    end

    previewSummary = type(snapshotTransferOps.previewRowPatch) == "function" and snapshotTransferOps.previewRowPatch(snapshotData) or nil
    if type(previewSummary) == "table" then
      local normalized = NormalizeRevisionSummary(previewSummary, previewSummary.profileName, previewSummary.profileId)
      normalized.scopeDomains = ResolveProfileRevisionDomainList(previewSummary.scopeDomains)
      normalized.scopeSubdomains = NormalizeProfileSyncSubdomainList(previewSummary.scopeSubdomains, previewSummary.scopeDomains)
      normalized.transferKind = "ROWPATCHES"
      normalized.exportedAt = tonumber(previewSummary.exportedAt) or nil
      normalized.selectedRowCount = math.max(0, tonumber(previewSummary.selectedRowCount) or 0)
      return normalized
    end

    previewSummary = type(snapshotTransferOps.previewDomain) == "function" and snapshotTransferOps.previewDomain(snapshotData) or nil
    if type(previewSummary) == "table" then
      local normalized = NormalizeRevisionSummary(previewSummary, previewSummary.profileName, previewSummary.profileId)
      normalized.scopeDomains = ResolveProfileRevisionDomainList(previewSummary.scopeDomains)
      normalized.transferKind = "DOMAINS"
      normalized.exportedAt = tonumber(previewSummary.exportedAt) or nil
      return normalized
    end
    return nil
  end

  profileSyncLocalOps.buildTransferDiff = function(profileName, snapshotData)
    local detailDiff = type(deps.BuildLootProfileSnapshotDiff) == "function" and deps.BuildLootProfileSnapshotDiff(profileName, snapshotData) or nil
    if type(detailDiff) == "table" then
      detailDiff.scopeDomains = ResolveProfileRevisionDomainList(detailDiff.scopeDomains)
      return detailDiff
    end
    detailDiff = type(deps.BuildLootProfileSubdomainSnapshotDiff) == "function" and deps.BuildLootProfileSubdomainSnapshotDiff(profileName, snapshotData) or nil
    if type(detailDiff) == "table" then
      detailDiff.scopeDomains = ResolveProfileRevisionDomainList(detailDiff.scopeDomains)
      detailDiff.scopeSubdomains = NormalizeProfileSyncSubdomainList(detailDiff.scopeSubdomains, detailDiff.scopeDomains)
      return detailDiff
    end
    detailDiff = type(deps.BuildLootProfileSubdomainPatchDiff) == "function" and deps.BuildLootProfileSubdomainPatchDiff(profileName, snapshotData) or nil
    if type(detailDiff) == "table" then
      detailDiff.scopeDomains = ResolveProfileRevisionDomainList(detailDiff.scopeDomains)
      detailDiff.scopeSubdomains = NormalizeProfileSyncSubdomainList(detailDiff.scopeSubdomains, detailDiff.scopeDomains)
      return detailDiff
    end
    detailDiff = type(deps.BuildLootProfileConflictRowPatchDiff) == "function" and deps.BuildLootProfileConflictRowPatchDiff(profileName, snapshotData) or nil
    if type(detailDiff) == "table" then
      detailDiff.scopeDomains = ResolveProfileRevisionDomainList(detailDiff.scopeDomains)
      detailDiff.scopeSubdomains = NormalizeProfileSyncSubdomainList(detailDiff.scopeSubdomains, detailDiff.scopeDomains)
      return detailDiff
    end
    detailDiff = type(deps.BuildLootProfileDomainSnapshotDiff) == "function" and deps.BuildLootProfileDomainSnapshotDiff(profileName, snapshotData) or nil
    if type(detailDiff) == "table" then
      detailDiff.scopeDomains = ResolveProfileRevisionDomainList(detailDiff.scopeDomains)
      return detailDiff
    end
    return nil
  end

  profileSyncLocalOps.importTransferSnapshot = function(targetProfileName, snapshotData, profileId, sender, transferKind, opts)
    opts = type(opts) == "table" and opts or {}
    local importOptions = {
      expectedProfileId = profileId,
      sourceCharacter = sender,
      allowAuthoritativeArchiveReplace = opts.allowAuthoritativeArchiveReplace == true,
      preserveSessionIds = CloneProfileSyncTextList(opts.preserveSessionIds),
    }
    if transferKind == "SUBDOMAINS" and type(snapshotTransferOps.importSubdomain) == "function" then
      return snapshotTransferOps.importSubdomain(targetProfileName, snapshotData, importOptions)
    end
    if transferKind == "PATCHES" and type(snapshotTransferOps.importPatch) == "function" then
      return snapshotTransferOps.importPatch(targetProfileName, snapshotData, importOptions)
    end
    if transferKind == "ROWPATCHES" and type(snapshotTransferOps.importRowPatch) == "function" then
      return snapshotTransferOps.importRowPatch(targetProfileName, snapshotData, importOptions)
    end
    if transferKind == "DOMAINS" and type(snapshotTransferOps.importDomain) == "function" then
      return snapshotTransferOps.importDomain(targetProfileName, snapshotData, importOptions)
    end
    return deps.ImportLootProfileSnapshot(targetProfileName, snapshotData, importOptions)
  end

  profileSyncLocalOps.resolveIncomingProfileSyncTargetProfileName = function(syncState, activeProfileName)
    syncState = type(syncState) == "table" and syncState or {}
    local targetProfileName = TrimText(syncState.targetProfileName)
    if targetProfileName == "" then
      targetProfileName = TrimText(activeProfileName)
    end
    if targetProfileName == "" then
      targetProfileName = ResolveLocalSharedProfileName(syncState.profileName, syncState.profileId, "")
    end
    return TrimText(targetProfileName)
  end

  profileSyncLocalOps.buildIncomingProfileSnapshotReviewState = function(syncState, sender, targetProfileName, snapshotData, previewSummary, comparedDomains)
    local reviewState = {
      remoteNewerDomains = {},
      localNewerDomains = {},
      detailDiff = nil,
      detailConflict = nil,
      localRevisionSummary = nil,
    }
    syncState = type(syncState) == "table" and syncState or {}
    if not syncState.reviewSync and not syncState.previewSync then
      return reviewState
    end

    reviewState.localRevisionSummary = NormalizeRevisionSummary(syncState.localRevisionSummary, targetProfileName, syncState.profileId)
    reviewState.remoteNewerDomains, reviewState.localNewerDomains = profileSyncLocalOps.compareProfileRevisionSummaries(
      reviewState.localRevisionSummary,
      previewSummary,
      comparedDomains
    )
    reviewState.detailDiff = profileSyncLocalOps.buildTransferDiff(targetProfileName, snapshotData)
    if type(reviewState.detailDiff) == "table" then
      reviewState.detailDiff.memberKey = NormalizeSenderKey(sender)
      reviewState.detailDiff.profileName = targetProfileName
      reviewState.detailDiff.remoteDomains = CloneProfileSyncDomainList(reviewState.remoteNewerDomains)
      reviewState.detailDiff.localDomains = CloneProfileSyncDomainList(reviewState.localNewerDomains)
      reviewState.detailDiff.comparison = select(1, profileSyncLocalOps.resolveProfileSyncComparison(reviewState.localRevisionSummary, previewSummary))
    end
    if syncState.previewSync and type(deps.BuildLootProfileTransferConflictPreview) == "function" then
      reviewState.detailConflict = deps.BuildLootProfileTransferConflictPreview(targetProfileName, snapshotData)
      if type(reviewState.detailConflict) == "table" then
        reviewState.detailConflict.memberKey = NormalizeSenderKey(sender)
        reviewState.detailConflict.profileName = targetProfileName
        reviewState.detailConflict.remoteDomains = CloneProfileSyncDomainList(reviewState.remoteNewerDomains)
        reviewState.detailConflict.localDomains = CloneProfileSyncDomainList(reviewState.localNewerDomains)
        reviewState.detailConflict.comparison = select(1, profileSyncLocalOps.resolveProfileSyncComparison(reviewState.localRevisionSummary, previewSummary))
        reviewState.detailConflict.previewProfileId = TrimText(previewSummary.profileId)
      end
    end
    return reviewState
  end

  profileSyncLocalOps.publishIncomingProfileSnapshotPreview = function(syncState, sender, snapshotData, previewSummary, reviewState)
    syncState = type(syncState) == "table" and syncState or {}
    reviewState = type(reviewState) == "table" and reviewState or {}
    local previewNoticeText = profileSyncLocalOps.buildPreviewSnapshotReceivedNoticeText(sender)
    local runtimeStateChanged = profileSyncLocalOps.emitProfileSyncRuntimeNotice({
      sessionId = syncState.sessionId,
      profileName = syncState.profileName,
      runtimeStateKey = "preview_snapshot_received",
      runtimeStateLevel = "success",
      runtimeStateMessage = previewNoticeText,
      sender = sender,
      remoteDomains = reviewState.remoteNewerDomains,
      localDomains = reviewState.localNewerDomains,
      detailDiff = reviewState.detailDiff,
      detailConflict = reviewState.detailConflict,
      detailSnapshotData = snapshotData,
      detailPreviewSummary = previewSummary,
      detailBaseSummary = reviewState.localRevisionSummary,
      skipIfSame = true,
      printMessage = previewNoticeText,
    })
    if runtimeStateChanged then
      profileSyncLocalOps.refreshSyncManagementSection({
        defer = true,
      })
    end
    return runtimeStateChanged
  end

  profileSyncLocalOps.updateSessionStateAfterIncomingProfileApply = function(activeSession, syncState, targetProfileName, sender, previewSummary)
    if type(activeSession) ~= "table" or activeSession.id ~= TrimText(type(syncState) == "table" and syncState.sessionId or "") then
      return
    end

    local profile = type(sessionRuntimeOps.getProfile) == "function" and select(1, sessionRuntimeOps.getProfile(targetProfileName)) or nil
    if type(profile) == "table" and type(deps.NormalizeLootRollOptions) == "function" then
      activeSession.rollOptions = deps.NormalizeLootRollOptions(profile.settings and profile.settings.rollOptions)
    end
    if type(activeSession.members) == "table" then
      for memberKey, member in pairs(activeSession.members) do
        if type(member) == "table" then
          if type(deps.GetLootProfileMaster) == "function" then
            member.profileMaster = deps.GetLootProfileMaster(targetProfileName)
          end
          if type(deps.GetLootProfileRole) == "function" then
            member.role = deps.GetLootProfileRole(targetProfileName, memberKey)
          end
        end
      end
    end

    local senderKey = NormalizeSenderKey(sender)
    local senderMember = type(activeSession.members) == "table" and activeSession.members[senderKey] or nil
    if type(senderMember) == "table" then
      local liveLootManifest = type(GetLootProfileSubchecksumManifest) == "function"
        and GetLootProfileSubchecksumManifest(targetProfileName, { "loot", "session" })
        or nil
      local archiveScopeChecksums = profileSyncLocalOps.buildProfileSyncArchiveScopeChecksums(liveLootManifest, activeSession)
      senderMember.sharedProfileId = TrimText(previewSummary.profileId)
      senderMember.settingsRevision = tonumber(previewSummary.settings) or 0
      senderMember.permissionsRevision = tonumber(previewSummary.permissions) or 0
      senderMember.operationalRevision = tonumber(previewSummary.operational) or 0
      senderMember.lootRevision = tonumber(previewSummary.loot) or tonumber(previewSummary.operational) or 0
      senderMember.sessionRevision = tonumber(previewSummary.session) or tonumber(previewSummary.operational) or 0
      senderMember.settingsChecksum = TrimText(previewSummary.settingsChecksum)
      senderMember.permissionsChecksum = TrimText(previewSummary.permissionsChecksum)
      senderMember.operationalChecksum = TrimText(previewSummary.operationalChecksum)
      senderMember.lootChecksum = TrimText(previewSummary.lootChecksum)
      senderMember.sessionChecksum = TrimText(previewSummary.sessionChecksum)
      senderMember.liveLootChecksum = profileSyncLocalOps.buildLiveLootChecksum(liveLootManifest, activeSession)
      senderMember.archiveLootChecksum = profileSyncLocalOps.buildProfileSyncArchiveLootChecksum(liveLootManifest, activeSession)
      senderMember.lootListArchiveChecksum = TrimText(archiveScopeChecksums.lootList)
      senderMember.itemHistoryArchiveChecksum = TrimText(archiveScopeChecksums.itemHistory)
      senderMember.sessionHistoryArchiveChecksum = TrimText(archiveScopeChecksums.sessionHistory)
      senderMember.funAwardsArchiveChecksum = TrimText(archiveScopeChecksums.funAwards)
      senderMember.profileUpdatedAt = tonumber(previewSummary.updatedAt) or tonumber(time and time() or 0) or 0
      senderMember.lastSyncAt = tonumber(time and time() or 0) or 0
    end
    activeSession.sharedProfileReady = true
    activeSession.__sharedProfilePendingNoticeShown = nil
  end

  profileSyncLocalOps.scheduleDelayedLocalProfileStateSend = function(sessionId, profileName, targetProfileName, options)
    local delayedSessionId = TrimText(sessionId)
    local delayedProfileName = TrimText(profileName)
    local delayedTargetProfileName = TrimText(targetProfileName)
    local forceSend = type(options) == "table" and options.force == true
    if delayedSessionId == "" or delayedProfileName == "" or delayedTargetProfileName == "" then
      return
    end

    local stateKey = table.concat({
      string.lower(delayedSessionId),
      string.lower(delayedProfileName),
      string.lower(delayedTargetProfileName),
    }, "|")
    local token = math.max(0, tonumber(profileSyncCaches.delayedLocalProfileStateSendTokens[stateKey]) or 0) + 1
    profileSyncCaches.delayedLocalProfileStateSendTokens[stateKey] = token

    if type(Compat) == "table" and type(Compat.After) == "function" then
      Compat.After(0.35, function()
        if profileSyncCaches.delayedLocalProfileStateSendTokens[stateKey] ~= token then
          return
        end
        profileSyncCaches.delayedLocalProfileStateSendTokens[stateKey] = nil
        profileSyncLocalOps.sendLocalProfileStateToHost(delayedSessionId, delayedProfileName, delayedTargetProfileName, {
          force = forceSend,
        })
      end)
    else
      profileSyncCaches.delayedLocalProfileStateSendTokens[stateKey] = nil
      profileSyncLocalOps.sendLocalProfileStateToHost(delayedSessionId, delayedProfileName, delayedTargetProfileName, {
        force = forceSend,
      })
    end
  end

  profileSyncLocalOps.applyIncomingProfileSnapshot = function(options)
    options = type(options) == "table" and options or {}
    local syncState = type(options.syncState) == "table" and options.syncState or {}
    local activeSession = type(options.activeSession) == "table" and options.activeSession or nil
    local targetProfileName = TrimText(options.targetProfileName)
    local snapshotData = tostring(options.snapshotData or "")
    local previewSummary = type(options.previewSummary) == "table" and options.previewSummary or {}
    local sender = options.sender
    local mode = TrimText(options.mode)
    local successMessage = TrimText(options.successMessage)
    local printMessage = TrimText(options.printMessage)
    local remoteNewerDomains = CloneProfileSyncDomainList(options.remoteNewerDomains or {})
    local localNewerDomains = CloneProfileSyncDomainList(options.localNewerDomains or {})
    local reviewSyncDetailDiff = options.reviewSyncDetailDiff
    local deferAcknowledgement = options.deferAcknowledgement == true
    local resolvedSuccessMessage = successMessage ~= ""
      and successMessage
      or profileSyncLocalOps.buildIncomingProfileApplyRuntimeMessage(mode, targetProfileName, sender)
    local senderKey = NormalizeSenderKey(sender)
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    local hostSideApply = type(activeSession) == "table" and NormalizeCharacterKey(activeSession.host or "") == selfKey
    local senderIsActiveHost = type(activeSession) == "table"
      and NormalizeCharacterKey(activeSession.host or "") == senderKey
    local previousCurrentSectionState = type(activeSession) == "table" and activeSession.id == syncState.sessionId
      and BuildCurrentSessionDisplaySignature(activeSession, targetProfileName)
      or ""

    if hostSideApply then
      profileSyncLocalOps.pushUndoSnapshotIfSupported(
        targetProfileName,
        mode,
        senderKey,
        TrimText(syncState.profileId),
        profileSyncLocalOps.buildUndoSnapshotSummary("applying incoming shared profile data", senderKey)
      )
    end

    local ok, result = profileSyncLocalOps.tryImportIncomingProfileSnapshot(
      targetProfileName,
      snapshotData,
      syncState.profileId,
      senderKey,
      previewSummary.transferKind,
      {
        printFailure = false,
        allowAuthoritativeArchiveReplace = senderIsActiveHost
          and string.upper(TrimText(syncState.mode)) == "BACKGROUND"
          and TrimText(previewSummary.authoritativeArchiveScope) ~= "",
        preserveSessionIds = type(activeSession) == "table" and { TrimText(activeSession.id) } or {},
      }
    )
    if not ok then
      profileSyncLocalOps.finalizeIncomingProfileApplyFailure(result, {
        activeSession = activeSession,
        sessionId = syncState.sessionId,
        profileName = syncState.profileName,
        targetProfileName = targetProfileName,
        sender = senderKey,
        runtimeStateKey = mode .. "_failed",
        runtimeStateLevel = "warn",
        runtimeStateMessage = "The incoming shared profile update could not be applied.",
        previousCurrentSectionState = previousCurrentSectionState,
        skipIfSame = true,
        deferRefresh = true,
      })
      return false
    end

    profileSyncLocalOps.updateSessionStateAfterIncomingProfileApply(
      activeSession,
      syncState,
      targetProfileName,
      senderKey,
      previewSummary
    )
    if senderKey ~= "" then
      -- The imported snapshot changes this member's revision baseline; old precise data is no longer authoritative.
      local appliedScopeDomains = MergeProfileRevisionDomains(syncState.scopeDomains, previewSummary.scopeDomains)
      InvalidateMemberPreciseSyncState(syncState.sessionId, senderKey, {
        domains = appliedScopeDomains,
        subdomains = MergeRequestedProfileSyncSubdomains(
          appliedScopeDomains,
          syncState.scopeSubdomains,
          previewSummary.scopeSubdomains
        ),
        revisionSummary = previewSummary,
      })
    end
    if hostSideApply then
      profileSyncLocalOps.refreshHostSessionMemberState(targetProfileName, syncState.sessionId, {
        suppressCheckpoint = true,
      })
    end
    local currentSectionStateChanged = previousCurrentSectionState ~= BuildCurrentSessionDisplaySignature(activeSession, targetProfileName)

    profileSyncLocalOps.finalizeIncomingProfileApplySuccess({
      targetProfileName = targetProfileName,
      sessionId = syncState.sessionId,
      profileName = syncState.profileName,
      runtimeStateKey = mode,
      runtimeStateLevel = "success",
      runtimeStateMessage = resolvedSuccessMessage,
      sender = senderKey,
      remoteDomains = remoteNewerDomains,
      localDomains = localNewerDomains,
      detailDiff = reviewSyncDetailDiff,
      printMessage = printMessage,
      skipIfSame = true,
      currentSectionChanged = currentSectionStateChanged,
      refreshSections = false,
    })
    if hostSideApply and string.find(string.lower(tostring(mode or "")), "applied", 1, true) then
      profileSyncLocalOps.recordRepairHistoryIfSupported({
        profileName = targetProfileName,
        sessionId = TrimText(syncState.sessionId),
        memberKey = senderKey,
        kind = mode,
        summary = resolvedSuccessMessage,
        createdAt = GetNow(),
        skipIfRecentSame = true,
        dedupeWindowSeconds = 10,
      })
    end

    profileSyncLocalOps.sendLocalProfileStateToHost(syncState.sessionId, syncState.profileName, targetProfileName)
    -- The immediate proof can precede checksum-cache invalidation on an existing replica.
    profileSyncLocalOps.scheduleDelayedLocalProfileStateSend(syncState.sessionId, syncState.profileName, targetProfileName, {
      force = true,
    })
    generationOps.RememberTransferGenerationState(
      syncState.sessionId,
      senderKey,
      TrimText(syncState.lane) ~= "" and syncState.lane or generationOps.NormalizeProfileTransferLane("", syncState.scopeSubdomains, syncState.transferKind),
      syncState.generation,
      GetNow(),
      true
    )
    if type(profileSyncLocalOps.rememberAppliedCombatSnapshotGeneration) == "function" then
      profileSyncLocalOps.rememberAppliedCombatSnapshotGeneration(syncState, senderKey)
    end
    if not deferAcknowledgement then
      SendProfileSyncAck(syncState, targetProfileName, previewSummary, "APPLIED")
    end
    profileSyncLocalOps.refreshChoicePopup({
      reason = "sync",
    })
    profileSyncLocalOps.refreshCurrentAndSyncSections(currentSectionStateChanged, {
      defer = true,
    })
    return true
  end

  profileSyncLocalOps.clonePreparedSnapshotCacheValue = function(value)
    if type(value) ~= "table" then
      return value
    end
    local clone = {}
    for key, nestedValue in pairs(value) do
      clone[key] = profileSyncLocalOps.clonePreparedSnapshotCacheValue(nestedValue)
    end
    return clone
  end

  profileSyncLocalOps.prunePreparedSnapshotCache = function(now, profileName, revisionSignature)
    local currentTime = math.max(0, tonumber(now) or GetNow())
    local resolvedProfileName = string.lower(TrimText(profileName))
    local resolvedRevisionSignature = TrimText(revisionSignature)
    local retained = {}
    for cacheKey, entry in pairs(type(profileSyncCaches.preparedSnapshots) == "table"
      and profileSyncCaches.preparedSnapshots or {}) do
      local expired = type(entry) ~= "table"
        or math.max(0, tonumber(entry.expiresAt) or 0) <= currentTime
      local staleRevision = not expired
        and resolvedProfileName ~= ""
        and string.lower(TrimText(entry.profileName)) == resolvedProfileName
        and resolvedRevisionSignature ~= ""
        and TrimText(entry.revisionSignature) ~= resolvedRevisionSignature
      if expired or staleRevision then
        profileSyncCaches.preparedSnapshots[cacheKey] = nil
      else
        retained[#retained + 1] = {
          key = cacheKey,
          lastUsedAt = math.max(0, tonumber(entry.lastUsedAt or entry.createdAt) or 0),
        }
      end
    end
    table.sort(retained, function(left, right)
      if left.lastUsedAt ~= right.lastUsedAt then
        return left.lastUsedAt < right.lastUsedAt
      end
      return left.key < right.key
    end)
    while #retained > math.max(1, tonumber(profileSyncConfig.maxPreparedSnapshots) or 8) do
      local oldest = table.remove(retained, 1)
      profileSyncCaches.preparedSnapshots[oldest.key] = nil
    end
    return #retained
  end

  profileSyncLocalOps.buildPreparedSnapshotCacheKey = function(profileName, opts, domains, subdomains, authoritativeArchiveScope)
    opts = type(opts) == "table" and opts or {}
    if type(opts.patchManifest) == "table"
      or type(opts.rowSelectionsBySubdomain) == "table"
      or type(opts.rowMapsBySubdomain) == "table"
      or type(opts.prebuiltRowsBySubdomain) == "table"
      or opts.disablePreparedSnapshotCache == true
    then
      return "", ""
    end
    local resolvedProfileName = TrimText(profileName)
    local profileId = TrimText(select(1, GetLootProfileId(resolvedProfileName)) or "")
    local revisionSummary = NormalizeRevisionSummary(
      GetLootProfileRevisionSummary(resolvedProfileName),
      resolvedProfileName,
      profileId
    )
    local revisionSignature = BuildStableValueSignature(revisionSummary)
    if resolvedProfileName == "" or revisionSignature == "" then
      return "", ""
    end
    local chunkSize = math.max(1, tonumber(type(deps.GetProfileSnapshotChunkSize) == "function"
      and deps.GetProfileSnapshotChunkSize() or 120) or 120)
    return table.concat({
      string.lower(resolvedProfileName),
      string.lower(profileId),
      revisionSignature,
      type(opts.domains) ~= "nil" and "domains" or "full",
      EncodeProfileRevisionDomains(type(domains) == "table" and domains or {}),
      table.concat(CloneProfileSyncSubdomainList(type(subdomains) == "table" and subdomains or {}), "\30"),
      string.upper(TrimText(authoritativeArchiveScope)),
      string.lower(TrimText(opts.sessionId)),
      tostring(math.floor(chunkSize + 0.5)),
    }, "\31"), revisionSignature
  end

  profileSyncLocalOps.getPreparedSnapshotCacheValue = function(cacheKey, revisionSignature)
    local resolvedCacheKey = TrimText(cacheKey)
    if resolvedCacheKey == "" then
      return nil
    end
    local now = GetNow()
    local entry = type(profileSyncCaches.preparedSnapshots) == "table"
      and profileSyncCaches.preparedSnapshots[resolvedCacheKey]
      or nil
    if type(entry) ~= "table"
      or TrimText(entry.revisionSignature) ~= TrimText(revisionSignature)
      or math.max(0, tonumber(entry.expiresAt) or 0) <= now
      or type(entry.preparedSnapshot) ~= "table"
    then
      if type(profileSyncCaches.preparedSnapshots) == "table" then
        profileSyncCaches.preparedSnapshots[resolvedCacheKey] = nil
      end
      return nil
    end
    entry.lastUsedAt = now
    profileSyncSessionState.preparedSnapshotCacheHits = math.max(0,
      tonumber(profileSyncSessionState.preparedSnapshotCacheHits) or 0) + 1
    return profileSyncLocalOps.clonePreparedSnapshotCacheValue(entry.preparedSnapshot)
  end

  profileSyncLocalOps.rememberPreparedSnapshotCacheValue = function(cacheKey, revisionSignature, profileName, preparedSnapshot)
    local resolvedCacheKey = TrimText(cacheKey)
    if resolvedCacheKey == "" or TrimText(revisionSignature) == "" or type(preparedSnapshot) ~= "table" then
      return false
    end
    local now = GetNow()
    profileSyncCaches.preparedSnapshots[resolvedCacheKey] = {
      profileName = TrimText(profileName),
      revisionSignature = TrimText(revisionSignature),
      preparedSnapshot = profileSyncLocalOps.clonePreparedSnapshotCacheValue(preparedSnapshot),
      createdAt = now,
      lastUsedAt = now,
      expiresAt = now + math.max(1, tonumber(profileSyncConfig.preparedSnapshotRetentionSeconds) or 20),
    }
    profileSyncLocalOps.prunePreparedSnapshotCache(now, profileName, revisionSignature)
    return true
  end

  profileSyncLocalOps.prepareProfileSnapshotTransfer = function(profileName, opts)
    local performanceTiming = {
      total = profileSyncLocalOps.beginPerformanceSample("snapshot_prepare_total", 1),
      export = profileSyncLocalOps.beginPerformanceSample("snapshot_export", 1),
    }
    opts = type(opts) == "table" and opts or {}
    local domains = ResolveProfileRevisionDomainList(opts.domains)
    local requestedDomains = CloneProfileSyncDomainList(domains)
    local subdomains = NormalizeRequestedProfileSyncSubdomains(opts.subdomains, domains)
    local requestedSubdomains = CloneProfileSyncSubdomainList(subdomains)
    local domainCsv = TrimText(type(opts.domains) ~= "nil" and EncodeProfileRevisionDomains(domains) or "")
    local mode = TrimText(opts.mode)
    local reason = TrimText(opts.reason)
    local authoritativeArchiveScope = string.upper(TrimText(opts.authoritativeArchiveScope))
    if authoritativeArchiveScope ~= "LOOT_LIST"
      and authoritativeArchiveScope ~= "SESSION_HISTORY"
      and authoritativeArchiveScope ~= "FUN_AWARDS"
    then
      authoritativeArchiveScope = ""
    end
    local preparedSnapshotCacheKey, preparedSnapshotRevisionSignature =
      profileSyncLocalOps.buildPreparedSnapshotCacheKey(profileName, opts, domains, subdomains, authoritativeArchiveScope)
    profileSyncLocalOps.prunePreparedSnapshotCache(GetNow(), profileName, preparedSnapshotRevisionSignature)
    local cachedPreparedSnapshot = profileSyncLocalOps.getPreparedSnapshotCacheValue(
      preparedSnapshotCacheKey,
      preparedSnapshotRevisionSignature
    )
    if type(cachedPreparedSnapshot) == "table" then
      profileSyncLocalOps.recordPerformance("snapshot_export", performanceTiming.export, {
        bytes = 0,
        context = "cache_hit_" .. TrimText(cachedPreparedSnapshot.transferKind),
      })
      profileSyncLocalOps.recordPerformance("snapshot_prepare_total", performanceTiming.total, {
        chunkCount = #(type(cachedPreparedSnapshot.chunks) == "table" and cachedPreparedSnapshot.chunks or {}),
        context = "cache_hit_" .. TrimText(cachedPreparedSnapshot.transferKind),
      })
      return cachedPreparedSnapshot
    elseif preparedSnapshotCacheKey ~= "" then
      profileSyncSessionState.preparedSnapshotCacheMisses = math.max(0,
        tonumber(profileSyncSessionState.preparedSnapshotCacheMisses) or 0) + 1
    end
    local snapshot
    local transferKind = "FULL"
    local rowPatchRequested = authoritativeArchiveScope == "" and #requestedSubdomains > 0
      and (type(opts.rowSelectionsBySubdomain) == "table" or type(opts.prebuiltRowsBySubdomain) == "table")
    local patchRequested = authoritativeArchiveScope == "" and #requestedSubdomains > 0 and type(opts.patchManifest) == "table"
    if authoritativeArchiveScope == "" and #subdomains > 0
      and type(opts.rowSelectionsBySubdomain) == "table"
      and type(snapshotTransferOps.exportRowPatch) == "function" then
      snapshot = snapshotTransferOps.exportRowPatch(
        profileName,
        opts.rowSelectionsBySubdomain,
        opts.rowMapsBySubdomain,
        opts.prebuiltRowsBySubdomain
      )
      if type(snapshot) == "string" and snapshot ~= "" then
        transferKind = "ROWPATCHES"
        domains = type(ResolveLootProfileDomainsForSubdomains) == "function"
          and ResolveLootProfileDomainsForSubdomains(subdomains)
          or ResolveProfileRevisionDomainList(domains)
      end
    end
    if authoritativeArchiveScope == "" and (type(snapshot) ~= "string" or snapshot == "") and #subdomains > 0
      and type(opts.prebuiltRowsBySubdomain) == "table"
      and type(snapshotTransferOps.exportRowPatch) == "function"
    then
      snapshot = snapshotTransferOps.exportRowPatch(
        profileName,
        opts.rowSelectionsBySubdomain or {},
        opts.rowMapsBySubdomain or {},
        opts.prebuiltRowsBySubdomain
      )
      if type(snapshot) == "string" and snapshot ~= "" then
        transferKind = "ROWPATCHES"
        domains = type(ResolveLootProfileDomainsForSubdomains) == "function"
          and ResolveLootProfileDomainsForSubdomains(subdomains)
          or ResolveProfileRevisionDomainList(domains)
      end
    end
    if authoritativeArchiveScope == "" and (type(snapshot) ~= "string" or snapshot == "") and #subdomains > 0 and type(opts.patchManifest) == "table" and type(snapshotTransferOps.exportPatch) == "function" then
      snapshot = snapshotTransferOps.exportPatch(profileName, subdomains, opts.patchManifest)
      if type(snapshot) == "string" and snapshot ~= "" then
        transferKind = "PATCHES"
        domains = type(ResolveLootProfileDomainsForSubdomains) == "function"
          and ResolveLootProfileDomainsForSubdomains(subdomains)
          or ResolveProfileRevisionDomainList(domains)
      end
    end
    if (type(snapshot) ~= "string" or snapshot == "")
      and (#subdomains > 0 or authoritativeArchiveScope ~= "")
      and type(snapshotTransferOps.exportSubdomain) == "function"
    then
      snapshot = snapshotTransferOps.exportSubdomain(profileName, subdomains, {
        authoritativeArchiveScope = authoritativeArchiveScope,
        preserveSessionIds = TrimText(opts.sessionId) ~= "" and { TrimText(opts.sessionId) } or {},
      })
      transferKind = "SUBDOMAINS"
      local exportedPreview = type(snapshot) == "string" and snapshot ~= ""
        and type(snapshotTransferOps.previewSubdomain) == "function"
        and snapshotTransferOps.previewSubdomain(snapshot)
        or nil
      if type(exportedPreview) == "table" then
        subdomains = CloneProfileSyncSubdomainList(exportedPreview.scopeSubdomains)
        domains = CloneProfileSyncDomainList(exportedPreview.scopeDomains)
      else
        domains = type(ResolveLootProfileDomainsForSubdomains) == "function"
          and ResolveLootProfileDomainsForSubdomains(subdomains)
          or ResolveProfileRevisionDomainList(domains)
      end
    elseif domainCsv ~= "" and type(snapshotTransferOps.exportDomain) == "function" then
      snapshot = snapshotTransferOps.exportDomain(profileName, domains)
      transferKind = "DOMAINS"
    else
      snapshot = deps.ExportLootProfileSnapshot(profileName)
    end
    profileSyncLocalOps.recordPerformance("snapshot_export", performanceTiming.export, {
      bytes = type(snapshot) == "string" and #snapshot or 0,
      context = transferKind,
    })

    local fallbackReasons = {}
    if rowPatchRequested and transferKind ~= "ROWPATCHES" then
      AppendDecisionReason(fallbackReasons, "row_patch_unavailable")
    end
    if patchRequested and transferKind ~= "PATCHES" and transferKind ~= "ROWPATCHES" then
      AppendDecisionReason(fallbackReasons, "patch_manifest_snapshot_fallback")
    end
    if #requestedSubdomains > 0
      and transferKind ~= "ROWPATCHES"
      and transferKind ~= "PATCHES"
      and transferKind ~= "SUBDOMAINS" then
      AppendDecisionReason(fallbackReasons, "subdomain_scope_broadened")
    elseif #requestedSubdomains == 0 and domainCsv ~= "" and transferKind == "FULL" then
      AppendDecisionReason(fallbackReasons, "domain_scope_broadened")
    end
    local transferFallback = ClassifyPreparedTransferFallback(
      requestedDomains,
      requestedSubdomains,
      transferKind,
      fallbackReasons
    )

    if type(snapshot) ~= "string" or snapshot == "" then
      if type(RecordProfileSyncDecision) == "function" then
        RecordProfileSyncDecision("prepare_snapshot_transfer", {
          action = "failed",
          sessionId = TrimText(opts.sessionId),
          profileName = TrimText(profileName),
          mode = mode,
          reason = reason,
          transferKind = transferKind,
          transferKinds = { transferKind },
          requestedDomains = requestedDomains,
          requestedSubdomains = requestedSubdomains,
          domains = CloneProfileSyncDomainList(domains),
          subdomains = CloneProfileSyncSubdomainList(subdomains),
          requestedScope = transferFallback.requestedScope,
          scopeEscalated = transferFallback.scopeEscalated,
          fullSnapshotFallback = transferFallback.fullSnapshotFallback,
          fallbackEscalation = transferFallback.fallbackEscalation,
          fallbackReason = fallbackReasons[1],
          fallbackReasons = fallbackReasons,
          authoritativeArchiveScope = authoritativeArchiveScope,
          error = "Profile snapshot export failed.",
        })
      end
      profileSyncLocalOps.recordPerformance("snapshot_prepare_total", performanceTiming.total, {
        context = "failed_" .. transferKind,
      })
      return nil, "Profile snapshot export failed."
    end
    local preparedSnapshot = {
      profileName = TrimText(profileName),
      profileId = TrimText(select(1, GetLootProfileId(profileName)) or ""),
      domains = transferKind == "FULL" and CloneProfileSyncDomainList(PROFILE_REVISION_DOMAINS) or CloneProfileSyncDomainList(domains),
      subdomains = (transferKind == "SUBDOMAINS" or transferKind == "PATCHES" or transferKind == "ROWPATCHES") and CloneProfileSyncSubdomainList(subdomains) or {},
      transferKind = transferKind,
      requestedDomains = CloneProfileSyncDomainList(requestedDomains),
      requestedSubdomains = CloneProfileSyncSubdomainList(requestedSubdomains),
      requestedScope = transferFallback.requestedScope,
      fallbackReasons = CloneProfileSyncTextList(fallbackReasons),
      fallbackEscalation = transferFallback.fallbackEscalation,
      scopeEscalated = transferFallback.scopeEscalated,
      fullSnapshotFallback = transferFallback.fullSnapshotFallback,
      authoritativeArchiveScope = authoritativeArchiveScope,
    }
    performanceTiming.chunks = profileSyncLocalOps.beginPerformanceSample("snapshot_chunks", 1)
    preparedSnapshot.chunks = BuildProfileSnapshotChunks(snapshot)
    profileSyncLocalOps.recordPerformance("snapshot_chunks", performanceTiming.chunks, {
      bytes = #snapshot,
      chunkCount = #preparedSnapshot.chunks,
      context = transferKind,
    })
    performanceTiming.manifest = profileSyncLocalOps.beginPerformanceSample("snapshot_manifest", 1)
    preparedSnapshot.patchManifestSummary = profileSyncLocalOps.buildPreparedTransferPatchManifestSummary(profileName, subdomains)
    profileSyncLocalOps.recordPerformance("snapshot_manifest", performanceTiming.manifest, {
      chunkCount = #preparedSnapshot.chunks,
      context = transferKind,
    })
    profileSyncLocalOps.rememberPreparedSnapshotCacheValue(
      preparedSnapshotCacheKey,
      preparedSnapshotRevisionSignature,
      profileName,
      preparedSnapshot
    )
    if type(RecordProfileSyncDecision) == "function" then
      RecordProfileSyncDecision("prepare_snapshot_transfer", {
        action = "prepared",
        sessionId = TrimText(opts.sessionId),
        profileName = TrimText(profileName),
        mode = mode,
        reason = reason,
        transferKind = transferKind,
        transferKinds = { transferKind },
        chunkCount = #preparedSnapshot.chunks,
        requestedDomains = requestedDomains,
        requestedSubdomains = requestedSubdomains,
        domains = preparedSnapshot.domains,
        subdomains = preparedSnapshot.subdomains,
        requestedScope = transferFallback.requestedScope,
        scopeEscalated = transferFallback.scopeEscalated,
        fullSnapshotFallback = transferFallback.fullSnapshotFallback,
        fallbackEscalation = transferFallback.fallbackEscalation,
        fallbackReason = fallbackReasons[1],
        fallbackReasons = fallbackReasons,
        authoritativeArchiveScope = authoritativeArchiveScope,
      })
    end
    profileSyncLocalOps.recordPerformance("snapshot_prepare_total", performanceTiming.total, {
      bytes = #snapshot,
      chunkCount = #preparedSnapshot.chunks,
      context = transferKind,
    })
    return preparedSnapshot
  end

  profileSyncLocalOps.buildPreparedSnapshotSendContext = function(preparedSnapshot, sessionId, target, opts)
    opts = type(opts) == "table" and opts or {}
    local transferKind = TrimText(type(preparedSnapshot) == "table" and preparedSnapshot.transferKind or "")
    local subdomains = (transferKind == "SUBDOMAINS" or transferKind == "PATCHES" or transferKind == "ROWPATCHES")
      and table.concat(type(preparedSnapshot) == "table" and preparedSnapshot.subdomains or {}, ",")
      or ""
    if #subdomains > profileSyncConfig.subcheckChunkLimit then
      subdomains = ""
    end
    return {
      sessionId = TrimText(sessionId),
      target = NormalizeCharacterKey(target),
      mode = TrimText(opts.mode),
      reason = TrimText(opts.reason),
      hostAuthoritativeOverride = opts.forceAuthoritativeOverride == true,
      profileName = TrimText(type(preparedSnapshot) == "table" and preparedSnapshot.profileName or ""),
      profileId = TrimText(type(preparedSnapshot) == "table" and preparedSnapshot.profileId or ""),
      transferKind = transferKind,
      domains = transferKind ~= "FULL" and EncodeProfileRevisionDomains(type(preparedSnapshot) == "table" and preparedSnapshot.domains or {}) or "",
      subdomains = subdomains,
      chunks = type(preparedSnapshot) == "table" and type(preparedSnapshot.chunks) == "table" and preparedSnapshot.chunks or {},
    }
  end

  profileSyncLocalOps.buildPreparedSnapshotAnnotationPayload = function(preparedSnapshot, sendContext)
    sendContext = type(sendContext) == "table" and sendContext or {}
    return {
      sessionId = TrimText(sendContext.sessionId),
      profileName = TrimText(sendContext.profileName),
      profileId = TrimText(sendContext.profileId),
      mode = TrimText(sendContext.mode),
      reason = TrimText(sendContext.reason),
      hostAuthoritativeOverride = sendContext.hostAuthoritativeOverride == true,
      domains = TrimText(sendContext.domains),
      transferKind = TrimText(sendContext.transferKind),
      subdomains = TrimText(sendContext.subdomains),
      scopeDomains = CloneProfileSyncDomainList(type(preparedSnapshot) == "table" and preparedSnapshot.domains or {}),
      scopeSubdomains = CloneProfileSyncSubdomainList(type(preparedSnapshot) == "table" and preparedSnapshot.subdomains or {}),
      requestedScope = TrimText(type(preparedSnapshot) == "table" and preparedSnapshot.requestedScope or ""),
      requestedDomains = CloneProfileSyncDomainList(type(preparedSnapshot) == "table" and preparedSnapshot.requestedDomains or {}),
      requestedSubdomains = CloneProfileSyncSubdomainList(type(preparedSnapshot) == "table" and preparedSnapshot.requestedSubdomains or {}),
      scopeEscalated = type(preparedSnapshot) == "table" and preparedSnapshot.scopeEscalated == true or false,
      fullSnapshotFallback = type(preparedSnapshot) == "table" and preparedSnapshot.fullSnapshotFallback == true or false,
      fallbackEscalation = TrimText(type(preparedSnapshot) == "table" and preparedSnapshot.fallbackEscalation or ""),
      fallbackReasons = CloneProfileSyncTextList(type(preparedSnapshot) == "table" and preparedSnapshot.fallbackReasons or {}),
      patchManifestSummary = type(preparedSnapshot) == "table" and preparedSnapshot.patchManifestSummary or nil,
      authoritativeArchiveScope = TrimText(
        type(preparedSnapshot) == "table" and preparedSnapshot.authoritativeArchiveScope or ""
      ),
      target = NormalizeCharacterKey(sendContext.target),
      totalChunks = #(type(sendContext.chunks) == "table" and sendContext.chunks or {}),
    }
  end

  profileSyncLocalOps.recordPreparedSnapshotSendDecision = function(preparedSnapshot, sendContext, action, errorMessage)
    if type(RecordProfileSyncDecision) ~= "function" then
      return
    end
    sendContext = type(sendContext) == "table" and sendContext or {}
    RecordProfileSyncDecision("send_prepared_snapshot", {
      action = action,
      sessionId = TrimText(sendContext.sessionId),
      profileName = TrimText(sendContext.profileName),
      mode = TrimText(sendContext.mode),
      reason = TrimText(sendContext.reason),
      transferKind = TrimText(sendContext.transferKind),
      transferKinds = { TrimText(sendContext.transferKind) },
      target = NormalizeCharacterKey(sendContext.target),
      targetCount = 1,
      chunkCount = #(type(sendContext.chunks) == "table" and sendContext.chunks or {}),
      domains = CloneProfileSyncDomainList(type(preparedSnapshot) == "table" and preparedSnapshot.domains or {}),
      subdomains = CloneProfileSyncSubdomainList(type(preparedSnapshot) == "table" and preparedSnapshot.subdomains or {}),
      requestedDomains = CloneProfileSyncDomainList(type(preparedSnapshot) == "table" and preparedSnapshot.requestedDomains or {}),
      requestedSubdomains = CloneProfileSyncSubdomainList(type(preparedSnapshot) == "table" and preparedSnapshot.requestedSubdomains or {}),
      requestedScope = TrimText(type(preparedSnapshot) == "table" and preparedSnapshot.requestedScope or ""),
      scopeEscalated = type(preparedSnapshot) == "table" and preparedSnapshot.scopeEscalated == true or false,
      fullSnapshotFallback = type(preparedSnapshot) == "table" and preparedSnapshot.fullSnapshotFallback == true or false,
      fallbackEscalation = TrimText(type(preparedSnapshot) == "table" and preparedSnapshot.fallbackEscalation or ""),
      fallbackReasons = CloneProfileSyncTextList(type(preparedSnapshot) == "table" and preparedSnapshot.fallbackReasons or {}),
      authoritativeArchiveScope = TrimText(type(preparedSnapshot) == "table" and preparedSnapshot.authoritativeArchiveScope or ""),
      error = errorMessage,
    })
  end

  profileSyncLocalOps.findActiveSessionMember = function(activeSession, memberKey)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    for key, member in pairs(type(activeSession) == "table" and type(activeSession.members) == "table" and activeSession.members or {}) do
      if NormalizeCharacterKey(key) == resolvedMemberKey
        or NormalizeCharacterKey(type(member) == "table" and member.name or "") == resolvedMemberKey
      then
        return member
      end
    end
    return nil
  end

  profileSyncLocalOps.resolveArchiveTransactionScopes = function(transfer)
    transfer = type(transfer) == "table" and transfer or {}
    local transferLane = string.lower(TrimText(transfer.lane))
    if transferLane == "" and type(generationOps.NormalizeProfileTransferLane) == "function" then
      transferLane = string.lower(TrimText(generationOps.NormalizeProfileTransferLane(
        transfer.reason,
        type(transfer.scopeSubdomains) == "table" and transfer.scopeSubdomains or transfer.subdomains,
        transfer.transferKind
      )))
    end
    if transferLane ~= "archive" then
      return {}
    end
    local scopes = {}
    local seen = {}
    local function AddScope(scope)
      if scope ~= "" and not seen[scope] then
        seen[scope] = true
        scopes[#scopes + 1] = scope
      end
    end
    local reason = string.lower(TrimText(transfer.reason))
    if reason:find("loot_archive", 1, true) or reason:find("loot_list_archive", 1, true) then
      AddScope("lootList")
    end
    if reason:find("item_history", 1, true) then
      AddScope("itemHistory")
    end
    if reason:find("session_archive", 1, true) or reason:find("session_history", 1, true) then
      AddScope("sessionHistory")
    end
    if reason:find("fun_awards", 1, true) then
      AddScope("funAwards")
    end
    local subdomains = type(transfer.scopeSubdomains) == "table" and transfer.scopeSubdomains
      or type(transfer.subdomains) == "table" and transfer.subdomains
      or {}
    for _, subdomain in ipairs(subdomains) 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
        AddScope("funAwards")
      elseif resolvedSubdomain:find("^slb:", 1, false) then
        AddScope("itemHistory")
      elseif resolvedSubdomain:find("^llr:", 1, false) or resolvedSubdomain:find("^lmr:", 1, false) then
        AddScope("lootList")
      elseif resolvedSubdomain:find("^ssr:", 1, false) then
        AddScope("sessionHistory")
      end
    end
    return scopes
  end

  profileSyncLocalOps.getArchiveTransactionExpectedChecksums = function(profileName, activeSession)
    if type(GetLootProfileSubchecksumManifest) ~= "function" then
      return {}
    end
    local manifest = GetLootProfileSubchecksumManifest(profileName, { "loot", "session" })
    return profileSyncLocalOps.buildProfileSyncArchiveScopeChecksums(manifest, activeSession)
  end

  profileSyncLocalOps.beginArchiveTransactionsForTransfer = function(activeSession, profileName, memberKey, transfer)
    local member = profileSyncLocalOps.findActiveSessionMember(activeSession, memberKey)
    local scopes = profileSyncLocalOps.resolveArchiveTransactionScopes(transfer)
    if type(member) ~= "table" or #scopes == 0 or type(generationOps.BeginArchiveTransaction) ~= "function" then
      return 0
    end
    local expectedChecksums = profileSyncLocalOps.getArchiveTransactionExpectedChecksums(profileName, activeSession)
    local started = 0
    for _, scope in ipairs(scopes) do
      local manifestLeafCount = 0
      for _, subdomain in ipairs(type(transfer.scopeSubdomains) == "table" and transfer.scopeSubdomains or {}) do
        local resolvedSubdomain = string.lower(TrimText(subdomain))
        if (scope == "lootList" and (resolvedSubdomain:find("^llr:", 1, false) or resolvedSubdomain:find("^lmr:", 1, false)))
          or (scope == "itemHistory" and resolvedSubdomain:find("^slb:", 1, false))
          or (scope == "sessionHistory" and resolvedSubdomain:find("^ssr:", 1, false))
          or (scope == "funAwards" and (
            resolvedSubdomain == "lrsr"
            or resolvedSubdomain == "lrsv"
            or resolvedSubdomain:find("^lre:", 1, false)
            or resolvedSubdomain:find("^lve:", 1, false)
          ))
        then
          manifestLeafCount = manifestLeafCount + 1
        end
      end
      local transaction = generationOps.BeginArchiveTransaction(member, scope, {
        sessionId = TrimText(type(activeSession) == "table" and activeSession.id or ""),
        transferId = transfer.transferId,
        generation = transfer.generation,
        expectedChecksum = expectedChecksums[scope],
        manifestChecksum = expectedChecksums[scope],
        manifestLeafCount = manifestLeafCount,
        reason = transfer.reason,
        transferKind = transfer.transferKind,
        resetAttempts = string.lower(TrimText(transfer.reason)):find("^host_push", 1, false) ~= nil
          or transfer.hostAuthoritativeOverride == true,
        at = GetNow(),
        maxAttempts = 3,
      })
      if type(transaction) == "table" then
        started = started + 1
      end
    end
    return started
  end

  profileSyncLocalOps.markArchiveTransferState = function(transfer, state, details)
    transfer = type(transfer) == "table" and transfer or {}
    details = type(details) == "table" and details or {}
    local activeSession, activeProfileName = GetActiveLootSession()
    if type(activeSession) ~= "table" or TrimText(activeSession.id) ~= TrimText(transfer.sessionId) then
      return false
    end
    local member = profileSyncLocalOps.findActiveSessionMember(activeSession, transfer.target)
    if type(member) ~= "table" or type(generationOps.MarkArchiveTransactionState) ~= "function" then
      return false
    end
    local changed = false
    for _, scope in ipairs(profileSyncLocalOps.resolveArchiveTransactionScopes(transfer)) do
      local marked = generationOps.MarkArchiveTransactionState(member, scope, state, {
        transferId = transfer.transferId,
        generation = transfer.generation,
        at = details.at or GetNow(),
        error = details.error,
        appliedChecksum = details.appliedChecksum,
      })
      changed = marked == true or changed
    end
    if changed and type(RecordProfileSyncDecision) == "function" then
      RecordProfileSyncDecision("archive_scope_transaction", {
        action = TrimText(state),
        sessionId = TrimText(transfer.sessionId),
        profileName = FirstNonEmptyText(transfer.profileName, activeProfileName),
        reason = TrimText(transfer.reason),
        transferKind = TrimText(transfer.transferKind),
        target = NormalizeCharacterKey(transfer.target),
        error = TrimText(details.error),
      })
    end
    return changed
  end

  profileSyncLocalOps.canRetryArchiveTransfer = function(transfer)
    transfer = type(transfer) == "table" and transfer or {}
    local activeSession = select(1, GetActiveLootSession())
    local member = profileSyncLocalOps.findActiveSessionMember(activeSession, transfer.target)
    local scopes = profileSyncLocalOps.resolveArchiveTransactionScopes(transfer)
    if type(member) ~= "table" or #scopes == 0 or type(generationOps.GetArchiveTransactionState) ~= "function" then
      return true, "not_archive_scoped"
    end
    local states = generationOps.GetArchiveTransactionState(member)
    for _, scope in ipairs(scopes) do
      local transaction = type(states[scope]) == "table" and states[scope] or nil
      if type(transaction) == "table"
        and math.max(0, tonumber(transaction.attempts) or 0) >= math.max(1, tonumber(transaction.maxAttempts) or 3)
      then
        profileSyncLocalOps.markArchiveTransferState(transfer, "failed", {
          error = "Archive scope retry limit reached after " .. tostring(transaction.attempts) .. " attempts.",
        })
        return false, "archive_retry_exhausted"
      end
    end
    return true, "archive_retry_available"
  end

  profileSyncLocalOps.reconcileMemberArchiveTransactions = function(activeSession, memberKey, member)
    member = type(member) == "table" and member or profileSyncLocalOps.findActiveSessionMember(activeSession, memberKey)
    if type(member) ~= "table" or type(generationOps.ReconcileArchiveTransactions) ~= "function" then
      return false, {}
    end
    local changed, confirmedScopes = generationOps.ReconcileArchiveTransactions(member)
    if changed and type(RecordProfileSyncDecision) == "function" then
      RecordProfileSyncDecision("archive_scope_transaction", {
        action = "checksum_confirmed",
        sessionId = TrimText(type(activeSession) == "table" and activeSession.id or ""),
        profileName = TrimText(type(activeSession) == "table" and activeSession.profileName or ""),
        target = NormalizeCharacterKey(memberKey),
        requestedSubdomains = confirmedScopes,
      })
    end
    return changed, confirmedScopes
  end

  local function SendPreparedProfileSnapshot(preparedSnapshot, sessionId, target, opts)
    if type(preparedSnapshot) ~= "table" or type(preparedSnapshot.chunks) ~= "table" then
      return false, "Profile snapshot is not prepared."
    end

    opts = type(opts) == "table" and opts or {}
    local sendContext = profileSyncLocalOps.buildPreparedSnapshotSendContext(preparedSnapshot, sessionId, target, opts)
    local profileName = TrimText(sendContext.profileName)
    local profileId = TrimText(sendContext.profileId)
    local chunks = sendContext.chunks
    local transferId = string.format("PX-%d-%d", tonumber(time and time() or 0) or 0, math.random(1000, 9999))
    local transferLane = generationOps.NormalizeProfileTransferLane(TrimText(opts.reason), preparedSnapshot.subdomains, preparedSnapshot.transferKind)
    local annotationPayload = profileSyncLocalOps.buildPreparedSnapshotAnnotationPayload(preparedSnapshot, sendContext)
    if type(sessionRuntimeOps.splitProfileSnapshotPayload) == "function" then
      local safeChunks, splitError = sessionRuntimeOps.splitProfileSnapshotPayload(
        table.concat(chunks),
        transferId,
        math.max(1, tonumber(type(deps.GetProfileSnapshotChunkSize) == "function" and deps.GetProfileSnapshotChunkSize() or 120) or 120)
      )
      if type(safeChunks) ~= "table" or #safeChunks <= 0 then
        if type(sessionRuntimeOps.recordOutboundPayloadReject) == "function" then
          sessionRuntimeOps.recordOutboundPayloadReject("PSYNC_CHUNK", splitError, 0, {
            sessionId = sessionId,
            target = target,
            mode = annotationPayload.mode,
            lane = transferLane,
            transferKind = annotationPayload.transferKind,
            scopeSubdomains = annotationPayload.scopeSubdomains,
            requestedSubdomains = annotationPayload.requestedSubdomains,
            scopeDomains = annotationPayload.scopeDomains,
            requestedDomains = annotationPayload.requestedDomains,
          })
        end
        profileSyncLocalOps.recordPreparedSnapshotSendDecision(
          preparedSnapshot,
          sendContext,
          "failed",
          splitError or "Profile snapshot chunk payload exceeds the safe addon-message limit."
        )
        return false, splitError or "Profile snapshot chunk payload exceeds the safe addon-message limit."
      end
      chunks = safeChunks
      sendContext.chunks = chunks
    end
    annotationPayload.totalChunks = #chunks
    local mode = TrimText(sendContext.mode)
    local domains = TrimText(sendContext.domains)
    local transferKind = TrimText(sendContext.transferKind)
    local subdomains = TrimText(sendContext.subdomains)
    local previewGeneration = 0
    if type(sessionRuntimeOps.previewOutboundProfileTransferGeneration) == "function" then
      previewGeneration = math.max(0, tonumber(sessionRuntimeOps.previewOutboundProfileTransferGeneration(annotationPayload)) or 0)
    end
    if type(sessionRuntimeOps.validateProfileSnapshotStartPayload) == "function" then
      local startPayloadSafe, startPayloadReason, startPayloadBytes = sessionRuntimeOps.validateProfileSnapshotStartPayload(
        transferId,
        sessionId,
        profileName,
        profileId,
        tostring(#chunks),
        mode,
        domains,
        transferKind,
        subdomains,
        tostring(previewGeneration),
        transferLane,
        sendContext.hostAuthoritativeOverride == true and "HOST_OVERRIDE" or ""
      )
      if not startPayloadSafe then
        if type(sessionRuntimeOps.recordOutboundPayloadReject) == "function" then
          sessionRuntimeOps.recordOutboundPayloadReject("PSYNC_START", startPayloadReason, startPayloadBytes, {
            sessionId = sessionId,
            target = target,
            mode = annotationPayload.mode,
            lane = transferLane,
            transferKind = annotationPayload.transferKind,
            scopeSubdomains = annotationPayload.scopeSubdomains,
            requestedSubdomains = annotationPayload.requestedSubdomains,
            scopeDomains = annotationPayload.scopeDomains,
            requestedDomains = annotationPayload.requestedDomains,
          })
        end
        profileSyncLocalOps.recordPreparedSnapshotSendDecision(
          preparedSnapshot,
          sendContext,
          "failed",
          "Profile snapshot metadata exceeds the safe addon-message limit."
        )
        return false, "Profile snapshot metadata exceeds the safe addon-message limit."
      end
    end
    local annotatedTransfer = nil

    if type(sessionRuntimeOps.annotateTransfer) == "function" then
      annotatedTransfer = sessionRuntimeOps.annotateTransfer(
        transferId,
        annotationPayload
      )
    end
    local transferGeneration = math.max(0, tonumber(type(annotatedTransfer) == "table" and annotatedTransfer.generation or 0) or 0)
    generationOps.RememberTransferGenerationState(sessionId, target, transferLane, transferGeneration, GetNow(), false)
    if type(annotatedTransfer) == "table" then
      local activeSession = select(1, GetActiveLootSession())
      profileSyncLocalOps.beginArchiveTransactionsForTransfer(activeSession, profileName, target, annotatedTransfer)
    end

    local sent, sendError = SendComm(
      "PSYNC_START",
      "WHISPER",
      target,
      transferId,
      sessionId,
      profileName,
      profileId,
      tostring(#chunks),
      mode,
      domains,
      transferKind,
      subdomains,
      tostring(transferGeneration),
      transferLane,
      sendContext.hostAuthoritativeOverride == true and "HOST_OVERRIDE" or ""
    )
    if not sent then
      profileSyncLocalOps.markArchiveTransferState(annotatedTransfer, "failed", {
        error = sendError or "Profile snapshot start could not be sent.",
      })
      profileSyncLocalOps.recordPreparedSnapshotSendDecision(preparedSnapshot, sendContext, "failed", sendError or "Profile snapshot start could not be sent.")
      return false, sendError or "Profile snapshot start could not be sent."
    end
    for index, chunk in ipairs(chunks) do
      local chunkSent, chunkError = SendComm("PSYNC_CHUNK", "WHISPER", target, transferId, tostring(index), chunk)
      if not chunkSent then
        profileSyncLocalOps.markArchiveTransferState(annotatedTransfer, "failed", {
          error = chunkError or ("Profile snapshot chunk " .. tostring(index) .. " could not be sent."),
        })
        profileSyncLocalOps.recordPreparedSnapshotSendDecision(
          preparedSnapshot,
          sendContext,
          "failed",
          chunkError or ("Profile snapshot chunk " .. tostring(index) .. " could not be sent.")
        )
        return false, chunkError or ("Profile snapshot chunk " .. tostring(index) .. " could not be sent.")
      end
    end
    local endSent, endError = SendComm("PSYNC_END", "WHISPER", target, transferId)
    if not endSent then
      profileSyncLocalOps.markArchiveTransferState(annotatedTransfer, "failed", {
        error = endError or "Profile snapshot end could not be sent.",
      })
      profileSyncLocalOps.recordPreparedSnapshotSendDecision(preparedSnapshot, sendContext, "failed", endError or "Profile snapshot end could not be sent.")
      return false, endError or "Profile snapshot end could not be sent."
    end
    if type(sessionRuntimeOps.annotateTransfer) == "function" then
      sessionRuntimeOps.annotateTransfer(
        transferId,
        annotationPayload
      )
    end
    profileSyncLocalOps.recordPreparedSnapshotSendDecision(preparedSnapshot, sendContext, "sent", nil)
    return true, transferId
  end

  local function SendProfileSnapshot(profileName, sessionId, target, opts)
    local preparedSnapshot, err = profileSyncLocalOps.prepareProfileSnapshotTransfer(profileName, opts)
    if not preparedSnapshot then
      return false, err
    end
    return SendPreparedProfileSnapshot(preparedSnapshot, sessionId, target, opts)
  end

  profileSyncLocalOps.finalizePreparedRepairTransferDetail = function(detail, transfers, fallbackReasons)
    detail = type(detail) == "table" and detail or {}
    detail.transferKinds = BuildPreparedTransferKindList(transfers)
    detail.fallbackReasons = CloneProfileSyncTextList(fallbackReasons)
    local scopeEscalationKinds = {}
    detail.scopeEscalated = false
    detail.fullSnapshotFallback = false
    for _, preparedTransfer in ipairs(type(transfers) == "table" and transfers or {}) do
      if type(preparedTransfer) == "table" then
        detail.scopeEscalated = detail.scopeEscalated or preparedTransfer.scopeEscalated == true
        detail.fullSnapshotFallback = detail.fullSnapshotFallback or preparedTransfer.fullSnapshotFallback == true
        AppendDecisionReason(scopeEscalationKinds, preparedTransfer.fallbackEscalation)
      end
    end
    detail.scopeEscalationKinds = CloneProfileSyncTextList(scopeEscalationKinds)
    return detail
  end

  profileSyncLocalOps.recordPreparedRepairTransferDecision = function(sessionId, profileName, opts, detail, transfers, fallbackReasons, action, errorMessage)
    detail = profileSyncLocalOps.finalizePreparedRepairTransferDetail(detail, transfers, fallbackReasons)
    if type(RecordProfileSyncDecision) ~= "function" then
      return detail
    end
    RecordProfileSyncDecision("build_repair_transfers", {
      action = action,
      sessionId = TrimText(sessionId),
      profileName = TrimText(profileName),
      mode = TrimText(type(opts) == "table" and opts.mode or ""),
      reason = TrimText(type(opts) == "table" and opts.reason or ""),
      transferKinds = CloneProfileSyncTextList(detail.transferKinds),
      requestedDomains = CloneProfileSyncDomainList(detail.requestedDomains),
      requestedSubdomains = CloneProfileSyncSubdomainList(detail.requestedSubdomains),
      patchSubdomains = CloneProfileSyncSubdomainList(detail.patchTransferSubdomains),
      snapshotFallbackSubdomains = CloneProfileSyncSubdomainList(detail.snapshotFallbackSubdomains),
      transferCount = #(type(transfers) == "table" and transfers or {}),
      requestedScope = TrimText(detail.requestedScope),
      scopeEscalated = detail.scopeEscalated == true,
      fullSnapshotFallback = detail.fullSnapshotFallback == true,
      scopeEscalationKinds = CloneProfileSyncTextList(detail.scopeEscalationKinds),
      fallbackReason = type(detail.fallbackReasons) == "table" and detail.fallbackReasons[1] or nil,
      fallbackReasons = CloneProfileSyncTextList(detail.fallbackReasons),
      error = errorMessage,
    })
    return detail
  end

  profileSyncLocalOps.buildPreparedProfileRepairTransfersUncached = function(profileName, sessionId, memberKey, opts)
    opts = type(opts) == "table" and opts or {}
    local resolvedDomains = ResolveProfileRevisionDomainList(opts.domains)
    local resolvedSubdomains = NormalizeRequestedProfileSyncSubdomains(opts.subdomains, resolvedDomains)
    local transfers = {}
    local detail = {
      patchTransfers = 0,
      patchSubdomains = 0,
      snapshotTransfers = 0,
      snapshotSubdomains = 0,
      requestedDomains = CloneProfileSyncDomainList(resolvedDomains),
      requestedSubdomains = CloneProfileSyncSubdomainList(resolvedSubdomains),
      patchTransferSubdomains = {},
      patchStateFallbackSubdomains = {},
      snapshotFallbackSubdomains = {},
      transferKinds = {},
      fallbackReasons = {},
      patchManifestMatched = false,
      requestedScope = #resolvedSubdomains > 0 and "precise" or (#resolvedDomains > 0 and "targeted" or "full"),
      scopeEscalated = false,
      fullSnapshotFallback = false,
      scopeEscalationKinds = {},
    }
    local fallbackReasons = {}
    local localProfileId = TrimText(select(1, GetLootProfileId(profileName)) or "")
    local remoteRevisionSummary = CaptureSessionMemberRevisionSummary(sessionId, memberKey, profileName, "")
    if localProfileId ~= "" and type(remoteRevisionSummary) == "table" then
      HydratePersistedSessionMemberBaseline(sessionId, localProfileId, profileName, memberKey, remoteRevisionSummary)
    end

    if #resolvedSubdomains == 0 then
      local preparedSnapshot, prepareError = profileSyncLocalOps.prepareProfileSnapshotTransfer(profileName, {
        domains = #resolvedDomains > 0 and resolvedDomains or nil,
        mode = TrimText(opts.mode),
        reason = TrimText(opts.reason),
        sessionId = TrimText(sessionId),
      })
      if not preparedSnapshot then
        profileSyncLocalOps.recordPreparedRepairTransferDecision(sessionId, profileName, opts, detail, transfers, fallbackReasons, "failed", prepareError)
        return nil, prepareError, detail
      end
      detail.snapshotTransfers = 1
      transfers[1] = preparedSnapshot
      profileSyncLocalOps.recordPreparedRepairTransferDecision(sessionId, profileName, opts, detail, transfers, fallbackReasons, "prepared", nil)
      return transfers, nil, detail
    end

    local patchReadySubdomains = {}
    local patchReadyLookup = {}
    local patchCapableLookup = {}
    for _, subdomain in ipairs(type(FilterLootProfilePatchCapableSubdomains) == "function"
      and FilterLootProfilePatchCapableSubdomains(resolvedSubdomains)
      or {}) do
      patchCapableLookup[string.lower(TrimText(subdomain))] = true
    end
    local patchManifestState = GetMemberPatchManifestState(sessionId, memberKey)
    local expectedPatchManifestToken = TrimText(opts.patchManifestToken)
    local patchManifestMatches = expectedPatchManifestToken == ""
      or (type(patchManifestState) == "table" and TrimText(patchManifestState.token) == expectedPatchManifestToken)
    detail.patchManifestMatched = patchManifestMatches
    if expectedPatchManifestToken ~= "" and not patchManifestMatches then
      AppendDecisionReason(fallbackReasons, "patch_manifest_token_mismatch")
    end
    if patchManifestMatches and type(patchManifestState) == "table" and type(patchManifestState.bySubdomain) == "table" then
      for _, subdomain in ipairs(type(FilterLootProfilePatchCapableSubdomains) == "function"
        and FilterLootProfilePatchCapableSubdomains(resolvedSubdomains)
        or {}) do
        if type(patchManifestState.bySubdomain[subdomain]) == "table" then
          patchReadyLookup[string.lower(subdomain)] = true
          patchReadySubdomains[#patchReadySubdomains + 1] = subdomain
        end
      end
    end

    local requestedSubdomainsByDomain = {}
    for _, subdomain in ipairs(resolvedSubdomains) do
      local domain = type(GetLootProfileSubdomainParentDomain) == "function"
        and GetLootProfileSubdomainParentDomain(subdomain)
        or ""
      if domain ~= "" then
        requestedSubdomainsByDomain[domain] = requestedSubdomainsByDomain[domain] or {}
        requestedSubdomainsByDomain[domain][#requestedSubdomainsByDomain[domain] + 1] = subdomain
      end
    end

    local patchTransferSubdomains = {}
    local patchStateFallbackSubdomains = {}
    local snapshotFallbackSubdomains = {}
    local successfulPatchSubdomains = {}
    for _, domain in ipairs(type(ResolveLootProfileDomainsForSubdomains) == "function"
      and ResolveLootProfileDomainsForSubdomains(resolvedSubdomains)
      or resolvedDomains) do
      local domainSubdomains = requestedSubdomainsByDomain[domain] or {}
      for _, subdomain in ipairs(domainSubdomains) do
        local subdomainKey = string.lower(TrimText(subdomain))
        if patchReadyLookup[subdomainKey] then
          patchTransferSubdomains[#patchTransferSubdomains + 1] = subdomain
        elseif patchCapableLookup[subdomainKey] then
          patchStateFallbackSubdomains[#patchStateFallbackSubdomains + 1] = subdomain
          snapshotFallbackSubdomains[#snapshotFallbackSubdomains + 1] = subdomain
        else
          snapshotFallbackSubdomains[#snapshotFallbackSubdomains + 1] = subdomain
        end
      end
    end

    if #patchStateFallbackSubdomains > 0 then
      AppendDecisionReason(fallbackReasons, "missing_patch_state")
      profileSyncLocalOps.queueAutoPatchManifestRequest(memberKey, patchStateFallbackSubdomains)
    elseif #patchReadySubdomains == 0 and next(patchCapableLookup) ~= nil then
      AppendDecisionReason(fallbackReasons, "no_patch_ready_subdomains")
    end

    if #patchTransferSubdomains > 0 then
      local preparedPatch = profileSyncLocalOps.prepareProfileSnapshotTransfer(profileName, {
        domains = type(ResolveLootProfileDomainsForSubdomains) == "function"
          and ResolveLootProfileDomainsForSubdomains(patchTransferSubdomains)
          or resolvedDomains,
        subdomains = patchTransferSubdomains,
        patchManifest = patchManifestState,
        mode = TrimText(opts.mode),
        reason = TrimText(opts.reason),
        sessionId = TrimText(sessionId),
      })
      if type(preparedPatch) == "table" and preparedPatch.transferKind == "PATCHES" then
        transfers[#transfers + 1] = preparedPatch
        detail.patchTransfers = 1
        detail.patchSubdomains = #patchTransferSubdomains
        successfulPatchSubdomains = CloneProfileSyncSubdomainList(patchTransferSubdomains)
      else
        AppendDecisionReason(fallbackReasons, "patch_export_snapshot_fallback")
        for _, subdomain in ipairs(patchTransferSubdomains) do
          snapshotFallbackSubdomains[#snapshotFallbackSubdomains + 1] = subdomain
        end
      end
    end

    detail.patchTransferSubdomains = CloneProfileSyncSubdomainList(successfulPatchSubdomains)
    detail.patchStateFallbackSubdomains = CloneProfileSyncSubdomainList(patchStateFallbackSubdomains)
    detail.snapshotFallbackSubdomains = CloneProfileSyncSubdomainList(snapshotFallbackSubdomains)
    if #snapshotFallbackSubdomains > 0 then
      local preparedSnapshot, prepareError = profileSyncLocalOps.prepareProfileSnapshotTransfer(profileName, {
        domains = type(ResolveLootProfileDomainsForSubdomains) == "function"
          and ResolveLootProfileDomainsForSubdomains(snapshotFallbackSubdomains)
          or resolvedDomains,
        subdomains = snapshotFallbackSubdomains,
        mode = TrimText(opts.mode),
        reason = TrimText(opts.reason),
        sessionId = TrimText(sessionId),
      })
      if not preparedSnapshot then
        profileSyncLocalOps.recordPreparedRepairTransferDecision(
          sessionId,
          profileName,
          opts,
          detail,
          transfers,
          fallbackReasons,
          #transfers > 0 and "partial_failed" or "failed",
          prepareError
        )
        return #transfers > 0 and transfers or nil, prepareError, detail
      end
      transfers[#transfers + 1] = preparedSnapshot
      detail.snapshotTransfers = detail.snapshotTransfers + 1
      detail.snapshotSubdomains = #snapshotFallbackSubdomains
    end

    if #transfers == 0 then
      profileSyncLocalOps.recordPreparedRepairTransferDecision(sessionId, profileName, opts, detail, transfers, fallbackReasons, "failed", "No repair transfer could be prepared.")
      return nil, "No repair transfer could be prepared.", detail
    end
    profileSyncLocalOps.recordPreparedRepairTransferDecision(sessionId, profileName, opts, detail, transfers, fallbackReasons, "prepared", nil)
    return transfers, nil, detail
  end

  profileSyncLocalOps.isArchiveRepairPreparationCacheEligible = function(profileName, sessionId, memberKey, opts)
    opts = type(opts) == "table" and opts or {}
    if TrimText(profileName) == "" or TrimText(sessionId) == "" or NormalizeCharacterKey(memberKey) == "" then
      return false
    end
    if string.upper(TrimText(opts.mode)) ~= "BACKGROUND" then
      return false
    end
    if type(opts.rowSelectionsBySubdomain) == "table" or type(opts.rowMapsBySubdomain) == "table"
      or type(opts.prebuiltRowsBySubdomain) == "table"
    then
      return false
    end
    local normalizedDomains = ResolveProfileRevisionDomainList(opts.domains)
    local normalizedSubdomains = NormalizeRequestedProfileSyncSubdomains(opts.subdomains, normalizedDomains)
    return generationOps.NormalizeProfileTransferLane(TrimText(opts.reason), normalizedSubdomains, TrimText(opts.transferKind)) == "archive"
  end

  profileSyncLocalOps.buildArchiveRepairPreparationSignature = function(profileName, sessionId, memberKey, 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 "", ""
    end
    local domains = ResolveProfileRevisionDomainList(opts.domains)
    local subdomains = NormalizeRequestedProfileSyncSubdomains(opts.subdomains, domains)
    local profileId = TrimText(select(1, GetLootProfileId(resolvedProfileName)) or "")
    local revisionSummary = NormalizeRevisionSummary(
      GetLootProfileRevisionSummary(resolvedProfileName),
      resolvedProfileName,
      profileId
    )
    local revisionSignature = BuildStableValueSignature(revisionSummary)
    local patchManifestState = GetMemberPatchManifestState(resolvedSessionId, resolvedMemberKey)
    local observedPatchManifestToken = TrimText(type(patchManifestState) == "table" and patchManifestState.token or "")
    local lane = generationOps.NormalizeProfileTransferLane(TrimText(opts.reason), subdomains, TrimText(opts.transferKind))
    return table.concat({
      string.lower(resolvedSessionId),
      string.lower(resolvedMemberKey),
      string.lower(resolvedProfileName),
      string.lower(profileId),
      string.upper(TrimText(opts.mode)),
      string.lower(lane),
      string.lower(TrimText(opts.reason)),
      TrimText(opts.transferKind),
      EncodeProfileRevisionDomains(domains),
      table.concat(CloneProfileSyncSubdomainList(subdomains), "\30"),
      TrimText(opts.patchManifestToken),
      observedPatchManifestToken,
      revisionSignature,
    }, "\31"), revisionSignature
  end

  profileSyncLocalOps.clonePreparedArchiveRepairCacheValue = function(value)
    if type(value) ~= "table" then
      return value
    end
    if type(deps.DeepCopy) == "function" then
      local copiedOk, copied = pcall(deps.DeepCopy, value)
      if copiedOk and type(copied) == "table" then
        return copied
      end
    end
    return value
  end

  profileSyncLocalOps.prunePreparedArchiveRepairCache = function(now)
    local currentTime = math.max(0, tonumber(now) or GetNow())
    local retained = {}
    local removed = 0
    for cacheKey, entry in pairs(type(profileSyncCaches.preparedArchiveRepairs) == "table"
      and profileSyncCaches.preparedArchiveRepairs or {}) do
      local expiresAt = math.max(0, tonumber(type(entry) == "table" and entry.expiresAt or 0) or 0)
      if type(entry) ~= "table" or expiresAt <= currentTime then
        profileSyncCaches.preparedArchiveRepairs[cacheKey] = nil
        removed = removed + 1
      else
        retained[#retained + 1] = {
          key = cacheKey,
          createdAt = math.max(0, tonumber(entry.createdAt) or 0),
        }
      end
    end
    table.sort(retained, function(left, right)
      if left.createdAt ~= right.createdAt then
        return left.createdAt < right.createdAt
      end
      return left.key < right.key
    end)
    while #retained > math.max(1, tonumber(profileSyncConfig.maxPreparedArchiveRepairs) or 12) do
      local oldest = table.remove(retained, 1)
      profileSyncCaches.preparedArchiveRepairs[oldest.key] = nil
      removed = removed + 1
    end
    if removed > 0 then
      profileSyncSessionState.archivePreparationPrunedTotal = math.max(0,
        tonumber(profileSyncSessionState.archivePreparationPrunedTotal) or 0) + removed
    end
    return removed, #retained
  end

  profileSyncLocalOps.invalidatePreparedArchiveRepairCacheForRevision = function(sessionId, memberKey, profileName, revisionSignature)
    local resolvedSessionId = TrimText(sessionId)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    local resolvedProfileName = TrimText(profileName)
    local removed = 0
    if resolvedSessionId == "" or resolvedMemberKey == "" or resolvedProfileName == "" then
      return removed
    end
    for cacheKey, entry in pairs(type(profileSyncCaches.preparedArchiveRepairs) == "table"
      and profileSyncCaches.preparedArchiveRepairs or {}) do
      if type(entry) == "table"
        and TrimText(entry.sessionId) == resolvedSessionId
        and NormalizeCharacterKey(entry.memberKey) == resolvedMemberKey
        and string.lower(TrimText(entry.profileName)) == string.lower(resolvedProfileName)
        and TrimText(entry.revisionSignature) ~= TrimText(revisionSignature)
      then
        profileSyncCaches.preparedArchiveRepairs[cacheKey] = nil
        removed = removed + 1
      end
    end
    if removed > 0 then
      profileSyncSessionState.archivePreparationPrunedTotal = math.max(0,
        tonumber(profileSyncSessionState.archivePreparationPrunedTotal) or 0) + removed
    end
    return removed
  end

  INTERNAL_API.LIDCOUNCIL_ShouldReuseArchiveRepairPreparation_Impl = function(entry, signature, revisionSignature, now)
    return type(entry) == "table"
      and TrimText(entry.signature) ~= ""
      and TrimText(entry.signature) == TrimText(signature)
      and TrimText(entry.revisionSignature) ~= ""
      and TrimText(entry.revisionSignature) == TrimText(revisionSignature)
      and math.max(0, tonumber(entry.expiresAt) or 0) > math.max(0, tonumber(now) or 0)
      and type(entry.transfers) == "table"
      and #entry.transfers > 0
  end

  profileSyncLocalOps.buildPreparedProfileRepairTransfers = function(profileName, sessionId, memberKey, opts)
    opts = type(opts) == "table" and opts or {}
    if not profileSyncLocalOps.isArchiveRepairPreparationCacheEligible(profileName, sessionId, memberKey, opts) then
      return profileSyncLocalOps.buildPreparedProfileRepairTransfersUncached(profileName, sessionId, memberKey, opts)
    end
    local signature, revisionSignature = profileSyncLocalOps.buildArchiveRepairPreparationSignature(profileName, sessionId, memberKey, opts)
    if signature == "" or revisionSignature == "" then
      return profileSyncLocalOps.buildPreparedProfileRepairTransfersUncached(profileName, sessionId, memberKey, opts)
    end
    local now = GetNow()
    profileSyncLocalOps.prunePreparedArchiveRepairCache(now)
    profileSyncLocalOps.invalidatePreparedArchiveRepairCacheForRevision(sessionId, memberKey, profileName, revisionSignature)
    local entry = profileSyncCaches.preparedArchiveRepairs[signature]
    if INTERNAL_API.LIDCOUNCIL_ShouldReuseArchiveRepairPreparation_Impl(entry, signature, revisionSignature, now) then
      local transfers = profileSyncLocalOps.clonePreparedArchiveRepairCacheValue(entry.transfers)
      local detail = profileSyncLocalOps.clonePreparedArchiveRepairCacheValue(entry.detail)
      profileSyncSessionState.archivePreparationCoalescedTotal = math.max(0,
        tonumber(profileSyncSessionState.archivePreparationCoalescedTotal) or 0) + 1
      profileSyncSessionState.lastArchivePreparationCoalescedAt = now
      profileSyncSessionState.lastArchivePreparationCoalescedTarget = NormalizeCharacterKey(memberKey)
      profileSyncLocalOps.recordPreparedRepairTransferDecision(
        sessionId,
        profileName,
        opts,
        detail,
        transfers,
        type(detail) == "table" and detail.fallbackReasons or {},
        "coalesced_prepared",
        nil
      )
      return transfers, nil, detail
    end

    local transfers, prepareError, detail = profileSyncLocalOps.buildPreparedProfileRepairTransfersUncached(profileName, sessionId, memberKey, opts)
    if type(transfers) == "table" and #transfers > 0 then
      profileSyncCaches.preparedArchiveRepairs[signature] = {
        signature = signature,
        revisionSignature = revisionSignature,
        sessionId = TrimText(sessionId),
        memberKey = NormalizeCharacterKey(memberKey),
        profileName = TrimText(profileName),
        createdAt = now,
        expiresAt = now + math.max(0.1, tonumber(profileSyncConfig.preparedArchiveRepairRetentionSeconds) or 3),
        transfers = profileSyncLocalOps.clonePreparedArchiveRepairCacheValue(transfers),
        detail = profileSyncLocalOps.clonePreparedArchiveRepairCacheValue(detail),
      }
      profileSyncLocalOps.prunePreparedArchiveRepairCache(now)
    end
    return transfers, prepareError, detail
  end

  profileSyncLocalOps.buildProfilePatchManifestResponseSignature = function(profileId, manifestData)
    return TrimText(profileId) .. "\31" .. tostring(manifestData or "")
  end

  local function SendProfileSubdomainPatchManifest(profileName, sessionId, target, subdomains, opts)
    opts = type(opts) == "table" and opts or {}
    local resolvedProfileName = TrimText(profileName)
    local resolvedSessionId = TrimText(sessionId)
    local resolvedTarget = NormalizeCharacterKey(target)
    local normalizedSubdomains = type(FilterLootProfilePatchCapableSubdomains) == "function"
      and FilterLootProfilePatchCapableSubdomains(subdomains)
      or CloneProfileSyncSubdomainList(subdomains)
    if resolvedProfileName == "" or resolvedSessionId == "" or resolvedTarget == "" or #normalizedSubdomains == 0 then
      return false, "Patch manifest target or scope is missing."
    end

    local manifestData = type(opts.manifestData) == "string" and opts.manifestData or nil
    if manifestData == nil then
      manifestData = type(snapshotTransferOps.exportPatchManifest) == "function"
        and snapshotTransferOps.exportPatchManifest(resolvedProfileName, normalizedSubdomains)
        or nil
    end
    if type(manifestData) ~= "string" or manifestData == "" then
      return false, "Patch manifest export failed."
    end

    local localProfileId = FirstNonEmptyText(opts.profileId, select(1, GetLootProfileId(resolvedProfileName)) or "")
    local responseToken = TrimText(opts.responseToken)
    if responseToken == "" then
      responseToken = string.format("PSP-%d-%d", tonumber(time and time() or 0) or 0, math.random(1000, 9999))
    end
    local chunks = BuildProfileSnapshotChunks(manifestData)
    if type(sessionRuntimeOps.splitCommPayloadField) == "function" then
      local maxPartField = tostring(profileSyncConfig.maxIncomingPreciseMultipartParts)
      local safeChunks, splitError = sessionRuntimeOps.splitCommPayloadField(
        "PSUBPATCH_STATE",
        manifestData,
        { resolvedSessionId, resolvedProfileName, localProfileId, responseToken, maxPartField, maxPartField },
        { TrimText(opts.requestToken) },
        math.max(1, tonumber(type(deps.GetProfileSnapshotChunkSize) == "function" and deps.GetProfileSnapshotChunkSize() or 120) or 120)
      )
      if type(safeChunks) ~= "table" or #safeChunks <= 0 then
        if type(sessionRuntimeOps.recordOutboundPayloadReject) == "function" then
          sessionRuntimeOps.recordOutboundPayloadReject("PSUBPATCH_STATE", splitError, 0, {
            sessionId = resolvedSessionId,
            target = resolvedTarget,
          })
        end
        return false, splitError or "Patch manifest response exceeds the safe addon-message limit.", responseToken
      end
      chunks = safeChunks
    end
    if #chunks > profileSyncConfig.maxIncomingPreciseMultipartParts then
      if type(sessionRuntimeOps.recordOutboundPayloadReject) == "function" then
        sessionRuntimeOps.recordOutboundPayloadReject("PSUBPATCH_STATE", "multipart_part_limit_exceeded", 0, {
          sessionId = resolvedSessionId,
          target = resolvedTarget,
        })
      end
      return false, "Patch manifest response requires too many parts.", responseToken
    end
    if type(sessionRuntimeOps.validateCommPayload) == "function" then
      for index, chunk in ipairs(chunks) do
        local payloadSafe, payloadReason, payloadBytes = sessionRuntimeOps.validateCommPayload(
          "PSUBPATCH_STATE",
          resolvedSessionId,
          resolvedProfileName,
          localProfileId,
          responseToken,
          tostring(index),
          tostring(#chunks),
          chunk,
          TrimText(opts.requestToken)
        )
        if not payloadSafe then
          if type(sessionRuntimeOps.recordOutboundPayloadReject) == "function" then
            sessionRuntimeOps.recordOutboundPayloadReject("PSUBPATCH_STATE", payloadReason, payloadBytes, {
              sessionId = resolvedSessionId,
              target = resolvedTarget,
            })
          end
          return false, "Patch manifest response exceeds the safe addon-message limit.", responseToken
        end
      end
    end
    local sentCount = 0
    for index, chunk in ipairs(chunks) do
      local sent = SendComm(
        "PSUBPATCH_STATE",
        "WHISPER",
        resolvedTarget,
        resolvedSessionId,
        resolvedProfileName,
        localProfileId,
        responseToken,
        tostring(index),
        tostring(#chunks),
        chunk,
        TrimText(opts.requestToken)
      )
      if not sent then
        return false, "Patch manifest chunk could not be sent.", responseToken
      end
      sentCount = sentCount + 1
    end
    return sentCount > 0, sentCount, responseToken
  end

  profileSyncLocalOps.queueProfilePatchManifestResponse = function(sessionId, profileName, memberKey, subdomains, requestToken)
    local resolvedSessionId = TrimText(sessionId)
    local resolvedProfileName = TrimText(profileName)
    local resolvedTarget = NormalizeCharacterKey(memberKey)
    local resolvedSubdomains = type(FilterLootProfilePatchCapableSubdomains) == "function"
      and FilterLootProfilePatchCapableSubdomains(subdomains)
      or CloneProfileSyncSubdomainList(subdomains)
    if resolvedSessionId == "" or resolvedProfileName == "" or resolvedTarget == "" or #resolvedSubdomains == 0 then
      return 0
    end

    local now = GetNow()
    PrunePreciseResponseRuntime(now)
    local requestKey = profileSyncLocalOps.buildPatchManifestRequestQueueKey(resolvedSessionId, resolvedTarget)
    local pending = profileSyncResponseRuntime.precise.pendingPatchManifest[requestKey]
    if type(pending) == "table" then
      local existingCsv = table.concat(pending.subdomains, ",")
      pending.subdomains = profileSyncLocalOps.mergePatchManifestRequestSubdomains(pending.subdomains, resolvedSubdomains)
      pending.updatedAt = now
      if TrimText(requestToken) ~= "" then
        pending.requestToken = TrimText(requestToken)
      end
      return table.concat(pending.subdomains, ",") ~= existingCsv and 1 or 0
    end

    profileSyncResponseRuntime.precise.pendingPatchManifest[requestKey] = {
      sessionId = resolvedSessionId,
      profileName = resolvedProfileName,
      target = resolvedTarget,
      subdomains = resolvedSubdomains,
      queuedAt = now,
      updatedAt = now,
      requestToken = TrimText(requestToken),
    }

    if type(Compat) == "table" and type(Compat.After) == "function" then
      profileSyncResponseRuntime.precise.timerToken = math.max(0, tonumber(profileSyncResponseRuntime.precise.timerToken) or 0) + 1
      local timerToken = profileSyncResponseRuntime.precise.timerToken
      profileSyncResponseRuntime.precise.pendingPatchManifest[requestKey].timerToken = timerToken
      Compat.After(profileSyncConfig.patchManifestRequestCoalesceDelaySeconds, function()
        profileSyncLocalOps.flushQueuedProfilePatchManifestResponse(requestKey, timerToken)
      end)
      return 1
    end

    return profileSyncLocalOps.flushQueuedProfilePatchManifestResponse(requestKey)
  end

  profileSyncLocalOps.flushQueuedProfilePatchManifestResponse = function(requestKey, expectedTimerToken)
    local pending = profileSyncResponseRuntime.precise.pendingPatchManifest[TrimText(requestKey)]
    if type(pending) ~= "table" then
      return 0
    end
    if expectedTimerToken ~= nil and math.max(0, tonumber(pending.timerToken) or 0) ~= math.max(0, tonumber(expectedTimerToken) or 0) then
      return 0
    end
    profileSyncResponseRuntime.precise.pendingPatchManifest[requestKey] = nil

    local activeSession, activeProfileName = GetActiveLootSession()
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    local resolvedSessionId = TrimText(pending.sessionId)
    local resolvedProfileName = TrimText(pending.profileName)
    local resolvedTarget = NormalizeCharacterKey(pending.target)
    if resolvedSessionId == ""
      or resolvedProfileName == ""
      or resolvedTarget == ""
      or not sessionRuntimeOps.doesSessionMatch(activeSession, activeProfileName, resolvedSessionId, resolvedProfileName)
      or not sessionRuntimeOps.isHostSender(activeSession, resolvedTarget)
      or selfKey == ""
      or not sessionRuntimeOps.isJoinedCharacter(activeSession, selfKey)
    then
      return 0
    end

    local resolvedSubdomains = type(FilterLootProfilePatchCapableSubdomains) == "function"
      and FilterLootProfilePatchCapableSubdomains(pending.subdomains)
      or CloneProfileSyncSubdomainList(pending.subdomains)
    if #resolvedSubdomains == 0 then
      return 0
    end

    local localProfileId = TrimText(select(1, GetLootProfileId(activeProfileName)) or "")
    if localProfileId == "" then
      return 0
    end
    local manifestData = type(snapshotTransferOps.exportPatchManifest) == "function"
      and snapshotTransferOps.exportPatchManifest(activeProfileName, resolvedSubdomains)
      or nil
    if type(manifestData) ~= "string" or manifestData == "" then
      return 0
    end

    local requestStamp = profileSyncLocalOps.buildPatchManifestRequestStamp(resolvedSessionId, resolvedTarget, resolvedSubdomains)
    local responseSignature = profileSyncLocalOps.buildProfilePatchManifestResponseSignature(localProfileId, manifestData)
    local now = GetNow()
    local recentState = profileSyncResponseRuntime.precise.recentPatchManifest[requestStamp]
    local shouldSuppressResponse = INTERNAL_API.LIDCOUNCIL_ShouldSuppressPreciseResponse_Impl
    if type(shouldSuppressResponse) == "function" and shouldSuppressResponse(
      recentState,
      responseSignature,
      pending.requestToken,
      now,
      profileSyncConfig.localProfileStateDedupeSeconds
    ) then
      return 0
    end

    local generatedResponseToken = string.format("PSP-%d-%d", tonumber(time and time() or 0) or 0, math.random(1000, 9999))
    local responseToken = generatedResponseToken
    local resolveResponseToken = INTERNAL_API.LIDCOUNCIL_ResolvePreciseResponseToken_Impl
    if type(resolveResponseToken) == "function" then
      responseToken = select(1, resolveResponseToken(
        recentState,
        responseSignature,
        pending.requestToken,
        "",
        generatedResponseToken
      ))
    end
    local sent, sentCount = SendProfileSubdomainPatchManifest(
      activeProfileName,
      resolvedSessionId,
      resolvedTarget,
      resolvedSubdomains,
      {
        manifestData = manifestData,
        profileId = localProfileId,
        requestToken = pending.requestToken,
        responseToken = responseToken,
      }
    )
    sentCount = math.max(0, tonumber(sentCount) or 0)
    if sent and sentCount > 0 then
      profileSyncResponseRuntime.precise.recentPatchManifest[requestStamp] = {
        signature = responseSignature,
        requestToken = TrimText(pending.requestToken),
        responseToken = responseToken,
        sentAt = now,
      }
      profileSyncLocalOps.emitPreciseProfileSyncSendNotice({
        sessionId = resolvedSessionId,
        profileName = activeProfileName,
        sender = resolvedTarget,
        kind = "patch_manifest",
      })
    end
    return sentCount
  end

  profileSyncLocalOps.estimateSnapshotTargetDelay = function(preparedSnapshot)
    local chunkCount = type(preparedSnapshot) == "table" and type(preparedSnapshot.chunks) == "table" and #preparedSnapshot.chunks or 0
    local transferKind = TrimText(type(preparedSnapshot) == "table" and preparedSnapshot.transferKind or "")
    local intervalSeconds = math.max(0, tonumber(type(deps.GetCommOutboundIntervalSeconds) == "function" and deps.GetCommOutboundIntervalSeconds() or 0.12) or 0.12)
    local outboundStatus = type(deps.GetCommOutboundQueueStatus) == "function" and deps.GetCommOutboundQueueStatus() or nil
    local queuePressure = #profileSyncSessionState.pendingSnapshotBatch + math.max(0, tonumber(type(outboundStatus) == "table" and outboundStatus.pending) or 0)
    local throttlePressure = type(outboundStatus) == "table"
      and math.max(0, tonumber(outboundStatus.throttledTotal) or 0) > math.max(0, tonumber(outboundStatus.sentTotal) or 0)
      or false
    local delayScale = queuePressure >= 16 and 1.55 or (queuePressure >= 8 and 1.25 or 1.0)
    if throttlePressure then
      delayScale = delayScale * 1.20
    end
    if transferKind == "ROWPATCHES" then
      return math.max(intervalSeconds, (((chunkCount * 0.35) + 1.00) * intervalSeconds) * delayScale)
    elseif transferKind == "PATCHES" then
      return math.max(intervalSeconds, (((chunkCount * 0.50) + 1.20) * intervalSeconds) * delayScale)
    elseif transferKind == "SUBDOMAINS" then
      return math.max(intervalSeconds, (((chunkCount * 0.75) + 1.60) * intervalSeconds) * delayScale)
    end
    return math.max(0, (((chunkCount + 2) * intervalSeconds) + intervalSeconds) * delayScale)
  end

  profileSyncLocalOps.getPreparedTransferPriority = function(preparedSnapshot, batchItem)
    local transferKind = TrimText(type(preparedSnapshot) == "table" and preparedSnapshot.transferKind or "")
    local opts = type(batchItem) == "table" and type(batchItem.opts) == "table" and batchItem.opts or {}
    local resolvedMode = string.upper(TrimText(opts.mode))
    local resolvedReason = string.lower(TrimText(opts.reason))
    local scopeSubdomains = type(preparedSnapshot) == "table" and preparedSnapshot.subdomains
      or type(opts.subdomains) == "table" and opts.subdomains
      or {}
    local transferLane = generationOps.NormalizeProfileTransferLane(TrimText(opts.reason), scopeSubdomains, transferKind)
    local transferKindOffset = 8
    if transferKind == "ROWPATCHES" then
      transferKindOffset = 0
    elseif transferKind == "PATCHES" then
      transferKindOffset = 1
    elseif transferKind == "SUBDOMAINS" then
      transferKindOffset = 3
    elseif transferKind == "DOMAINS" then
      transferKindOffset = 5
    elseif transferKind == "FULL" then
      transferKindOffset = 7
    end

    if resolvedMode == "BACKGROUND" then
      if transferLane == "archive" then
        return 60 + transferKindOffset
      elseif transferLane == "stats" then
        return 44 + transferKindOffset
      end
      return 28 + transferKindOffset
    end

    if string.find(resolvedReason, "bootstrap", 1, true) then
      if transferLane == "archive" then
        return 14 + transferKindOffset
      elseif transferLane == "stats" then
        return 10 + transferKindOffset
      end
      return 6 + transferKindOffset
    end

    if transferLane == "archive" then
      return 36 + transferKindOffset
    elseif transferLane == "stats" then
      return 22 + transferKindOffset
    end
    return 16 + transferKindOffset
  end

  profileSyncLocalOps.hasHigherPriorityOutboundYieldTraffic = function(outboundStatus)
    outboundStatus = type(outboundStatus) == "table" and outboundStatus or nil
    local nextPriority = math.max(0, tonumber(type(outboundStatus) == "table" and outboundStatus.nextPriority or 0) or 0)
    return nextPriority > 0 and nextPriority <= 5
  end

  profileSyncLocalOps.resolveSnapshotBatchAdmission = function(outboundStatus, transferPriority, overrides)
    outboundStatus = type(outboundStatus) == "table" and outboundStatus or {}
    overrides = type(overrides) == "table" and overrides or {}
    local pendingMessages = math.max(0, tonumber(outboundStatus.pending) or 0)
    local additionalMessages = math.max(0, tonumber(overrides.additionalMessages) or 0)
    local chatLockdownActive = outboundStatus.chatLockdownActive == true
    local pollSeconds = math.max(0.05, tonumber(overrides.pollSeconds)
      or tonumber(profileSyncConfig.snapshotAdmissionPollSeconds) or 0.50)
    if chatLockdownActive then
      return {
        admit = false,
        reason = "chat_lockdown",
        delaySeconds = math.max(1, pollSeconds),
        activeTransfers = 0,
        pendingMessages = pendingMessages,
        additionalMessages = additionalMessages,
        chatLockdownActive = true,
      }
    end
    local globalThrottleCooldownRemaining = math.max(0,
      tonumber(outboundStatus.globalThrottleCooldownRemaining) or 0)
    if globalThrottleCooldownRemaining > 0 then
      return {
        admit = false,
        reason = "global_throttle_cooldown",
        delaySeconds = math.max(pollSeconds, globalThrottleCooldownRemaining),
        activeTransfers = 0,
        pendingMessages = pendingMessages,
        additionalMessages = additionalMessages,
        globalThrottleCooldownRemaining = globalThrottleCooldownRemaining,
      }
    end
    local transferStatus = type(outboundStatus.profileTransferStatus) == "table"
      and outboundStatus.profileTransferStatus
      or {}
    local activeTransfers = math.max(0, tonumber(transferStatus.active) or 0)
    -- Waiting for a remote ACK/application no longer consumes outbound queue
    -- capacity. Count only transfers which are still being queued or sent so
    -- one offline or combat-locked joiner cannot block the rest of the raid.
    if type(outboundStatus.profileTransfers) == "table" then
      activeTransfers = 0
      for _, transfer in ipairs(outboundStatus.profileTransfers) do
        local transferState = TrimText(type(transfer) == "table" and transfer.state or "")
        if transferState == "queued" or transferState == "sending" then
          activeTransfers = activeTransfers + 1
        end
      end
    end
    local throttled = outboundStatus.currentThrottleActive == true
    local maxActiveTransfers = math.max(1, tonumber(overrides.maxActiveTransfers)
      or tonumber(profileSyncConfig.snapshotAdmissionMaxActiveTransfers) or 2)
    if throttled then
      maxActiveTransfers = math.min(maxActiveTransfers, math.max(1,
        tonumber(overrides.maxActiveTransfersWhileThrottled)
          or tonumber(profileSyncConfig.snapshotAdmissionMaxActiveTransfersWhileThrottled) or 1))
    end
    if math.max(0, tonumber(transferPriority) or 0) >= 28 then
      maxActiveTransfers = math.min(maxActiveTransfers, math.max(1,
        tonumber(overrides.maxBackgroundActiveTransfers)
          or tonumber(profileSyncConfig.snapshotAdmissionMaxBackgroundActiveTransfers) or 1))
    end
    local maxQueuedMessages = math.max(1, tonumber(overrides.maxQueuedMessages)
      or tonumber(profileSyncConfig.snapshotAdmissionMaxQueuedMessages) or 96)
    if throttled then
      maxQueuedMessages = math.min(maxQueuedMessages, math.max(1,
        tonumber(overrides.maxQueuedMessagesWhileThrottled)
          or tonumber(profileSyncConfig.snapshotAdmissionMaxQueuedMessagesWhileThrottled) or 48))
    end
    if activeTransfers >= maxActiveTransfers then
      return {
        admit = false,
        reason = throttled and "throttled_active_transfer_limit" or "active_transfer_limit",
        delaySeconds = pollSeconds,
        activeTransfers = activeTransfers,
        maxActiveTransfers = maxActiveTransfers,
        pendingMessages = pendingMessages,
        maxQueuedMessages = maxQueuedMessages,
      }
    end
    if pendingMessages >= maxQueuedMessages then
      return {
        admit = false,
        reason = throttled and "throttled_queue_limit" or "queue_limit",
        delaySeconds = pollSeconds,
        activeTransfers = activeTransfers,
        maxActiveTransfers = maxActiveTransfers,
        pendingMessages = pendingMessages,
        maxQueuedMessages = maxQueuedMessages,
      }
    end
    if pendingMessages > 0 and additionalMessages > 0
      and (pendingMessages + additionalMessages) > maxQueuedMessages
    then
      return {
        admit = false,
        reason = throttled and "throttled_projected_queue_limit" or "projected_queue_limit",
        delaySeconds = pollSeconds,
        activeTransfers = activeTransfers,
        maxActiveTransfers = maxActiveTransfers,
        pendingMessages = pendingMessages,
        additionalMessages = additionalMessages,
        maxQueuedMessages = maxQueuedMessages,
      }
    end
    return {
      admit = true,
      reason = "admitted",
      delaySeconds = 0,
      activeTransfers = activeTransfers,
      maxActiveTransfers = maxActiveTransfers,
      pendingMessages = pendingMessages,
      additionalMessages = additionalMessages,
      maxQueuedMessages = maxQueuedMessages,
    }
  end
  INTERNAL_API.LIDCOUNCIL_ResolveSnapshotBatchAdmission_Impl =
    profileSyncLocalOps.resolveSnapshotBatchAdmission

  profileSyncLocalOps.getHigherPriorityOutboundYieldTrafficCount = function(outboundStatus)
    outboundStatus = type(outboundStatus) == "table" and outboundStatus or nil
    local byPriority = type(outboundStatus) == "table" and type(outboundStatus.byPriority) == "table"
      and outboundStatus.byPriority
      or nil
    if type(byPriority) == "table" then
      local urgentCount = 0
      for priority = 1, 5 do
        urgentCount = urgentCount + math.max(0, tonumber(byPriority[tostring(priority)]) or 0)
      end
      return urgentCount
    end
    return profileSyncLocalOps.hasHigherPriorityOutboundYieldTraffic(outboundStatus) and 1 or 0
  end

  profileSyncLocalOps.getSnapshotBatchYieldRescheduleDelay = function(delay, transferPriority, outboundStatus)
    local resolvedDelay = math.max(0, tonumber(delay) or 0)
    local urgentCount = profileSyncLocalOps.getHigherPriorityOutboundYieldTrafficCount(outboundStatus)
    if urgentCount <= 0 then
      return resolvedDelay
    end

    local intervalSeconds = math.max(0, tonumber(type(deps.GetCommOutboundIntervalSeconds) == "function"
      and deps.GetCommOutboundIntervalSeconds()
      or 0.12) or 0.12)
    local yieldDelay = intervalSeconds * math.min(6, math.max(2, urgentCount + 1))
    transferPriority = math.max(0, tonumber(transferPriority) or 0)
    if transferPriority >= 28 then
      yieldDelay = yieldDelay * 1.50
    elseif transferPriority >= 16 then
      yieldDelay = yieldDelay * 1.20
    end
    return math.max(resolvedDelay, yieldDelay)
  end

  profileSyncLocalOps.canPreferSnapshotBatchSession = function(priority)
    priority = math.max(0, tonumber(priority) or 0)
    return priority > 0 and priority < 28
  end

  profileSyncLocalOps.setSnapshotBatchPreferredSession = function(sessionId, priority)
    local resolvedSessionId = TrimText(sessionId)
    if resolvedSessionId ~= "" and profileSyncLocalOps.canPreferSnapshotBatchSession(priority) then
      profileSyncSessionState.snapshotBatchPreferredSessionId = resolvedSessionId
      return
    end
    profileSyncSessionState.snapshotBatchPreferredSessionId = ""
  end

  profileSyncLocalOps.getSnapshotBatchSessionAffinityRank = function(item, priority, preferredSessionId)
    if TrimText(preferredSessionId) == "" or not profileSyncLocalOps.canPreferSnapshotBatchSession(priority) then
      return 1
    end
    return TrimText(type(item) == "table" and item.sessionId or "") == TrimText(preferredSessionId) and 0 or 1
  end

  profileSyncLocalOps.getPreparedTransferBurstLimit = function(preparedSnapshot, batchItem)
    local transferKind = TrimText(type(preparedSnapshot) == "table" and preparedSnapshot.transferKind or "")
    local chunkCount = type(preparedSnapshot) == "table" and type(preparedSnapshot.chunks) == "table" and #preparedSnapshot.chunks or 0
    local outboundStatus = type(deps.GetCommOutboundQueueStatus) == "function" and deps.GetCommOutboundQueueStatus() or nil
    local queuePressure = #profileSyncSessionState.pendingSnapshotBatch + math.max(0, tonumber(type(outboundStatus) == "table" and outboundStatus.pending) or 0)
    local burstLimit
    if transferKind == "ROWPATCHES" then
      burstLimit = chunkCount <= 3 and 4 or 2
    elseif transferKind == "PATCHES" then
      burstLimit = chunkCount <= 4 and 3 or 2
    elseif transferKind == "SUBDOMAINS" and chunkCount <= 3 then
      burstLimit = 2
    else
      burstLimit = 1
    end
    if profileSyncLocalOps.hasHigherPriorityOutboundYieldTraffic(outboundStatus) then
      return 1
    end
    if queuePressure >= 18 then
      return 1
    elseif queuePressure >= 10 then
      return math.max(1, burstLimit - 1)
    elseif queuePressure <= 2 and transferKind == "ROWPATCHES" and chunkCount <= 2 then
      return burstLimit + 1
    end
    return burstLimit
  end

  profileSyncLocalOps.buildPreparedTransferScopeDescriptor = function(preparedSnapshot, batchItem)
    local descriptor = {
      profileName = "",
      transferKind = "",
      domains = {},
      subdomains = {},
      full = false,
    }
    if type(preparedSnapshot) == "table" then
      descriptor.profileName = TrimText(preparedSnapshot.profileName)
      descriptor.transferKind = TrimText(preparedSnapshot.transferKind)
      descriptor.domains = CloneProfileSyncDomainList(preparedSnapshot.domains)
      descriptor.subdomains = CloneProfileSyncSubdomainList(preparedSnapshot.subdomains)
      descriptor.full = descriptor.transferKind == "FULL"
    end
    if descriptor.profileName == "" and type(batchItem) == "table" then
      descriptor.profileName = TrimText(batchItem.profileName or "")
    end
    local opts = type(batchItem) == "table" and type(batchItem.opts) == "table" and batchItem.opts or nil
    if #descriptor.domains == 0 and type(opts) == "table" then
      descriptor.domains = ResolveProfileRevisionDomainList(opts.domains)
    end
    if #descriptor.subdomains == 0 and type(opts) == "table" then
      descriptor.subdomains = NormalizeRequestedProfileSyncSubdomains(opts.subdomains, descriptor.domains)
    end
    if descriptor.transferKind == "" then
      if #descriptor.subdomains > 0 then
        descriptor.transferKind = "SUBDOMAINS"
      elseif #descriptor.domains > 0 then
        descriptor.transferKind = "DOMAINS"
      else
        descriptor.transferKind = "FULL"
        descriptor.full = true
      end
    end
    if descriptor.transferKind == "FULL" then
      descriptor.full = true
    end
    return descriptor
  end

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

  profileSyncLocalOps.isScopeListSubset = function(left, right)
    local leftLookup = profileSyncLocalOps.buildScopeLookup(left)
    local rightLookup = profileSyncLocalOps.buildScopeLookup(right)
    local count = 0
    for key in pairs(leftLookup) do
      count = count + 1
      if not rightLookup[key] then
        return false
      end
    end
    return count > 0
  end

  profileSyncLocalOps.areScopeListsEqual = function(left, right)
    return profileSyncLocalOps.isScopeListSubset(left, right) and profileSyncLocalOps.isScopeListSubset(right, left)
  end

  -- A matching archive transfer already in the outbound queue will deliver the same data.
  profileSyncLocalOps.isMatchingArchiveInFlightProfileTransfer = function(preparedSnapshot, sessionId, target, opts, transfer)
    opts = type(opts) == "table" and opts or {}
    transfer = type(transfer) == "table" and transfer or {}
    if string.upper(TrimText(opts.mode)) ~= "BACKGROUND" then
      return false
    end
    local transferState = string.lower(TrimText(transfer.state))
    if transferState ~= "queued" and transferState ~= "sending" then
      return false
    end
    if string.upper(TrimText(type(preparedSnapshot) == "table" and preparedSnapshot.authoritativeArchiveScope or ""))
      ~= string.upper(TrimText(transfer.authoritativeArchiveScope))
    then
      return false
    end
    local incomingScope = profileSyncLocalOps.buildPreparedTransferScopeDescriptor(preparedSnapshot, {
      sessionId = sessionId,
      target = target,
      opts = opts,
    })
    local outgoingScope = profileSyncLocalOps.buildPreparedTransferScopeDescriptor({
      profileName = transfer.profileName,
      transferKind = transfer.transferKind,
      domains = type(transfer.scopeDomains) == "table" and transfer.scopeDomains or {},
      subdomains = type(transfer.scopeSubdomains) == "table" and transfer.scopeSubdomains or {},
    }, {
      sessionId = transfer.sessionId,
      target = transfer.target,
      opts = {
        domains = type(transfer.scopeDomains) == "table" and transfer.scopeDomains or {},
        subdomains = type(transfer.scopeSubdomains) == "table" and transfer.scopeSubdomains or {},
      },
    })
    local incomingLane = generationOps.NormalizeProfileTransferLane(
      TrimText(opts.reason),
      incomingScope.subdomains,
      incomingScope.transferKind
    )
    local outgoingLane = TrimText(transfer.lane)
    if outgoingLane == "" then
      outgoingLane = generationOps.NormalizeProfileTransferLane(
        TrimText(transfer.reason),
        outgoingScope.subdomains,
        outgoingScope.transferKind
      )
    end
    if incomingLane ~= "archive" or string.lower(outgoingLane) ~= "archive" then
      return false
    end
    if NormalizeCharacterKey(target) ~= NormalizeCharacterKey(transfer.target)
      or TrimText(sessionId) ~= TrimText(transfer.sessionId)
      or string.upper(TrimText(transfer.mode)) ~= "BACKGROUND"
      or incomingScope.profileName == ""
      or string.lower(incomingScope.profileName) ~= string.lower(outgoingScope.profileName)
      or incomingScope.transferKind ~= outgoingScope.transferKind
      or incomingScope.full ~= outgoingScope.full
    then
      return false
    end
    if incomingScope.full then
      return true
    end
    if #incomingScope.subdomains > 0 or #outgoingScope.subdomains > 0 then
      return #incomingScope.subdomains > 0
        and #outgoingScope.subdomains > 0
        and profileSyncLocalOps.areScopeListsEqual(incomingScope.subdomains, outgoingScope.subdomains)
    end
    return #incomingScope.domains > 0
      and #outgoingScope.domains > 0
      and profileSyncLocalOps.areScopeListsEqual(incomingScope.domains, outgoingScope.domains)
  end

  INTERNAL_API.LIDCOUNCIL_IsMatchingArchiveInFlightProfileTransfer_Impl = function(incoming, transfer)
    incoming = type(incoming) == "table" and incoming or {}
    return profileSyncLocalOps.isMatchingArchiveInFlightProfileTransfer(
      incoming.preparedSnapshot,
      incoming.sessionId,
      incoming.target,
      incoming.opts,
      transfer
    )
  end

  profileSyncLocalOps.clonePendingSnapshotBatchOptions = function(opts)
    local cloned = {}
    for key, value in pairs(type(opts) == "table" and opts or {}) do
      cloned[key] = value
    end
    if type(cloned.domains) == "table" then
      cloned.domains = CloneProfileSyncDomainList(cloned.domains)
    end
    if type(cloned.subdomains) == "table" then
      cloned.subdomains = CloneProfileSyncSubdomainList(cloned.subdomains)
    end
    cloned.preparedSnapshot = nil
    return cloned
  end

  profileSyncLocalOps.mergeProfileSyncTextLists = function(...)
    local merged = {}
    for index = 1, select("#", ...) do
      local values = select(index, ...)
      if type(values) == "table" then
        for _, value in ipairs(values) do
          merged[#merged + 1] = value
        end
      end
    end
    return CloneProfileSyncTextList(merged)
  end

  profileSyncLocalOps.getPendingSnapshotBatchDeliverySignature = function(item)
    local opts = type(item) == "table" and type(item.opts) == "table" and item.opts or {}
    return string.upper(TrimText(opts.mode)),
      TrimText(opts.reason)
  end

  profileSyncLocalOps.canExactCoalescePendingSnapshotBatchModes = function(existingMode, incomingMode)
    local resolvedExistingMode = string.upper(TrimText(existingMode))
    local resolvedIncomingMode = string.upper(TrimText(incomingMode))
    if resolvedExistingMode == "" or resolvedIncomingMode == "" then
      return false
    end
    if resolvedExistingMode == resolvedIncomingMode then
      return true
    end
    return (resolvedExistingMode == "LIVE" and resolvedIncomingMode == "BACKGROUND")
      or (resolvedExistingMode == "BACKGROUND" and resolvedIncomingMode == "LIVE")
  end

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

  profileSyncLocalOps.buildPreparedSnapshotPatchManifestSignature = function(manifestSummary)
    manifestSummary = type(manifestSummary) == "table" and manifestSummary or {}
    return table.concat({
      TrimText(manifestSummary.profileId),
      EncodeProfileRevisionDomains(type(manifestSummary.scopeDomains) == "table" and manifestSummary.scopeDomains or {}),
      table.concat(
        CloneProfileSyncSubdomainList(type(manifestSummary.scopeSubdomains) == "table" and manifestSummary.scopeSubdomains or {}),
        "\30"
      ),
    }, "\31")
  end

  profileSyncLocalOps.buildPendingSnapshotBatchExactSignature = function(item, options)
    options = type(options) == "table" and options or {}
    local preparedSnapshot = type(item) == "table" and type(item.preparedSnapshot) == "table" and item.preparedSnapshot or nil
    local itemOpts = type(item) == "table" and type(item.opts) == "table" and item.opts or {}
    if type(preparedSnapshot) ~= "table" then
      return ""
    end
    local signatureParts = {
      TrimText(type(item) == "table" and item.sessionId or ""),
      NormalizeCharacterKey(type(item) == "table" and item.target or ""),
      TrimText(preparedSnapshot.profileName),
      TrimText(preparedSnapshot.profileId),
      TrimText(preparedSnapshot.transferKind),
      EncodeProfileRevisionDomains(type(preparedSnapshot.domains) == "table" and preparedSnapshot.domains or {}),
      table.concat(CloneProfileSyncSubdomainList(type(preparedSnapshot.subdomains) == "table" and preparedSnapshot.subdomains or {}), "\30"),
      TrimText(preparedSnapshot.requestedScope),
      EncodeProfileRevisionDomains(type(preparedSnapshot.requestedDomains) == "table" and preparedSnapshot.requestedDomains or {}),
      table.concat(CloneProfileSyncSubdomainList(type(preparedSnapshot.requestedSubdomains) == "table" and preparedSnapshot.requestedSubdomains or {}), "\30"),
      preparedSnapshot.scopeEscalated == true and "1" or "0",
      preparedSnapshot.fullSnapshotFallback == true and "1" or "0",
      TrimText(preparedSnapshot.fallbackEscalation),
      table.concat(CloneProfileSyncTextList(type(preparedSnapshot.fallbackReasons) == "table" and preparedSnapshot.fallbackReasons or {}), "\30"),
      profileSyncLocalOps.buildPreparedSnapshotPatchManifestSignature(preparedSnapshot.patchManifestSummary),
      profileSyncLocalOps.buildPreparedSnapshotChunkSignature(preparedSnapshot.chunks),
    }
    if options.includeMode ~= false then
      table.insert(signatureParts, 3, string.upper(TrimText(itemOpts.mode)))
    end
    return table.concat(signatureParts, "\31")
  end

  profileSyncLocalOps.selectPreferredPendingSnapshotBatchItem = function(existingItem, incomingItem)
    local existingPriority = math.max(0, tonumber(profileSyncLocalOps.getPreparedTransferPriority(
      type(existingItem) == "table" and existingItem.preparedSnapshot or nil,
      existingItem
    )) or 0)
    local incomingPriority = math.max(0, tonumber(profileSyncLocalOps.getPreparedTransferPriority(
      type(incomingItem) == "table" and incomingItem.preparedSnapshot or nil,
      incomingItem
    )) or 0)
    if incomingPriority < existingPriority then
      return incomingItem
    elseif existingPriority < incomingPriority then
      return existingItem
    end

    local existingChunkCount = type(existingItem) == "table"
      and type(existingItem.preparedSnapshot) == "table"
      and type(existingItem.preparedSnapshot.chunks) == "table"
      and #existingItem.preparedSnapshot.chunks
      or math.huge
    local incomingChunkCount = type(incomingItem) == "table"
      and type(incomingItem.preparedSnapshot) == "table"
      and type(incomingItem.preparedSnapshot.chunks) == "table"
      and #incomingItem.preparedSnapshot.chunks
      or math.huge
    if incomingChunkCount < existingChunkCount then
      return incomingItem
    end
    return existingItem
  end

  profileSyncLocalOps.buildCoalescedPendingSnapshotBatchItem = function(existingItem, incomingItem)
    if type(existingItem) ~= "table" or type(incomingItem) ~= "table" then
      return nil, nil
    end
    if NormalizeCharacterKey(existingItem.target) ~= NormalizeCharacterKey(incomingItem.target) then
      return nil, nil
    end
    if TrimText(existingItem.sessionId) ~= TrimText(incomingItem.sessionId) then
      return nil, nil
    end

    local existingMode, existingReason = profileSyncLocalOps.getPendingSnapshotBatchDeliverySignature(existingItem)
    local incomingMode, incomingReason = profileSyncLocalOps.getPendingSnapshotBatchDeliverySignature(incomingItem)
    if profileSyncLocalOps.canExactCoalescePendingSnapshotBatchModes(existingMode, incomingMode) then
      local existingExactSignature = profileSyncLocalOps.buildPendingSnapshotBatchExactSignature(existingItem, {
        includeMode = false,
      })
      local incomingExactSignature = profileSyncLocalOps.buildPendingSnapshotBatchExactSignature(incomingItem, {
        includeMode = false,
      })
      if existingExactSignature ~= "" and existingExactSignature == incomingExactSignature then
        return profileSyncLocalOps.selectPreferredPendingSnapshotBatchItem(existingItem, incomingItem), "exact_duplicate"
      end
    end
    if existingMode ~= incomingMode or existingReason ~= incomingReason then
      return nil, nil
    end

    local existingScope = profileSyncLocalOps.buildPreparedTransferScopeDescriptor(existingItem.preparedSnapshot, existingItem)
    local incomingScope = profileSyncLocalOps.buildPreparedTransferScopeDescriptor(incomingItem.preparedSnapshot, incomingItem)
    if existingScope.profileName ~= "" and incomingScope.profileName ~= ""
      and string.lower(existingScope.profileName) ~= string.lower(incomingScope.profileName)
    then
      return nil, nil
    end
    if existingScope.transferKind ~= incomingScope.transferKind
      or existingScope.transferKind == "FULL"
      or existingScope.transferKind == "ROWPATCHES"
    then
      return nil, nil
    end

    local mergedProfileName = FirstNonEmptyText(
      existingScope.profileName,
      incomingScope.profileName,
      TrimText(existingItem.profileName),
      TrimText(incomingItem.profileName)
    )
    if mergedProfileName == "" then
      return nil, nil
    end

    local mergedSessionId = TrimText(existingItem.sessionId)
    local mergedTarget = NormalizeCharacterKey(existingItem.target)
    local mergedOpts = profileSyncLocalOps.clonePendingSnapshotBatchOptions(existingItem.opts)
    local incomingOpts = profileSyncLocalOps.clonePendingSnapshotBatchOptions(incomingItem.opts)
    if TrimText(mergedOpts.mode) == "" then
      mergedOpts.mode = TrimText(incomingOpts.mode)
    end
    if TrimText(mergedOpts.reason) == "" then
      mergedOpts.reason = TrimText(incomingOpts.reason)
    end
    mergedOpts.rowSelectionsBySubdomain = nil
    mergedOpts.rowMapsBySubdomain = nil
    mergedOpts.prebuiltRowsBySubdomain = nil

    local mergedPreparedSnapshot = nil
    if existingScope.transferKind == "PATCHES" or existingScope.transferKind == "SUBDOMAINS" then
      if #existingScope.subdomains == 0 or #incomingScope.subdomains == 0 then
        return nil, nil
      end
      local mergedSubdomains = NormalizeProfileSyncSubdomainList(
        profileSyncLocalOps.mergeProfileSyncTextLists(existingScope.subdomains, incomingScope.subdomains),
        MergeProfileRevisionDomains(existingScope.domains, incomingScope.domains)
      )
      if #mergedSubdomains == 0 then
        return nil, nil
      end
      local mergedDomains = type(ResolveLootProfileDomainsForSubdomains) == "function"
        and ResolveLootProfileDomainsForSubdomains(mergedSubdomains)
        or MergeProfileRevisionDomains(existingScope.domains, incomingScope.domains)
      mergedOpts.domains = CloneProfileSyncDomainList(mergedDomains)
      mergedOpts.subdomains = CloneProfileSyncSubdomainList(mergedSubdomains)
      if existingScope.transferKind == "PATCHES" then
        if not profileSyncLocalOps.hasLoadedPatchManifestSubdomains(mergedSessionId, mergedTarget, mergedSubdomains) then
          return nil, nil
        end
        mergedOpts.patchManifest = GetMemberPatchManifestState(mergedSessionId, mergedTarget)
        if type(mergedOpts.patchManifest) ~= "table" then
          return nil, nil
        end
      else
        mergedOpts.patchManifest = nil
      end
      mergedPreparedSnapshot = profileSyncLocalOps.prepareProfileSnapshotTransfer(mergedProfileName, mergedOpts)
      if type(mergedPreparedSnapshot) ~= "table" or TrimText(mergedPreparedSnapshot.transferKind) ~= existingScope.transferKind then
        return nil, nil
      end
    elseif existingScope.transferKind == "DOMAINS" then
      if #existingScope.subdomains > 0 or #incomingScope.subdomains > 0 then
        return nil, nil
      end
      local mergedDomains = MergeProfileRevisionDomains(existingScope.domains, incomingScope.domains)
      mergedOpts.domains = CloneProfileSyncDomainList(mergedDomains)
      mergedOpts.subdomains = nil
      mergedOpts.patchManifest = nil
      mergedPreparedSnapshot = profileSyncLocalOps.prepareProfileSnapshotTransfer(mergedProfileName, mergedOpts)
      if type(mergedPreparedSnapshot) ~= "table" or TrimText(mergedPreparedSnapshot.transferKind) ~= "DOMAINS" then
        return nil, nil
      end
    else
      return nil, nil
    end

    mergedOpts.preparedSnapshot = mergedPreparedSnapshot
    return {
      profileName = mergedProfileName,
      preparedSnapshot = mergedPreparedSnapshot,
      sessionId = mergedSessionId,
      target = mergedTarget,
      opts = mergedOpts,
    }, "scope_merge"
  end

  profileSyncLocalOps.shouldReplacePendingSnapshotBatchItem = function(existingItem, replacementItem)
    if type(existingItem) ~= "table" or type(replacementItem) ~= "table" then
      return false
    end
    if NormalizeCharacterKey(existingItem.target) ~= NormalizeCharacterKey(replacementItem.target) then
      return false
    end
    if TrimText(existingItem.sessionId) ~= TrimText(replacementItem.sessionId) then
      return false
    end

    local existingScope = profileSyncLocalOps.buildPreparedTransferScopeDescriptor(existingItem.preparedSnapshot, existingItem)
    local replacementScope = profileSyncLocalOps.buildPreparedTransferScopeDescriptor(replacementItem.preparedSnapshot, replacementItem)
    local existingPriority = profileSyncLocalOps.getPreparedTransferPriority(existingItem.preparedSnapshot, existingItem)
    local replacementPriority = profileSyncLocalOps.getPreparedTransferPriority(replacementItem.preparedSnapshot, replacementItem)
    if existingScope.profileName ~= "" and replacementScope.profileName ~= ""
      and string.lower(existingScope.profileName) ~= string.lower(replacementScope.profileName) then
      return false
    end

    if replacementScope.full then
      return existingScope.full and replacementPriority <= existingPriority
    end
    if existingScope.full then
      return replacementScope.full and replacementPriority <= existingPriority
    end

    if #existingScope.subdomains > 0 or #replacementScope.subdomains > 0 then
      if #existingScope.subdomains == 0 or #replacementScope.subdomains == 0 then
        return false
      end
      return profileSyncLocalOps.areScopeListsEqual(existingScope.subdomains, replacementScope.subdomains)
        and replacementPriority <= existingPriority
    end

    return profileSyncLocalOps.areScopeListsEqual(existingScope.domains, replacementScope.domains)
      and replacementPriority <= existingPriority
  end

  profileSyncLocalOps.insertPendingSnapshotBatchItem = function(item)
    local mergedCount = 0
    local exactDuplicateCount = 0
    local coalescedItem = item
    local coalescedBatch = {}
    for _, existing in ipairs(profileSyncSessionState.pendingSnapshotBatch) do
      local mergedItem, mergeKind = profileSyncLocalOps.buildCoalescedPendingSnapshotBatchItem(existing, coalescedItem)
      if mergedItem then
        coalescedItem = mergedItem
        mergedCount = mergedCount + 1
        if TrimText(mergeKind) == "exact_duplicate" then
          exactDuplicateCount = exactDuplicateCount + 1
        end
      else
        coalescedBatch[#coalescedBatch + 1] = existing
      end
    end
    profileSyncSessionState.pendingSnapshotBatch = coalescedBatch
    item = coalescedItem

    local filteredBatch = {}
    for _, existing in ipairs(profileSyncSessionState.pendingSnapshotBatch) do
      if not profileSyncLocalOps.shouldReplacePendingSnapshotBatchItem(existing, item) then
        filteredBatch[#filteredBatch + 1] = existing
      end
    end
    profileSyncSessionState.pendingSnapshotBatch = filteredBatch

    local priority = profileSyncLocalOps.getPreparedTransferPriority(type(item) == "table" and item.preparedSnapshot or nil, item)
    local chunkCount = type(item) == "table" and type(item.preparedSnapshot) == "table" and type(item.preparedSnapshot.chunks) == "table"
      and #item.preparedSnapshot.chunks
      or math.huge
    local preferredSessionId = TrimText(profileSyncSessionState.snapshotBatchPreferredSessionId)
    local sessionAffinityRank = profileSyncLocalOps.getSnapshotBatchSessionAffinityRank(item, priority, preferredSessionId)
    local insertAt = #profileSyncSessionState.pendingSnapshotBatch + 1
    for index, existing in ipairs(profileSyncSessionState.pendingSnapshotBatch) do
      local existingPriority = profileSyncLocalOps.getPreparedTransferPriority(type(existing) == "table" and existing.preparedSnapshot or nil, existing)
      local existingSessionAffinityRank = profileSyncLocalOps.getSnapshotBatchSessionAffinityRank(existing, existingPriority, preferredSessionId)
      local existingChunkCount = type(existing) == "table" and type(existing.preparedSnapshot) == "table" and type(existing.preparedSnapshot.chunks) == "table"
        and #existing.preparedSnapshot.chunks
        or math.huge
      if existingPriority > priority
        or (existingPriority == priority and existingSessionAffinityRank > sessionAffinityRank)
        or (existingPriority == priority and existingSessionAffinityRank == sessionAffinityRank and existingChunkCount > chunkCount)
      then
        insertAt = index
        break
      end
    end
    table.insert(profileSyncSessionState.pendingSnapshotBatch, insertAt, item)
    return mergedCount, exactDuplicateCount
  end

  profileSyncLocalOps.getSnapshotBatchHoldDelay = function(item)
    local sessionId = TrimText(type(item) == "table" and item.sessionId or "")
    if sessionId == "" then
      return 0
    end
    local holdUntil = tonumber(profileSyncSessionState.snapshotBatchJoinHoldUntilBySession[sessionId]) or 0
    local now = GetNow()
    if holdUntil <= now then
      profileSyncSessionState.snapshotBatchJoinHoldUntilBySession[sessionId] = nil
      profileSyncSessionState.snapshotBatchJoinHoldReasonBySession[sessionId] = nil
      return 0
    end
    return math.max(0.1, holdUntil - now)
  end

  local RunNextSnapshotBatchItem

  profileSyncLocalOps.resolvePendingBatchPreparedSnapshot = function(batchItem)
    local preparedSnapshot = type(batchItem) == "table" and batchItem.preparedSnapshot or nil
    if not preparedSnapshot and TrimText(type(batchItem) == "table" and batchItem.profileName or "") ~= "" then
      preparedSnapshot = select(1, profileSyncLocalOps.prepareProfileSnapshotTransfer(batchItem.profileName, batchItem.opts))
    end
    return preparedSnapshot
  end

  profileSyncLocalOps.findNextRunnableSnapshotBatchItem = function()
    local selectedIndex = nil
    local selectedPriority = 0
    local preferredIndex = nil
    local preferredPriority = 0
    local nextHoldDelay = nil
    local preferredSessionId = TrimText(profileSyncSessionState.snapshotBatchPreferredSessionId)

    for index, candidate in ipairs(profileSyncSessionState.pendingSnapshotBatch) do
      if type(candidate) == "table" then
        local holdDelay = profileSyncLocalOps.getSnapshotBatchHoldDelay(candidate)
        if holdDelay > 0 then
          nextHoldDelay = nextHoldDelay and math.min(nextHoldDelay, holdDelay) or holdDelay
        elseif not profileSyncLocalOps.isSnapshotBatchItemArchivePaused(candidate) then
          local candidatePriority = math.max(0, tonumber(profileSyncLocalOps.getPreparedTransferPriority(
            type(candidate.preparedSnapshot) == "table" and candidate.preparedSnapshot or nil,
            candidate
          )) or 0)
          if not selectedIndex then
            selectedIndex = index
            selectedPriority = candidatePriority
          end
          if preferredSessionId ~= ""
            and TrimText(candidate.sessionId) == preferredSessionId
            and profileSyncLocalOps.canPreferSnapshotBatchSession(candidatePriority)
          then
            preferredIndex = index
            preferredPriority = candidatePriority
            if selectedIndex and candidatePriority == selectedPriority then
              break
            end
          end
        end
      end
    end

    if preferredIndex and selectedIndex and preferredIndex ~= selectedIndex then
      if preferredPriority < selectedPriority
        or (preferredPriority == selectedPriority and selectedPriority < 28)
      then
        selectedIndex = preferredIndex
        selectedPriority = preferredPriority
      end
    end

    return selectedIndex, selectedPriority, nextHoldDelay
  end

  profileSyncLocalOps.scheduleNextSnapshotBatchItem = function(delay)
    local resolvedDelay = math.max(0, tonumber(delay) or 0)
    profileSyncSessionState.snapshotBatchTimerToken = profileSyncSessionState.snapshotBatchTimerToken + 1
    local token = profileSyncSessionState.snapshotBatchTimerToken
    if type(Compat) == "table" and type(Compat.After) == "function" then
      Compat.After(resolvedDelay, function()
        if token ~= profileSyncSessionState.snapshotBatchTimerToken then
          return
        end
        RunNextSnapshotBatchItem()
      end)
    else
      RunNextSnapshotBatchItem()
    end
  end

  local function DelayProfileSnapshotBatchForJoins(sessionId, seconds, reason, profileName)
    local resolvedSessionId = TrimText(sessionId)
    if resolvedSessionId == "" then
      return false, 0
    end
    local delaySeconds = math.max(0, tonumber(seconds) or 0)
    if delaySeconds <= 0 then
      return false, 0
    end
    local holdUntil = GetNow() + delaySeconds
    profileSyncSessionState.snapshotBatchJoinHoldUntilBySession[resolvedSessionId] = math.max(
      tonumber(profileSyncSessionState.snapshotBatchJoinHoldUntilBySession[resolvedSessionId]) or 0,
      holdUntil
    )
    profileSyncSessionState.snapshotBatchJoinHoldReasonBySession[resolvedSessionId] = FirstNonEmptyText(
      TrimText(reason),
      profileSyncSessionState.snapshotBatchJoinHoldReasonBySession[resolvedSessionId],
      "roster_settling"
    )
    if #profileSyncSessionState.pendingSnapshotBatch > 0 and not profileSyncSessionState.snapshotBatchRunning then
      profileSyncSessionState.snapshotBatchRunning = true
      profileSyncLocalOps.scheduleNextSnapshotBatchItem(delaySeconds)
    end
    local stateProfileName = TrimText(profileName)
    if stateProfileName == "" then
      for _, item in ipairs(profileSyncSessionState.pendingSnapshotBatch) do
        if TrimText(type(item) == "table" and item.sessionId or "") == resolvedSessionId then
          stateProfileName = TrimText(item.profileName or (type(item.preparedSnapshot) == "table" and item.preparedSnapshot.profileName) or "")
          break
        end
      end
    end
    SetProfileSyncRuntimeState(resolvedSessionId, stateProfileName, "join_grace", "info",
      "Profile snapshot sync is waiting briefly for more raid members to join before sending the next profile copy.", {
        sender = TrimText(reason),
        skipIfSame = true,
        refreshEditor = false,
    })
    return true, math.max(0, profileSyncSessionState.snapshotBatchJoinHoldUntilBySession[resolvedSessionId] - GetNow())
  end

  profileSyncLocalOps.getProfileSnapshotBatchStatus = function()
    local statusNow = GetNow()
    local pendingIncomingTransfers = profileSyncLocalOps.pruneIncomingProfileSyncs(statusNow)
    local _, preparedArchiveRepairCacheEntries = profileSyncLocalOps.prunePreparedArchiveRepairCache(statusNow)
    local preparedSnapshotCacheEntries = profileSyncLocalOps.prunePreparedSnapshotCache(statusNow)
    local incomingSnapshotBytes = 0
    local oldestIncomingTransferAge = 0
    local longestIncomingTransferIdleSeconds = 0
    local latestIncomingTransfer = nil
    local latestIncomingTransferAt = 0
    for _, syncState in pairs(profileSyncSessionState.pendingProfileSyncs) do
      if type(syncState) == "table" then
        local updatedAt = math.max(0, tonumber(syncState.updatedAt or syncState.startedAt) or 0)
        incomingSnapshotBytes = incomingSnapshotBytes + math.max(0, tonumber(syncState.receivedBytes) or 0)
        oldestIncomingTransferAge = math.max(
          oldestIncomingTransferAge,
          math.max(0, statusNow - math.max(0, tonumber(syncState.startedAt) or 0))
        )
        longestIncomingTransferIdleSeconds = math.max(
          longestIncomingTransferIdleSeconds,
          math.max(0, statusNow - updatedAt)
        )
        if not latestIncomingTransfer or updatedAt >= latestIncomingTransferAt then
          latestIncomingTransferAt = updatedAt
          latestIncomingTransfer = {
            sender = NormalizeCharacterKey(syncState.sender),
            sessionId = TrimText(syncState.sessionId),
            mode = string.upper(TrimText(syncState.mode)),
            lane = string.lower(TrimText(syncState.lane)),
            transferKind = string.upper(TrimText(syncState.transferKind)),
            scopeDomains = CloneProfileSyncDomainList(syncState.scopeDomains),
            scopeSubdomains = CloneProfileSyncSubdomainList(syncState.scopeSubdomains),
            liveSync = syncState.liveSync == true,
            chunkCount = math.max(0, tonumber(syncState.chunkCount) or 0),
            receivedChunkCount = math.max(0, tonumber(syncState.receivedChunkCount) or 0),
          }
        end
      end
    end
    local incomingSnapshotHealth = INTERNAL_API.LIDCOUNCIL_GetIncomingProfileSyncHealth_Impl(
      pendingIncomingTransfers,
      longestIncomingTransferIdleSeconds,
      profileSyncConfig.incomingSnapshotStallSeconds
    )
    local cleanupHistory = {}
    for _, cleanup in ipairs(type(profileSyncSessionState.incomingSnapshotCleanupHistory) == "table"
      and profileSyncSessionState.incomingSnapshotCleanupHistory or {}) do
      if type(cleanup) == "table" then
        cleanupHistory[#cleanupHistory + 1] = {
          sessionId = TrimText(cleanup.sessionId),
          count = math.max(0, tonumber(cleanup.count) or 0),
          at = math.max(0, tonumber(cleanup.at) or 0),
        }
      end
    end
    local rejectCounts = {}
    for reason, count in pairs(type(profileSyncSessionState.incomingSnapshotRejectCounts) == "table"
      and profileSyncSessionState.incomingSnapshotRejectCounts or {}) do
      local resolvedReason = TrimText(reason)
      if resolvedReason ~= "" then
        rejectCounts[resolvedReason] = math.max(0, tonumber(count) or 0)
      end
    end
    local rejectHistory = {}
    for _, reject in ipairs(type(profileSyncSessionState.incomingSnapshotRejectHistory) == "table"
      and profileSyncSessionState.incomingSnapshotRejectHistory or {}) do
      if type(reject) == "table" then
        rejectHistory[#rejectHistory + 1] = {
          opcode = TrimText(reject.opcode),
          reason = TrimText(reject.reason),
          sender = NormalizeCharacterKey(reject.sender),
          transferId = TrimText(reject.transferId),
          sessionId = TrimText(reject.sessionId),
          at = math.max(0, tonumber(reject.at) or 0),
        }
      end
    end
    local firstItem = profileSyncSessionState.pendingSnapshotBatch[1]
    local selectedIndex = nil
    local nextRunnable = nil
    local pausedTargets = 0
    for _, item in ipairs(profileSyncSessionState.pendingSnapshotBatch) do
      if type(item) == "table" then
        if profileSyncLocalOps.isSnapshotBatchItemArchivePaused(item) then
          pausedTargets = pausedTargets + 1
        end
      end
    end
    selectedIndex = select(1, profileSyncLocalOps.findNextRunnableSnapshotBatchItem())
    if selectedIndex then
      nextRunnable = profileSyncSessionState.pendingSnapshotBatch[selectedIndex]
    end
    local holdRemaining = 0
    local heldSessionId = ""
    if type(firstItem) == "table" then
      heldSessionId = TrimText(firstItem.sessionId)
      holdRemaining = profileSyncLocalOps.getSnapshotBatchHoldDelay(firstItem)
    end
    local firstQueuedPreparedSnapshot = type(firstItem) == "table" and firstItem.preparedSnapshot or nil
    local firstQueuedPriority = type(firstItem) == "table"
      and math.max(0, tonumber(profileSyncLocalOps.getPreparedTransferPriority(firstQueuedPreparedSnapshot, firstItem)) or 0)
      or 0
    local nextPreparedSnapshot = type(nextRunnable) == "table" and nextRunnable.preparedSnapshot or firstQueuedPreparedSnapshot
    local pendingItems = {}
    for _, item in ipairs(profileSyncSessionState.pendingSnapshotBatch) do
      if type(item) == "table" and #pendingItems < 40 then
        local itemSessionId = TrimText(item.sessionId)
        local itemTarget = NormalizeCharacterKey(item.target)
        if itemSessionId ~= "" and itemTarget ~= "" then
          local itemPreparedSnapshot = item.preparedSnapshot
          pendingItems[#pendingItems + 1] = {
            sessionId = itemSessionId,
            target = itemTarget,
            priority = math.max(0, tonumber(profileSyncLocalOps.getPreparedTransferPriority(itemPreparedSnapshot, item)) or 0),
            transferKind = TrimText(type(itemPreparedSnapshot) == "table" and itemPreparedSnapshot.transferKind or ""),
            mode = TrimText(item.mode or (type(item.opts) == "table" and item.opts.mode) or ""),
            reason = TrimText(item.reason or (type(item.opts) == "table" and item.opts.reason) or ""),
            lane = TrimText(type(itemPreparedSnapshot) == "table" and itemPreparedSnapshot.lane or ""),
            domains = TrimText(type(itemPreparedSnapshot) == "table"
              and type(itemPreparedSnapshot.domains) == "table"
              and table.concat(itemPreparedSnapshot.domains, ",") or ""),
            subdomains = TrimText(type(itemPreparedSnapshot) == "table"
              and type(itemPreparedSnapshot.subdomains) == "table"
              and table.concat(itemPreparedSnapshot.subdomains, ",") or ""),
            holdRemaining = math.max(0, tonumber(profileSyncLocalOps.getSnapshotBatchHoldDelay(item)) or 0),
          }
        end
      end
    end
    return {
      running = profileSyncSessionState.snapshotBatchRunning and true or false,
      pendingTargets = #profileSyncSessionState.pendingSnapshotBatch,
      pendingIncomingTransfers = pendingIncomingTransfers,
      incomingTransfer = latestIncomingTransfer,
      maxIncomingTransfers = profileSyncConfig.maxPendingIncomingSnapshotTransfers,
      maxIncomingTransfersPerSender = profileSyncConfig.maxPendingIncomingSnapshotTransfersPerSender,
      incomingSnapshotBytes = incomingSnapshotBytes,
      maxIncomingSnapshotBytes = profileSyncConfig.maxIncomingSnapshotBytes,
      oldestIncomingTransferAge = oldestIncomingTransferAge,
      longestIncomingTransferIdleSeconds = longestIncomingTransferIdleSeconds,
      incomingSnapshotStallSeconds = math.max(1, tonumber(profileSyncConfig.incomingSnapshotStallSeconds) or 30),
      incomingSnapshotHealth = incomingSnapshotHealth,
      incomingSnapshotCleanupTotal = math.max(0, tonumber(profileSyncSessionState.incomingSnapshotCleanupTotal) or 0),
      lastIncomingSnapshotCleanupCount = math.max(0, tonumber(profileSyncSessionState.lastIncomingSnapshotCleanupCount) or 0),
      lastIncomingSnapshotCleanupSessionId = TrimText(profileSyncSessionState.lastIncomingSnapshotCleanupSessionId),
      lastIncomingSnapshotCleanupAt = math.max(0, tonumber(profileSyncSessionState.lastIncomingSnapshotCleanupAt) or 0),
      incomingSnapshotCleanupHistory = cleanupHistory,
      incomingSnapshotDiagnosticsSessionId = TrimText(profileSyncSessionState.incomingSnapshotDiagnosticsSessionId),
      incomingSnapshotDiagnosticsStartedAt = math.max(0, tonumber(profileSyncSessionState.incomingSnapshotDiagnosticsStartedAt) or 0),
      incomingSnapshotRejectTotal = math.max(0, tonumber(profileSyncSessionState.incomingSnapshotRejectTotal) or 0),
      lastIncomingSnapshotRejectOpcode = TrimText(profileSyncSessionState.lastIncomingSnapshotRejectOpcode),
      lastIncomingSnapshotRejectReason = TrimText(profileSyncSessionState.lastIncomingSnapshotRejectReason),
      lastIncomingSnapshotRejectSender = NormalizeCharacterKey(profileSyncSessionState.lastIncomingSnapshotRejectSender),
      lastIncomingSnapshotRejectTransferId = TrimText(profileSyncSessionState.lastIncomingSnapshotRejectTransferId),
      lastIncomingSnapshotRejectSessionId = TrimText(profileSyncSessionState.lastIncomingSnapshotRejectSessionId),
      lastIncomingSnapshotRejectAt = math.max(0, tonumber(profileSyncSessionState.lastIncomingSnapshotRejectAt) or 0),
      incomingSnapshotRejectCounts = rejectCounts,
      incomingSnapshotRejectHistory = rejectHistory,
      archiveInFlightCoalescedTotal = math.max(0, tonumber(profileSyncSessionState.archiveInFlightCoalescedTotal) or 0),
      lastArchiveInFlightCoalescedAt = math.max(0, tonumber(profileSyncSessionState.lastArchiveInFlightCoalescedAt) or 0),
      lastArchiveInFlightCoalescedTarget = NormalizeCharacterKey(profileSyncSessionState.lastArchiveInFlightCoalescedTarget),
      preparedArchiveRepairCacheEntries = math.max(0, tonumber(preparedArchiveRepairCacheEntries) or 0),
      preparedSnapshotCacheEntries = math.max(0, tonumber(preparedSnapshotCacheEntries) or 0),
      preparedSnapshotCacheHits = math.max(0, tonumber(profileSyncSessionState.preparedSnapshotCacheHits) or 0),
      preparedSnapshotCacheMisses = math.max(0, tonumber(profileSyncSessionState.preparedSnapshotCacheMisses) or 0),
      archivePreparationCoalescedTotal = math.max(0, tonumber(profileSyncSessionState.archivePreparationCoalescedTotal) or 0),
      archivePreparationPrunedTotal = math.max(0, tonumber(profileSyncSessionState.archivePreparationPrunedTotal) or 0),
      lastArchivePreparationCoalescedAt = math.max(0, tonumber(profileSyncSessionState.lastArchivePreparationCoalescedAt) or 0),
      lastArchivePreparationCoalescedTarget = NormalizeCharacterKey(profileSyncSessionState.lastArchivePreparationCoalescedTarget),
      admissionHoldReason = TrimText(profileSyncSessionState.snapshotAdmissionHoldReason),
      admissionHoldCount = math.max(0, tonumber(profileSyncSessionState.snapshotAdmissionHoldCount) or 0),
      admissionHoldAt = math.max(0, tonumber(profileSyncSessionState.snapshotAdmissionHoldAt) or 0),
      pausedTargets = pausedTargets,
      holdRemaining = math.max(0, tonumber(holdRemaining) or 0),
      heldSessionId = heldSessionId,
      holdReason = TrimText(profileSyncSessionState.snapshotBatchJoinHoldReasonBySession[heldSessionId]),
      firstQueuedTarget = NormalizeCharacterKey(type(firstItem) == "table" and firstItem.target or ""),
      firstQueuedTransferKind = TrimText(type(firstQueuedPreparedSnapshot) == "table" and firstQueuedPreparedSnapshot.transferKind or ""),
      firstQueuedPriority = firstQueuedPriority,
      pendingItems = pendingItems,
      nextTarget = NormalizeCharacterKey(type(nextRunnable) == "table" and nextRunnable.target or (type(firstItem) == "table" and firstItem.target or "")),
      nextProfileName = TrimText(type(nextRunnable) == "table" and (nextRunnable.profileName or (type(nextRunnable.preparedSnapshot) == "table" and nextRunnable.preparedSnapshot.profileName) or "") or (type(firstItem) == "table" and (firstItem.profileName or (type(firstItem.preparedSnapshot) == "table" and firstItem.preparedSnapshot.profileName) or "") or "")),
      nextTransferKind = TrimText(type(nextPreparedSnapshot) == "table" and nextPreparedSnapshot.transferKind or ""),
      nextPriority = (type(nextRunnable) == "table" or type(firstItem) == "table")
        and math.max(0, tonumber(profileSyncLocalOps.getPreparedTransferPriority(
          type(nextRunnable) == "table" and nextRunnable.preparedSnapshot or (type(firstItem) == "table" and firstItem.preparedSnapshot or nil),
          type(nextRunnable) == "table" and nextRunnable or firstItem
        )) or 0)
        or 0,
    }
  end

  RunNextSnapshotBatchItem = function()
    local selectedIndex, selectedPriority, nextHoldDelay = profileSyncLocalOps.findNextRunnableSnapshotBatchItem()

    if not selectedIndex then
      if #profileSyncSessionState.pendingSnapshotBatch > 0 then
        if nextHoldDelay and nextHoldDelay > 0 then
          profileSyncLocalOps.scheduleNextSnapshotBatchItem(nextHoldDelay)
        else
          profileSyncLocalOps.scheduleNextSnapshotBatchItem(0.50)
        end
      else
        profileSyncLocalOps.setSnapshotBatchPreferredSession("", 0)
        profileSyncSessionState.snapshotBatchRunning = false
      end
      return
    end

    local initialOutboundStatus = type(deps.GetCommOutboundQueueStatus) == "function"
      and deps.GetCommOutboundQueueStatus()
      or nil
    local selectedBatchItem = profileSyncSessionState.pendingSnapshotBatch[selectedIndex]
    local selectedPreparedSnapshot = type(selectedBatchItem) == "table" and selectedBatchItem.preparedSnapshot or nil
    local selectedProjectedMessages = type(selectedPreparedSnapshot) == "table"
      and type(selectedPreparedSnapshot.chunks) == "table"
      and (#selectedPreparedSnapshot.chunks + 2)
      or 0
    local initialAdmission = profileSyncLocalOps.resolveSnapshotBatchAdmission(initialOutboundStatus, selectedPriority, {
      additionalMessages = selectedProjectedMessages,
    })
    if initialAdmission.admit ~= true then
      profileSyncSessionState.snapshotAdmissionHoldReason = TrimText(initialAdmission.reason)
      profileSyncSessionState.snapshotAdmissionHoldCount =
        math.max(0, tonumber(profileSyncSessionState.snapshotAdmissionHoldCount) or 0) + 1
      profileSyncSessionState.snapshotAdmissionHoldAt = GetNow()
      profileSyncLocalOps.scheduleNextSnapshotBatchItem(initialAdmission.delaySeconds)
      return
    end
    profileSyncSessionState.snapshotAdmissionHoldReason = ""

    local item = table.remove(profileSyncSessionState.pendingSnapshotBatch, selectedIndex)
    if not item then
      profileSyncSessionState.snapshotBatchRunning = false
      return
    end

    local preparationBurstLimit = math.max(1, tonumber(profileSyncConfig.snapshotPreparationBurstLimit) or 1)
    local preparationsThisRun = type(item.preparedSnapshot) == "table" and 0 or 1
    local preparedSnapshot = profileSyncLocalOps.resolvePendingBatchPreparedSnapshot(item)
    local preparedPriority = profileSyncLocalOps.getPreparedTransferPriority(preparedSnapshot, item)
    local preparedAdmission = profileSyncLocalOps.resolveSnapshotBatchAdmission(
      type(deps.GetCommOutboundQueueStatus) == "function" and deps.GetCommOutboundQueueStatus() or nil,
      preparedPriority,
      {
        additionalMessages = type(preparedSnapshot) == "table" and type(preparedSnapshot.chunks) == "table"
          and (#preparedSnapshot.chunks + 2)
          or 0,
      }
    )
    if preparedAdmission.admit ~= true then
      item.preparedSnapshot = preparedSnapshot
      table.insert(profileSyncSessionState.pendingSnapshotBatch, math.min(
        math.max(1, tonumber(selectedIndex) or 1),
        #profileSyncSessionState.pendingSnapshotBatch + 1
      ), item)
      profileSyncSessionState.snapshotAdmissionHoldReason = TrimText(preparedAdmission.reason)
      profileSyncSessionState.snapshotAdmissionHoldCount =
        math.max(0, tonumber(profileSyncSessionState.snapshotAdmissionHoldCount) or 0) + 1
      profileSyncSessionState.snapshotAdmissionHoldAt = GetNow()
      profileSyncLocalOps.scheduleNextSnapshotBatchItem(preparedAdmission.delaySeconds)
      return
    end
    local burstLimit = math.max(1, profileSyncLocalOps.getPreparedTransferBurstLimit(preparedSnapshot, item))
    local sentCount = 0
    local maxDelay = profileSyncLocalOps.estimateSnapshotTargetDelay(preparedSnapshot)
    local basePriority = preparedPriority
    local baseSessionId = TrimText(item.sessionId)

    while item do
      preparedSnapshot = profileSyncLocalOps.resolvePendingBatchPreparedSnapshot(item)
      if preparedSnapshot then
        SendPreparedProfileSnapshot(preparedSnapshot, item.sessionId, item.target, item.opts)
        sentCount = sentCount + 1
        maxDelay = math.max(maxDelay, profileSyncLocalOps.estimateSnapshotTargetDelay(preparedSnapshot))
      end
      if sentCount >= burstLimit then
        break
      end
      local outboundStatus = type(deps.GetCommOutboundQueueStatus) == "function" and deps.GetCommOutboundQueueStatus() or nil
      if profileSyncLocalOps.hasHigherPriorityOutboundYieldTraffic(outboundStatus) then
        break
      end
      local candidate = profileSyncSessionState.pendingSnapshotBatch[1]
      if not candidate then
        break
      end
      if profileSyncLocalOps.isSnapshotBatchItemArchivePaused(candidate) then
        break
      end
      if profileSyncLocalOps.getSnapshotBatchHoldDelay(candidate) > 0 then
        break
      end
      if TrimText(candidate.sessionId) ~= baseSessionId then
        break
      end
      local candidatePriority = profileSyncLocalOps.getPreparedTransferPriority(
        type(candidate) == "table" and candidate.preparedSnapshot or nil,
        candidate
      )
      if candidatePriority ~= basePriority then
        break
      end
      local candidatePreparedSnapshot = type(candidate) == "table" and candidate.preparedSnapshot or nil
      if type(candidatePreparedSnapshot) ~= "table" then
        if preparationsThisRun >= preparationBurstLimit then
          break
        end
        candidatePreparedSnapshot = profileSyncLocalOps.resolvePendingBatchPreparedSnapshot(candidate)
        candidate.preparedSnapshot = candidatePreparedSnapshot
        preparationsThisRun = preparationsThisRun + 1
        candidatePriority = profileSyncLocalOps.getPreparedTransferPriority(candidatePreparedSnapshot, candidate)
        if candidatePriority ~= basePriority then
          break
        end
      end
      local candidateAdmission = profileSyncLocalOps.resolveSnapshotBatchAdmission(outboundStatus, candidatePriority, {
        additionalMessages = type(candidatePreparedSnapshot) == "table" and type(candidatePreparedSnapshot.chunks) == "table"
          and (#candidatePreparedSnapshot.chunks + 2)
          or 0,
      })
      if candidateAdmission.admit ~= true then
        profileSyncSessionState.snapshotAdmissionHoldReason = TrimText(candidateAdmission.reason)
        profileSyncSessionState.snapshotAdmissionHoldCount =
          math.max(0, tonumber(profileSyncSessionState.snapshotAdmissionHoldCount) or 0) + 1
        profileSyncSessionState.snapshotAdmissionHoldAt = GetNow()
        break
      end
      item = table.remove(profileSyncSessionState.pendingSnapshotBatch, 1)
    end

    local intervalSeconds = math.max(0, tonumber(type(deps.GetCommOutboundIntervalSeconds) == "function" and deps.GetCommOutboundIntervalSeconds() or 0.12) or 0.12)
    local delay = sentCount > 1
      and math.max(intervalSeconds, maxDelay / math.max(1, sentCount))
      or maxDelay
    profileSyncLocalOps.setSnapshotBatchPreferredSession(baseSessionId, sentCount > 0 and basePriority or 0)
    local outboundStatus = type(deps.GetCommOutboundQueueStatus) == "function" and deps.GetCommOutboundQueueStatus() or nil
    delay = profileSyncLocalOps.getSnapshotBatchYieldRescheduleDelay(delay, basePriority, outboundStatus)
    profileSyncLocalOps.scheduleNextSnapshotBatchItem(delay)
  end

  local function SendPreparedProfileSnapshotBatch(preparedSnapshot, sessionId, targets, opts)
    if type(preparedSnapshot) ~= "table" or type(preparedSnapshot.chunks) ~= "table" then
      return false, "Profile snapshot is not prepared."
    end
    if type(targets) ~= "table" or #targets == 0 then
      return false, "No profile snapshot targets."
    end

    opts = type(opts) == "table" and opts or {}
    local queued = 0
    local inFlightCoalescedCount = 0
    local mergedBatchCount = 0
    local exactDuplicateBatchCount = 0
    local shouldCoalesceArchiveInFlight = string.upper(TrimText(opts.mode)) == "BACKGROUND"
      and generationOps.NormalizeProfileTransferLane(
        TrimText(opts.reason),
        type(preparedSnapshot) == "table" and preparedSnapshot.subdomains or {},
        TrimText(type(preparedSnapshot) == "table" and preparedSnapshot.transferKind or "")
      ) == "archive"
    for _, target in ipairs(targets) do
      local resolvedTarget = NormalizeCharacterKey(target)
      if resolvedTarget ~= "" then
        local matchingTransfer = nil
        local outboundStatus = shouldCoalesceArchiveInFlight and type(sessionRuntimeOps.getCommOutboundQueueStatus) == "function"
          and sessionRuntimeOps.getCommOutboundQueueStatus()
          or nil
        for _, transfer in ipairs(type(outboundStatus) == "table" and outboundStatus.profileTransfers or {}) do
          if profileSyncLocalOps.isMatchingArchiveInFlightProfileTransfer(
            preparedSnapshot,
            sessionId,
            resolvedTarget,
            opts,
            transfer
          ) then
            matchingTransfer = transfer
            break
          end
        end
        if matchingTransfer then
          inFlightCoalescedCount = inFlightCoalescedCount + 1
          profileSyncSessionState.archiveInFlightCoalescedTotal = math.max(0,
            tonumber(profileSyncSessionState.archiveInFlightCoalescedTotal) or 0) + 1
          profileSyncSessionState.lastArchiveInFlightCoalescedAt = GetNow()
          profileSyncSessionState.lastArchiveInFlightCoalescedTarget = resolvedTarget
        else
          if type(sessionRuntimeOps.cancelQueuedProfileTransfersForScope) == "function" then
            sessionRuntimeOps.cancelQueuedProfileTransfersForScope(sessionId, resolvedTarget, preparedSnapshot, {
              profileName = TrimText(type(preparedSnapshot) == "table" and preparedSnapshot.profileName or ""),
              transferKind = TrimText(type(preparedSnapshot) == "table" and preparedSnapshot.transferKind or ""),
              scopeDomains = CloneProfileSyncDomainList(type(preparedSnapshot) == "table" and preparedSnapshot.domains or {}),
              scopeSubdomains = CloneProfileSyncSubdomainList(type(preparedSnapshot) == "table" and preparedSnapshot.subdomains or {}),
            })
          end
          local mergedCount, exactDuplicateCount = profileSyncLocalOps.insertPendingSnapshotBatchItem({
            preparedSnapshot = preparedSnapshot,
            sessionId = sessionId,
            target = resolvedTarget,
            opts = opts,
          })
          queued = queued + 1
          mergedBatchCount = mergedBatchCount + math.max(0, tonumber(mergedCount) or 0)
          exactDuplicateBatchCount = exactDuplicateBatchCount + math.max(0, tonumber(exactDuplicateCount) or 0)
        end
      end
    end

    if queued > 0 and not profileSyncSessionState.snapshotBatchRunning then
      profileSyncSessionState.snapshotBatchRunning = true
      RunNextSnapshotBatchItem()
    end
    if type(RecordProfileSyncDecision) == "function" then
      RecordProfileSyncDecision("queue_prepared_snapshot_batch", {
        action = queued > 0 and "queued" or (inFlightCoalescedCount > 0 and "coalesced" or "failed"),
        sessionId = TrimText(sessionId),
        profileName = TrimText(type(preparedSnapshot) == "table" and preparedSnapshot.profileName or ""),
        mode = TrimText(opts.mode),
        reason = TrimText(opts.reason),
        transferKind = TrimText(type(preparedSnapshot) == "table" and preparedSnapshot.transferKind or ""),
        transferKinds = { TrimText(type(preparedSnapshot) == "table" and preparedSnapshot.transferKind or "") },
        targetCount = #targets,
        queuedCount = queued,
        inFlightCoalescedCount = inFlightCoalescedCount,
        mergedCount = mergedBatchCount,
        exactDuplicateCount = exactDuplicateBatchCount,
        chunkCount = type(preparedSnapshot) == "table" and type(preparedSnapshot.chunks) == "table" and #preparedSnapshot.chunks or 0,
        domains = CloneProfileSyncDomainList(type(preparedSnapshot) == "table" and preparedSnapshot.domains or {}),
        subdomains = CloneProfileSyncSubdomainList(type(preparedSnapshot) == "table" and preparedSnapshot.subdomains or {}),
        error = (queued > 0 or inFlightCoalescedCount > 0) and nil or "No profile snapshot targets were queued.",
      })
    end
    return queued > 0 or inFlightCoalescedCount > 0, queued, {
      mergedCount = mergedBatchCount,
      exactDuplicateCount = exactDuplicateBatchCount,
      inFlightCoalescedCount = inFlightCoalescedCount,
    }
  end

  profileSyncLocalOps.queueSelectedPreviewRepairPropagation = function(activeSession, activeProfileName, previewMemberKey, subdomains, rowSelectionsBySubdomain, rowMapsBySubdomain)
    local resolvedProfileName = TrimText(activeProfileName)
    local resolvedPreviewMemberKey = NormalizeCharacterKey(previewMemberKey)
    local resolvedDomains = type(ResolveLootProfileDomainsForSubdomains) == "function"
      and ResolveLootProfileDomainsForSubdomains(subdomains)
      or ResolveProfileRevisionDomainList(nil)
    local resolvedSubdomains = NormalizeRequestedProfileSyncSubdomains(subdomains, resolvedDomains)
    if type(activeSession) ~= "table" or TrimText(activeSession.id) == "" or resolvedProfileName == "" or #resolvedSubdomains == 0 then
      return false, {
        queuedMembers = 0,
        queuedTransfers = 0,
        patchTransfers = 0,
        patchSubdomains = 0,
        snapshotTransfers = 0,
        skippedLineage = 0,
      }
    end

    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    local localProfileId = TrimText(select(1, GetLootProfileId(resolvedProfileName)) or "")
    local candidatesByKey = {}
    for _, candidate in ipairs(GetActiveProfileSyncCandidates() or {}) do
      local candidateKey = NormalizeCharacterKey(type(candidate) == "table" and candidate.memberKey or "")
      if candidateKey ~= "" then
        candidatesByKey[string.lower(candidateKey)] = candidate
      end
    end

    local stats = {
      queuedMembers = 0,
      queuedTransfers = 0,
      rowPatchTransfers = 0,
      rowPatchRows = 0,
      patchTransfers = 0,
      patchSubdomains = 0,
      snapshotTransfers = 0,
      skippedLineage = 0,
      failedMembers = 0,
      previewMemberQueued = false,
      lastError = "",
    }

    local queuedRowTargets = {}
    local preparedRowPatch = nil
    if type(rowSelectionsBySubdomain) == "table" and type(rowMapsBySubdomain) == "table" then
      preparedRowPatch = profileSyncLocalOps.prepareProfileSnapshotTransfer(resolvedProfileName, {
        domains = resolvedDomains,
        subdomains = resolvedSubdomains,
        rowSelectionsBySubdomain = rowSelectionsBySubdomain,
        rowMapsBySubdomain = rowMapsBySubdomain,
      })
    end

    for memberKey, member in pairs(activeSession.members or {}) do
      local resolvedMemberKey = NormalizeCharacterKey(memberKey)
      if resolvedMemberKey ~= "" and resolvedMemberKey ~= selfKey
        and type(member) == "table" and tostring(member.status or "JOINED") == "JOINED" then
        local candidate = candidatesByKey[string.lower(resolvedMemberKey)]
        local remoteProfileId = TrimText(
          type(candidate) == "table" and candidate.profileId
            or type(member) == "table" and member.sharedProfileId
            or ""
        )
        if localProfileId ~= "" and remoteProfileId ~= "" and string.lower(localProfileId) ~= string.lower(remoteProfileId) then
          stats.skippedLineage = stats.skippedLineage + 1
        elseif type(preparedRowPatch) == "table" and TrimText(preparedRowPatch.transferKind) == "ROWPATCHES" then
          queuedRowTargets[#queuedRowTargets + 1] = resolvedMemberKey
        else
          local preparedTransfers, prepareError, prepareDetail = profileSyncLocalOps.buildPreparedProfileRepairTransfers(
            resolvedProfileName,
            activeSession.id,
            resolvedMemberKey,
            {
              domains = resolvedDomains,
              subdomains = resolvedSubdomains,
            }
          )
          if type(preparedTransfers) ~= "table" or #preparedTransfers == 0 then
            local resolvedPrepareError = TrimText(prepareError)
            if string.lower(resolvedPrepareError) ~= "no repair transfer could be prepared." and resolvedPrepareError ~= "" then
              stats.failedMembers = stats.failedMembers + 1
              stats.lastError = TrimText(prepareError)
            end
          else
            local memberQueued = false
            for _, preparedSnapshot in ipairs(preparedTransfers) do
              local ok, queuedCount = SendPreparedProfileSnapshotBatch(preparedSnapshot, activeSession.id, { resolvedMemberKey }, {
                mode = "LIVE",
                reason = "preview_resolution_sync",
                domains = resolvedDomains,
                subdomains = resolvedSubdomains,
                preparedSnapshot = preparedSnapshot,
              })
              if ok then
                stats.queuedTransfers = stats.queuedTransfers + math.max(1, tonumber(queuedCount) or 1)
                memberQueued = true
              elseif TrimText(queuedCount) ~= "" then
                stats.lastError = TrimText(queuedCount)
              end
            end
            if memberQueued then
              stats.queuedMembers = stats.queuedMembers + 1
              stats.patchTransfers = stats.patchTransfers + math.max(0, tonumber(type(prepareDetail) == "table" and prepareDetail.patchTransfers or 0) or 0)
              stats.patchSubdomains = stats.patchSubdomains + math.max(0, tonumber(type(prepareDetail) == "table" and prepareDetail.patchSubdomains or 0) or 0)
              stats.snapshotTransfers = stats.snapshotTransfers + math.max(0, tonumber(type(prepareDetail) == "table" and prepareDetail.snapshotTransfers or 0) or 0)
              if resolvedPreviewMemberKey ~= "" and resolvedMemberKey == resolvedPreviewMemberKey then
                stats.previewMemberQueued = true
              end
            end
          end
        end
      end
    end

    if #queuedRowTargets > 0 and type(preparedRowPatch) == "table" and TrimText(preparedRowPatch.transferKind) == "ROWPATCHES" then
      local ok, queuedCount = SendPreparedProfileSnapshotBatch(preparedRowPatch, activeSession.id, queuedRowTargets, {
        mode = "LIVE",
        reason = "preview_resolution_rowpatch_sync",
        domains = resolvedDomains,
        subdomains = resolvedSubdomains,
        preparedSnapshot = preparedRowPatch,
      })
      if ok then
        stats.queuedMembers = stats.queuedMembers + math.max(0, tonumber(queuedCount) or #queuedRowTargets)
        stats.queuedTransfers = stats.queuedTransfers + math.max(0, tonumber(queuedCount) or #queuedRowTargets)
        stats.rowPatchTransfers = stats.rowPatchTransfers + math.max(0, tonumber(queuedCount) or #queuedRowTargets)
        local rowPatchRows = 0
        for _, selectedRows in pairs(type(rowSelectionsBySubdomain) == "table" and rowSelectionsBySubdomain or {}) do
          rowPatchRows = rowPatchRows + math.max(0, tonumber(type(selectedRows) == "table" and #selectedRows or 0) or 0)
        end
        stats.rowPatchRows = rowPatchRows
        if resolvedPreviewMemberKey ~= "" then
          for _, queuedTarget in ipairs(queuedRowTargets) do
            if queuedTarget == resolvedPreviewMemberKey then
              stats.previewMemberQueued = true
              break
            end
          end
        end
      elseif TrimText(queuedCount) ~= "" then
        stats.lastError = TrimText(queuedCount)
      end
    end

    return stats.queuedMembers > 0, stats
  end

  local function SendProfileSnapshotBatch(profileName, sessionId, targets, opts)
    local resolvedProfileName = TrimText(profileName)
    if resolvedProfileName == "" then
      return false, "Profile name is missing."
    end
    if type(targets) ~= "table" or #targets == 0 then
      return false, "No profile snapshot targets."
    end

    opts = type(opts) == "table" and opts or {}
    local queued = 0
    for _, target in ipairs(targets) do
      local resolvedTarget = NormalizeCharacterKey(target)
      if resolvedTarget ~= "" then
        profileSyncLocalOps.insertPendingSnapshotBatchItem({
          profileName = resolvedProfileName,
          sessionId = sessionId,
          target = resolvedTarget,
          opts = opts,
        })
        queued = queued + 1
      end
    end

    if queued > 0 and not profileSyncSessionState.snapshotBatchRunning then
      profileSyncSessionState.snapshotBatchRunning = true
      RunNextSnapshotBatchItem()
    end
    return queued > 0, queued
  end

  profileSyncLocalOps.buildRequestedProfileSyncResponseQueueKey = function(sessionId, memberKey, responseMode)
    local resolvedSessionId = string.lower(TrimText(sessionId))
    local resolvedMemberKey = string.lower(NormalizeCharacterKey(memberKey))
    local resolvedMode = string.upper(TrimText(responseMode))
    if resolvedSessionId == "" or resolvedMemberKey == "" or resolvedMode == "" then
      return ""
    end
    return table.concat({
      resolvedSessionId,
      resolvedMemberKey,
      resolvedMode,
    }, "|")
  end

  profileSyncLocalOps.buildPreparedProfileSyncResponseSignature = function(responseMode, requestDomains, requestSubdomains, preparedTransfers)
    local normalizedTransfers = {}
    for _, preparedSnapshot in ipairs(type(preparedTransfers) == "table" and preparedTransfers or {}) do
      if type(preparedSnapshot) == "table" then
        normalizedTransfers[#normalizedTransfers + 1] = {
          profileName = TrimText(preparedSnapshot.profileName),
          profileId = TrimText(preparedSnapshot.profileId),
          transferKind = TrimText(preparedSnapshot.transferKind),
          domains = CloneProfileSyncDomainList(preparedSnapshot.domains),
          subdomains = CloneProfileSyncSubdomainList(preparedSnapshot.subdomains),
          requestedDomains = CloneProfileSyncDomainList(preparedSnapshot.requestedDomains),
          requestedSubdomains = CloneProfileSyncSubdomainList(preparedSnapshot.requestedSubdomains),
          requestedScope = TrimText(preparedSnapshot.requestedScope),
          scopeEscalated = preparedSnapshot.scopeEscalated == true,
          fullSnapshotFallback = preparedSnapshot.fullSnapshotFallback == true,
          fallbackEscalation = TrimText(preparedSnapshot.fallbackEscalation),
          fallbackReasons = CloneProfileSyncTextList(preparedSnapshot.fallbackReasons),
          authoritativeArchiveScope = TrimText(preparedSnapshot.authoritativeArchiveScope),
          chunks = type(preparedSnapshot.chunks) == "table" and preparedSnapshot.chunks or {},
        }
      end
    end
    return BuildStableValueSignature({
      mode = string.upper(TrimText(responseMode)),
      requestDomains = CloneProfileSyncDomainList(requestDomains),
      requestSubdomains = CloneProfileSyncSubdomainList(requestSubdomains),
      transfers = normalizedTransfers,
    })
  end

  profileSyncLocalOps.cancelQueuedPreparedSnapshotTransfer = function(sessionId, target, preparedSnapshot)
    if type(sessionRuntimeOps.cancelQueuedProfileTransfersForScope) ~= "function" then
      return 0
    end
    return sessionRuntimeOps.cancelQueuedProfileTransfersForScope(sessionId, NormalizeCharacterKey(target), preparedSnapshot, {
      profileName = TrimText(type(preparedSnapshot) == "table" and preparedSnapshot.profileName or ""),
      transferKind = TrimText(type(preparedSnapshot) == "table" and preparedSnapshot.transferKind or ""),
      scopeDomains = CloneProfileSyncDomainList(type(preparedSnapshot) == "table" and preparedSnapshot.domains or {}),
      scopeSubdomains = CloneProfileSyncSubdomainList(type(preparedSnapshot) == "table" and preparedSnapshot.subdomains or {}),
    })
  end

  profileSyncLocalOps.queueRequestedProfileSyncResponse = function(sessionId, profileName, memberKey, requestMode, requestDomains, requestSubdomains, expectedPatchManifestToken)
    local resolvedSessionId = TrimText(sessionId)
    local resolvedProfileName = TrimText(profileName)
    local resolvedTarget = NormalizeCharacterKey(memberKey)
    local resolvedMode = string.upper(TrimText(requestMode)) == "PREVIEW" and "PREVIEW" or "REVIEW"
    local explicitRequestDomains = type(requestDomains) == "table" and requestDomains
      or (TrimText(requestDomains) ~= "" and DecodeProfileRevisionDomains(requestDomains) or {})
    local resolvedDomains = ResolveProfileRevisionDomainList(explicitRequestDomains)
    local resolvedSubdomains = NormalizeRequestedProfileSyncSubdomains(requestSubdomains, resolvedDomains)
    local resolvedExpectedPatchManifestToken = TrimText(expectedPatchManifestToken)
    if resolvedSessionId == "" or resolvedProfileName == "" or resolvedTarget == "" then
      return false
    end

    local now = GetNow()
    PrunePreciseResponseRuntime(now)
    local requestKey = profileSyncLocalOps.buildRequestedProfileSyncResponseQueueKey(resolvedSessionId, resolvedTarget, resolvedMode)
    if requestKey == "" then
      return false
    end

    local pending = profileSyncResponseRuntime.requested.pending[requestKey]
    if type(pending) == "table" then
      local mergedDomains = MergeProfileRevisionDomains(pending.requestDomains, resolvedDomains)
      pending.requestDomains = CloneProfileSyncDomainList(mergedDomains)
      pending.requestSubdomains = MergeRequestedProfileSyncSubdomains(
        mergedDomains,
        pending.requestSubdomains,
        resolvedSubdomains
      )
      if resolvedExpectedPatchManifestToken ~= "" then
        pending.expectedPatchManifestToken = resolvedExpectedPatchManifestToken
      end
      pending.updatedAt = now
      pending.allowPatchManifestDelay = pending.allowPatchManifestDelay == true or resolvedExpectedPatchManifestToken ~= ""
      return true
    end

    profileSyncResponseRuntime.requested.pending[requestKey] = {
      sessionId = resolvedSessionId,
      profileName = resolvedProfileName,
      target = resolvedTarget,
      responseMode = resolvedMode,
      requestDomains = CloneProfileSyncDomainList(resolvedDomains),
      requestSubdomains = CloneProfileSyncSubdomainList(resolvedSubdomains),
      expectedPatchManifestToken = resolvedExpectedPatchManifestToken,
      allowPatchManifestDelay = resolvedExpectedPatchManifestToken ~= "",
      queuedAt = now,
      updatedAt = now,
    }

    if type(Compat) == "table" and type(Compat.After) == "function" then
      Compat.After(profileSyncConfig.subcheckRequestCoalesceDelaySeconds, function()
        profileSyncLocalOps.flushQueuedRequestedProfileSyncResponse(requestKey)
      end)
      return true
    end

    return profileSyncLocalOps.flushQueuedRequestedProfileSyncResponse(requestKey) == true
  end

  profileSyncLocalOps.shouldDelayRequestedProfilePatchManifest = function(expectedPatchManifestToken, requestedPatchCapableSubdomains, prepareDetail)
    if TrimText(expectedPatchManifestToken) == "" or string.upper(TrimText(expectedPatchManifestToken)) == "MISS" then
      return false
    end
    if #(type(requestedPatchCapableSubdomains) == "table" and requestedPatchCapableSubdomains or {}) == 0 or type(prepareDetail) ~= "table" then
      return false
    end
    if prepareDetail.patchManifestMatched == false then
      return true
    end
    for _, fallbackReason in ipairs(type(prepareDetail.fallbackReasons) == "table" and prepareDetail.fallbackReasons or {}) do
      local resolvedReason = string.lower(TrimText(fallbackReason))
      if resolvedReason == "missing_patch_state"
        or resolvedReason == "patch_manifest_token_mismatch"
        or resolvedReason == "no_patch_ready_subdomains"
      then
        return true
      end
    end
    return false
  end

  profileSyncLocalOps.flushQueuedRequestedProfileSyncResponse = function(requestKey)
    local pending = profileSyncResponseRuntime.requested.pending[TrimText(requestKey)]
    if type(pending) ~= "table" then
      return false
    end
    profileSyncResponseRuntime.requested.pending[requestKey] = nil

    local activeSession, activeProfileName = GetActiveLootSession()
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    local resolvedSessionId = TrimText(pending.sessionId)
    local resolvedProfileName = TrimText(pending.profileName)
    local resolvedTarget = NormalizeCharacterKey(pending.target)
    local responseMode = string.upper(TrimText(pending.responseMode)) == "PREVIEW" and "PREVIEW" or "REVIEW"
    local requestDomains = CloneProfileSyncDomainList(type(pending.requestDomains) == "table" and pending.requestDomains or {})
    local requestSubdomains = NormalizeRequestedProfileSyncSubdomains(pending.requestSubdomains, requestDomains)
    local expectedPatchManifestToken = TrimText(pending.expectedPatchManifestToken)
    if resolvedSessionId == ""
      or resolvedProfileName == ""
      or resolvedTarget == ""
      or not sessionRuntimeOps.doesSessionMatch(activeSession, activeProfileName, resolvedSessionId, resolvedProfileName)
      or not sessionRuntimeOps.isHostSender(activeSession, resolvedTarget)
      or selfKey == ""
      or not sessionRuntimeOps.isJoinedCharacter(activeSession, selfKey)
    then
      return false
    end

    local requestedPatchCapableSubdomains = type(FilterLootProfilePatchCapableSubdomains) == "function"
      and FilterLootProfilePatchCapableSubdomains(requestSubdomains)
      or {}

    local responseReason = responseMode == "PREVIEW" and "preview_request_response" or "review_request_response"
    local preparedTransfers = {}
    local patchTransferCount = 0
    local patchScopeCount = 0
    if #requestSubdomains > 0 and type(profileSyncLocalOps.buildPreparedProfileRepairTransfers) == "function" then
      local scopedTransfers, _, prepareDetail = profileSyncLocalOps.buildPreparedProfileRepairTransfers(activeProfileName, resolvedSessionId, resolvedTarget, {
        mode = responseMode,
        reason = responseReason,
        domains = requestDomains,
        subdomains = requestSubdomains,
        patchManifestToken = expectedPatchManifestToken,
      })
      local shouldDelay = pending.allowPatchManifestDelay == true
        and profileSyncLocalOps.shouldDelayRequestedProfilePatchManifest(expectedPatchManifestToken, requestedPatchCapableSubdomains, prepareDetail)
        and math.max(0, tonumber(type(prepareDetail) == "table" and prepareDetail.snapshotTransfers) or 0) > 0
        and type(Compat) == "table"
        and type(Compat.After) == "function"
      if shouldDelay then
        pending.allowPatchManifestDelay = false
        pending.updatedAt = GetNow()
        profileSyncResponseRuntime.requested.pending[requestKey] = pending
        Compat.After(0.20, function()
          profileSyncLocalOps.flushQueuedRequestedProfileSyncResponse(requestKey)
        end)
        return true
      end
      if type(scopedTransfers) == "table" and #scopedTransfers > 0 then
        preparedTransfers = scopedTransfers
        patchTransferCount = math.max(0, tonumber(type(prepareDetail) == "table" and prepareDetail.patchTransfers) or 0)
        patchScopeCount = math.max(0, tonumber(type(prepareDetail) == "table" and prepareDetail.patchSubdomains) or 0)
      end
    end

    if #preparedTransfers == 0 then
      local preparedSnapshot = profileSyncLocalOps.prepareProfileSnapshotTransfer(activeProfileName, {
        mode = responseMode,
        reason = responseReason,
        domains = #requestDomains > 0 and requestDomains or nil,
        subdomains = #requestSubdomains > 0 and requestSubdomains or nil,
        sessionId = resolvedSessionId,
      })
      if type(preparedSnapshot) ~= "table" then
        return false
      end
      preparedTransfers[1] = preparedSnapshot
    end

    local responseSignature = profileSyncLocalOps.buildPreparedProfileSyncResponseSignature(responseMode, requestDomains, requestSubdomains, preparedTransfers)
    local recentState = profileSyncResponseRuntime.requested.recent[requestKey]
    local now = GetNow()
    local recentSentAt = math.max(0, tonumber(type(recentState) == "table" and recentState.sentAt or 0) or 0)
    if type(recentState) == "table"
      and TrimText(recentState.signature) == responseSignature
      and (now - recentSentAt) < profileSyncConfig.localProfileStateDedupeSeconds
    then
      return true
    end

    local queuedAny = false
    for _, preparedSnapshot in ipairs(preparedTransfers) do
      profileSyncLocalOps.cancelQueuedPreparedSnapshotTransfer(resolvedSessionId, resolvedTarget, preparedSnapshot)
      local queued = SendPreparedProfileSnapshotBatch(preparedSnapshot, resolvedSessionId, { resolvedTarget }, {
        mode = responseMode,
        reason = responseReason,
      })
      if queued then
        queuedAny = true
      else
        return false
      end
    end

    if not queuedAny then
      return false
    end

    profileSyncResponseRuntime.requested.recent[requestKey] = {
      signature = responseSignature,
      sentAt = now,
    }
    profileSyncLocalOps.emitRequestedProfileSyncResponseNotice({
      sessionId = resolvedSessionId,
      profileName = activeProfileName,
      responseMode = responseMode,
      targetMemberKey = resolvedTarget,
      preparedTransferCount = #preparedTransfers,
      patchTransferCount = patchTransferCount,
      patchScopeCount = patchScopeCount,
    })
    return true
  end

  profileSyncLocalOps.cancelProfileSnapshotBatchForSession = function(sessionId)
    local resolvedSessionId = TrimText(sessionId)
    if resolvedSessionId == "" then
      return 0
    end
    -- Chunks do not carry a session id, so discard their staged transfer at the lifecycle boundary.
    local removedIncomingTransfers = INTERNAL_API.LIDCOUNCIL_FinalizeIncomingProfileSyncSessionState_Impl(
      profileSyncSessionState,
      resolvedSessionId,
      GetNow(),
      TrimText
    )
    local removed = 0
    local kept = {}
    for _, item in ipairs(profileSyncSessionState.pendingSnapshotBatch) do
      if TrimText(type(item) == "table" and item.sessionId or "") == resolvedSessionId then
        removed = removed + 1
      else
        kept[#kept + 1] = item
      end
    end
    profileSyncSessionState.pendingSnapshotBatch = kept
    profileSyncSessionState.snapshotBatchJoinHoldUntilBySession[resolvedSessionId] = nil
    profileSyncSessionState.snapshotBatchJoinHoldReasonBySession[resolvedSessionId] = nil
    if profileSyncSessionState.snapshotBatchPreferredSessionId == resolvedSessionId then
      profileSyncLocalOps.setSnapshotBatchPreferredSession("", 0)
    end
    local removedPreparedArchiveRepairs = 0
    for cacheKey, entry in pairs(type(profileSyncCaches.preparedArchiveRepairs) == "table"
      and profileSyncCaches.preparedArchiveRepairs or {}) do
      if TrimText(type(entry) == "table" and entry.sessionId or "") == resolvedSessionId then
        profileSyncCaches.preparedArchiveRepairs[cacheKey] = nil
        removedPreparedArchiveRepairs = removedPreparedArchiveRepairs + 1
      end
    end
    if removedPreparedArchiveRepairs > 0 then
      profileSyncSessionState.archivePreparationPrunedTotal = math.max(0,
        tonumber(profileSyncSessionState.archivePreparationPrunedTotal) or 0) + removedPreparedArchiveRepairs
    end
    local requestPrefix = string.lower(resolvedSessionId) .. "|"
    for requestKey in pairs(profileSyncCaches.pendingSubchecksumRequests) do
      if requestKey:sub(1, #requestPrefix) == requestPrefix then
        profileSyncCaches.pendingSubchecksumRequests[requestKey] = nil
      end
    end
    for requestKey in pairs(profileSyncCaches.pendingPatchManifestRequests) do
      if requestKey:sub(1, #requestPrefix) == requestPrefix then
        profileSyncCaches.pendingPatchManifestRequests[requestKey] = nil
      end
    end
    for requestKey in pairs(profileSyncCaches.pendingAutoPatchManifestTimers) do
      if requestKey:sub(1, #requestPrefix) == requestPrefix then
        profileSyncCaches.pendingAutoPatchManifestTimers[requestKey] = nil
      end
    end
    for requestKey in pairs(profileSyncResponseRuntime.precise.pendingSubchecksum) do
      if requestKey:sub(1, #requestPrefix) == requestPrefix then
        profileSyncResponseRuntime.precise.pendingSubchecksum[requestKey] = nil
      end
    end
    for requestKey in pairs(profileSyncResponseRuntime.precise.pendingPatchManifest) do
      if requestKey:sub(1, #requestPrefix) == requestPrefix then
        profileSyncResponseRuntime.precise.pendingPatchManifest[requestKey] = nil
      end
    end
    for requestKey in pairs(profileSyncResponseRuntime.requested.pending) do
      if requestKey:sub(1, #requestPrefix) == requestPrefix then
        profileSyncResponseRuntime.requested.pending[requestKey] = nil
      end
    end
    for requestKey in pairs(profileSyncResponseRuntime.inboundRequestWindows) do
      if requestKey:sub(1, #requestPrefix) == requestPrefix then
        profileSyncResponseRuntime.inboundRequestWindows[requestKey] = nil
      end
    end
    for tokenKey in pairs(profileSyncCaches.preciseResponseTokens) do
      if tokenKey:sub(1, #requestPrefix) == requestPrefix then
        profileSyncCaches.preciseResponseTokens[tokenKey] = nil
      end
    end
    for requestStamp in pairs(profileSyncCaches.patchManifestRequestTokensByStamp) do
      if requestStamp:sub(1, #requestPrefix) == requestPrefix then
        profileSyncCaches.patchManifestRequestTokensByStamp[requestStamp] = nil
      end
    end
    for requestKey in pairs(profileSyncCaches.preciseSubchecksumRequestStateByMember) do
      if requestKey:sub(1, #requestPrefix) == requestPrefix then
        profileSyncCaches.preciseSubchecksumRequestStateByMember[requestKey] = nil
      end
    end
    for dropKey in pairs(profileSyncCaches.preciseResponseDrops) do
      if dropKey:sub(1, #requestPrefix) == requestPrefix then
        profileSyncCaches.preciseResponseDrops[dropKey] = nil
      end
    end
    profileSyncCaches.memberSubchecksumBySession[string.lower(resolvedSessionId)] = nil
    profileSyncCaches.lootListDifferenceDiagnosticsBySession[string.lower(resolvedSessionId)] = nil
    profileSyncCaches.itemHistoryDifferenceDiagnosticsBySession[string.lower(resolvedSessionId)] = nil
    profileSyncCaches.sessionHistoryDifferenceDiagnosticsBySession[string.lower(resolvedSessionId)] = nil
    profileSyncCaches.pendingMemberSubchecksumPartsBySession[string.lower(resolvedSessionId)] = nil
    profileSyncCaches.memberPatchManifestBySession[string.lower(resolvedSessionId)] = nil
    profileSyncCaches.pendingMemberPatchManifestPartsBySession[string.lower(resolvedSessionId)] = nil
    generationOps.ClearSessionTransferGenerationState(resolvedSessionId)
    for stamp in pairs(profileSyncCaches.recentPatchManifestRequests) do
      if stamp:sub(1, #requestPrefix) == requestPrefix then
        profileSyncCaches.recentPatchManifestRequests[stamp] = nil
      end
    end
    for stamp in pairs(profileSyncCaches.recentSubchecksumRequests) do
      if stamp:sub(1, #requestPrefix) == requestPrefix then
        profileSyncCaches.recentSubchecksumRequests[stamp] = nil
      end
    end
    for stamp in pairs(profileSyncResponseRuntime.precise.recentSubchecksum) do
      if stamp:sub(1, #requestPrefix) == requestPrefix then
        profileSyncResponseRuntime.precise.recentSubchecksum[stamp] = nil
      end
    end
    for stamp in pairs(profileSyncResponseRuntime.precise.recentPatchManifest) do
      if stamp:sub(1, #requestPrefix) == requestPrefix then
        profileSyncResponseRuntime.precise.recentPatchManifest[stamp] = nil
      end
    end
    for stamp in pairs(profileSyncResponseRuntime.requested.recent) do
      if stamp:sub(1, #requestPrefix) == requestPrefix then
        profileSyncResponseRuntime.requested.recent[stamp] = nil
      end
    end
    return removed
  end

  SendProfileSyncAck = function(syncState, targetProfileName, revisionSummary, ackPhase)
    if type(syncState) ~= "table" or type(SendComm) ~= "function" then
      return false
    end
    local target = NormalizeCharacterKey(syncState.sender)
    if target == "" then
      return false
    end

    local profileName = TrimText(targetProfileName)
    if profileName == "" then
      profileName = TrimText(syncState.profileName)
    end
    local profileId = TrimText(select(1, GetLootProfileId(profileName)) or syncState.profileId or "")
    local summary = NormalizeRevisionSummary(revisionSummary or GetLootProfileRevisionSummary(profileName), profileName, profileId)
    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 sync acknowledgement phase."
    end
    local ackArgs = {
      TrimText(syncState.transferId),
      TrimText(syncState.sessionId),
      TrimText(syncState.profileName),
      profileId,
      tostring(math.max(0, tonumber(syncState.chunkCount) or 0)),
      tostring(summary.settings or 0),
      tostring(summary.permissions or 0),
      tostring(summary.operational or 0),
      tostring(summary.updatedAt or 0),
      TrimText(summary.settingsChecksum),
      TrimText(summary.permissionsChecksum),
      TrimText(summary.operationalChecksum),
      tostring(summary.loot or summary.operational or 0),
      tostring(summary.session or summary.operational or 0),
      TrimText(summary.lootChecksum),
      TrimText(summary.sessionChecksum),
      tostring(math.max(0, tonumber(type(syncState) == "table" and syncState.generation or 0) or 0)),
      resolvedAckPhase,
    }
    if type(sessionRuntimeOps.validateCommPayload) == "function" then
      local payloadSafe, payloadReason, payloadBytes = sessionRuntimeOps.validateCommPayload("PSYNC_ACK", unpack(ackArgs))
      if not payloadSafe then
        -- The receiver already falls back to operational checksums for these optional fields.
        ackArgs[15] = ""
        ackArgs[16] = ""
        payloadSafe, payloadReason, payloadBytes = sessionRuntimeOps.validateCommPayload("PSYNC_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 = sessionRuntimeOps.validateCommPayload("PSYNC_ACK", unpack(ackArgs))
      end
      if not payloadSafe then
        if type(sessionRuntimeOps.recordOutboundPayloadReject) == "function" then
          sessionRuntimeOps.recordOutboundPayloadReject("PSYNC_ACK", payloadReason, payloadBytes, {
            sessionId = syncState.sessionId,
            target = target,
          })
        end
        if type(RecordProfileSyncDecision) == "function" then
          RecordProfileSyncDecision("send_profile_sync_ack", {
            action = "failed",
            sessionId = TrimText(syncState.sessionId),
            profileName = TrimText(syncState.profileName),
            target = target,
            error = "Profile sync acknowledgement exceeds the safe addon-message limit.",
          })
        end
        return false, "Profile sync acknowledgement exceeds the safe addon-message limit."
      end
    end
    return SendComm("PSYNC_ACK", "WHISPER", target, unpack(ackArgs))
  end

  profileSyncLocalOps.buildCombatProfileBarrierKey = function(syncState, sender)
    syncState = type(syncState) == "table" and syncState or {}
    local resolvedSender = TrimText(sender) ~= "" and sender or syncState.sender
    return table.concat({
      string.lower(TrimText(syncState.sessionId)),
      string.lower(TrimText(syncState.profileId) ~= "" and TrimText(syncState.profileId) or TrimText(syncState.profileName)),
      string.lower(NormalizeSenderKey(resolvedSender)),
    }, "\31")
  end

  profileSyncLocalOps.buildCombatSnapshotStreamKey = function(syncState, sender)
    syncState = type(syncState) == "table" and syncState or {}
    local domains = CloneProfileSyncDomainList(syncState.scopeDomains)
    local subdomains = CloneProfileSyncSubdomainList(syncState.scopeSubdomains)
    for index, domain in ipairs(domains) do
      domains[index] = string.lower(TrimText(domain))
    end
    for index, subdomain in ipairs(subdomains) do
      subdomains[index] = string.lower(TrimText(subdomain))
    end
    table.sort(domains)
    table.sort(subdomains)
    return table.concat({
      profileSyncLocalOps.buildCombatProfileBarrierKey(syncState, sender),
      string.upper(TrimText(syncState.transferKind)),
      table.concat(domains, ","),
      table.concat(subdomains, ","),
    }, "\31")
  end

  profileSyncLocalOps.rememberAppliedCombatSnapshotGeneration = function(syncState, sender)
    syncState = type(syncState) == "table" and syncState or {}
    local generation = math.max(0, tonumber(syncState.generation) or 0)
    if generation <= 0 then
      return
    end
    local streamKey = profileSyncLocalOps.buildCombatSnapshotStreamKey(syncState, sender)
    if streamKey == "" then
      return
    end
    local previous = math.max(
      0,
      tonumber(profileSyncSessionState.appliedSnapshotGenerationByStream[streamKey]) or 0
    )
    profileSyncSessionState.appliedSnapshotGenerationByStream[streamKey] = math.max(previous, generation)
  end

  profileSyncLocalOps.stageIncomingProfileSnapshotApplyIfCombat = function(options)
    options = type(options) == "table" and options or {}
    local decision = type(INTERNAL_API.LIDCOUNCIL_ResolveCombatSyncDecision_Impl) == "function"
      and INTERNAL_API.LIDCOUNCIL_ResolveCombatSyncDecision_Impl("PSYNC_END")
      or nil
    if type(decision) ~= "table" or decision.stageData ~= true then
      return false, "immediate"
    end

    local syncState = type(options.syncState) == "table" and options.syncState or {}
    local queueEntry = type(INTERNAL_API.LIDCOUNCIL_QueueCombatSyncInboxEntry_Impl) == "function"
      and INTERNAL_API.LIDCOUNCIL_QueueCombatSyncInboxEntry_Impl
      or nil
    if type(queueEntry) ~= "function" then
      profileSyncLocalOps.emitProfileSyncRuntimeNotice({
        sessionId = syncState.sessionId,
        profileName = syncState.profileName,
        runtimeStateKey = "combat_snapshot_queue_unavailable",
        runtimeStateLevel = "warn",
        runtimeStateMessage = "The incoming profile update could not be staged during combat.",
        sender = options.sender,
        skipIfSame = true,
      })
      return true, "combat_inbox_unavailable"
    end

    local stagedSyncState = {
      transferId = TrimText(syncState.transferId),
      sessionId = TrimText(syncState.sessionId),
      profileName = TrimText(syncState.profileName),
      profileId = TrimText(syncState.profileId),
      sender = NormalizeSenderKey(
        TrimText(syncState.sender) ~= "" and syncState.sender or options.sender
      ),
      chunkCount = math.max(0, tonumber(syncState.chunkCount) or 0),
      hadLocalSharedProfile = syncState.hadLocalSharedProfile == true,
      liveSync = syncState.liveSync == true,
      reviewSync = syncState.reviewSync == true,
      previewSync = syncState.previewSync == true,
      scopeDomains = CloneProfileSyncDomainList(syncState.scopeDomains),
      scopeSubdomains = CloneProfileSyncSubdomainList(syncState.scopeSubdomains),
      transferKind = TrimText(syncState.transferKind),
      generation = math.max(0, tonumber(syncState.generation) or 0),
      lane = TrimText(syncState.lane),
    }
    local barrierKey = profileSyncLocalOps.buildCombatProfileBarrierKey(stagedSyncState, stagedSyncState.sender)
    local streamKey = profileSyncLocalOps.buildCombatSnapshotStreamKey(stagedSyncState, stagedSyncState.sender)
    local appliedGeneration = math.max(
      0,
      tonumber(profileSyncSessionState.appliedSnapshotGenerationByStream[streamKey]) or 0
    )
    local currentSummary = NormalizeRevisionSummary(
      GetLootProfileRevisionSummary(options.targetProfileName),
      options.targetProfileName,
      stagedSyncState.profileId
    )
    local comparedDomains = MergeProfileRevisionDomains(
      stagedSyncState.scopeDomains,
      type(options.previewSummary) == "table" and options.previewSummary.scopeDomains or {}
    )
    local remoteNewerDomains = profileSyncLocalOps.compareProfileRevisionSummaries(
      currentSummary,
      options.previewSummary,
      comparedDomains
    )
    if stagedSyncState.generation > 0
      and appliedGeneration >= stagedSyncState.generation
      and #remoteNewerDomains == 0
    then
      SendProfileSyncAck(
        stagedSyncState,
        options.targetProfileName,
        currentSummary,
        "APPLIED"
      )
      return true, "already_applied_generation"
    end
    local queued, queueReason = queueEntry({
      opcode = "PSYNC_END",
      sessionId = stagedSyncState.sessionId,
      profileName = stagedSyncState.profileName,
      profileId = stagedSyncState.profileId,
      sender = stagedSyncState.sender,
      transferId = stagedSyncState.transferId,
      generation = stagedSyncState.generation,
      versionStamp = math.max(
        0,
        tonumber(type(options.previewSummary) == "table" and options.previewSummary.updatedAt or 0) or 0
      ),
      streamKey = streamKey,
      barrierKey = barrierKey,
      orderingBarrier = true,
      supersedeOlder = true,
      completion = {
        syncState = stagedSyncState,
        targetProfileName = TrimText(options.targetProfileName),
      },
      payload = {
        syncState = stagedSyncState,
        targetProfileName = TrimText(options.targetProfileName),
        snapshotData = tostring(options.snapshotData or ""),
        previewSummary = type(options.previewSummary) == "table" and options.previewSummary or {},
        sender = stagedSyncState.sender,
        mode = TrimText(options.mode),
        successMessage = TrimText(options.successMessage),
        printMessage = TrimText(options.printMessage),
        remoteNewerDomains = CloneProfileSyncDomainList(options.remoteNewerDomains),
        localNewerDomains = CloneProfileSyncDomainList(options.localNewerDomains),
      },
    })
    if queued ~= true then
      profileSyncLocalOps.emitProfileSyncRuntimeNotice({
        sessionId = stagedSyncState.sessionId,
        profileName = stagedSyncState.profileName,
        runtimeStateKey = "combat_snapshot_queue_failed",
        runtimeStateLevel = "warn",
        runtimeStateMessage = "The incoming profile update exceeded the combat staging limits.",
        sender = stagedSyncState.sender,
        skipIfSame = true,
      })
      return true, queueReason
    end

    SendProfileSyncAck(stagedSyncState, options.targetProfileName, options.previewSummary, "QUEUED")
    return true, queueReason
  end

  profileSyncLocalOps.applyCombatStagedProfileSnapshot = function(entry)
    local payload = type(entry) == "table" and type(entry.payload) == "table" and entry.payload or nil
    local syncState = type(payload) == "table" and type(payload.syncState) == "table" and payload.syncState or nil
    if type(syncState) ~= "table" then
      return true, "invalid_staged_snapshot_discarded"
    end

    local activeSession, activeProfileName = GetActiveLootSession()
    if not sessionRuntimeOps.doesSessionMatch(
      activeSession,
      activeProfileName,
      syncState.sessionId,
      syncState.profileName
    ) then
      return true, "stale_session_discarded"
    end
    local senderKey = NormalizeSenderKey(payload.sender or syncState.sender)
    if syncState.liveSync or syncState.reviewSync or syncState.previewSync then
      if not sessionRuntimeOps.isJoinedCharacter(activeSession, senderKey) then
        return true, "departed_sender_discarded"
      end
    elseif not sessionRuntimeOps.isHostSender(activeSession, senderKey) then
      return true, "stale_host_discarded"
    end

    local targetProfileName = TrimText(payload.targetProfileName)
    if targetProfileName == "" or string.lower(targetProfileName) ~= string.lower(TrimText(activeProfileName)) then
      return true, "stale_profile_discarded"
    end
    local function queueCompletionReceipts(revisionSummary)
      local receiptQueued, receiptReason = SendProfileSyncAck(
        syncState,
        targetProfileName,
        revisionSummary,
        "APPLIED"
      )
      if receiptQueued ~= true then
        return false, FirstNonEmptyText(receiptReason, "profile_sync_applied_receipt_not_queued")
      end
      for _, completion in ipairs(
        type(entry) == "table" and type(entry.coveredCompletions) == "table"
          and entry.coveredCompletions or {}
      ) do
        local coveredSyncState = type(completion) == "table"
          and type(completion.syncState) == "table"
          and completion.syncState
          or nil
        if type(coveredSyncState) == "table" then
          local coveredQueued, coveredReason = SendProfileSyncAck(
            coveredSyncState,
            TrimText(completion.targetProfileName),
            nil,
            "APPLIED"
          )
          if coveredQueued ~= true then
            return false, FirstNonEmptyText(coveredReason, "covered_profile_sync_applied_receipt_not_queued")
          end
        end
      end
      return true, "applied_receipts_queued"
    end
    local appliedGeneration = math.max(0, tonumber(syncState.generation) or 0)
    local streamKey = profileSyncLocalOps.buildCombatSnapshotStreamKey(syncState, senderKey)
    local rememberedGeneration = math.max(
      0,
      tonumber(profileSyncSessionState.appliedSnapshotGenerationByStream[streamKey]) or 0
    )
    if appliedGeneration > 0 and rememberedGeneration >= appliedGeneration then
      return queueCompletionReceipts(GetLootProfileRevisionSummary(targetProfileName))
    end
    local applyOptions = {
      activeSession = activeSession,
      syncState = syncState,
      targetProfileName = targetProfileName,
      snapshotData = tostring(payload.snapshotData or ""),
      previewSummary = type(payload.previewSummary) == "table" and payload.previewSummary or {},
      sender = senderKey,
      mode = TrimText(payload.mode),
      successMessage = TrimText(payload.successMessage),
      printMessage = TrimText(payload.printMessage),
      remoteNewerDomains = CloneProfileSyncDomainList(payload.remoteNewerDomains),
      localNewerDomains = CloneProfileSyncDomainList(payload.localNewerDomains),
      deferAcknowledgement = true,
    }
    if applyOptions.mode == "review_snapshot_applied" then
      applyOptions.reviewSyncDetailDiff = profileSyncLocalOps.buildTransferDiff(
        targetProfileName,
        applyOptions.snapshotData
      )
    end
    local applied, applyReason = profileSyncLocalOps.applyIncomingProfileSnapshot(applyOptions)
    if applied == true then
      return queueCompletionReceipts(GetLootProfileRevisionSummary(targetProfileName))
    end
    return applied, applyReason
  end

  local function HandleProfileSyncStart(fields, sender)
    local payload, payloadError = sessionRuntimeOps.parseInboundProfileSyncStartPayload(fields, sender)
    if type(payload) ~= "table" then
      sessionRuntimeOps.recordInboundPayloadReject("PSYNC_START", sender, fields, payloadError)
      return
    end
    local transferId = payload.transferId
    local sessionId = payload.sessionId
    local profileName = payload.profileName
    local profileId = payload.profileId
    local chunkCount = payload.chunkCount
    local syncMode = payload.syncMode
    local requestedDomains = payload.requestedDomains
    local transferKind = payload.transferKind
    local requestedSubdomains = payload.requestedSubdomains
    local transferGeneration = payload.transferGeneration
    local transferLane = payload.transferLane
    local hostAuthoritativeOverride = payload.hostAuthoritativeOverride == true
    local isLiveSync = syncMode == "LIVE"
    local isReviewSync = syncMode == "REVIEW"
    local isPreviewSync = syncMode == "PREVIEW"

    local activeSession, activeProfileName = GetActiveLootSession()
    if not activeSession or activeSession.id ~= sessionId then
      return
    end
    local senderKey = payload.senderKey
    if not sessionRuntimeOps.isCurrentGroupCharacter(senderKey) then
      return
    end
    if isLiveSync or isReviewSync or isPreviewSync then
      if not sessionRuntimeOps.isJoinedCharacter(activeSession, senderKey) then
        return
      end
    elseif not sessionRuntimeOps.isHostSender(activeSession, sender) then
      return
    end

    local allowed, admissionReason = profileSyncLocalOps.allowInboundResponseRequest(sessionId, senderKey, "PSYNC_START")
    if not allowed then
      sessionRuntimeOps.recordInboundPayloadReject("PSYNC_START", sender, fields, admissionReason)
      return
    end

    local now = GetNow()
    profileSyncLocalOps.beginIncomingSnapshotDiagnosticsForSession(sessionId, now)
    profileSyncLocalOps.pruneIncomingProfileSyncs(now)
    local existingSyncState = profileSyncSessionState.pendingProfileSyncs[transferId]
    if type(existingSyncState) == "table" then
      sessionRuntimeOps.recordInboundPayloadReject("PSYNC_START", sender, fields, "profile_sync_transfer_id_collision")
      return
    end
    local canStart, capacityReason = profileSyncLocalOps.canStartIncomingProfileSync(senderKey, now)
    if not canStart then
      sessionRuntimeOps.recordInboundPayloadReject("PSYNC_START", sender, fields, capacityReason)
      return
    end

    profileSyncSessionState.pendingProfileSyncs[transferId] = {
      transferId = transferId,
      sessionId = sessionId,
      profileName = profileName,
      profileId = profileId,
      targetProfileName = TrimText(activeProfileName),
      sender = senderKey,
      mode = syncMode,
      chunkCount = chunkCount,
      chunks = {},
      hadLocalSharedProfile = false,
      localRevisionSummary = nil,
      liveSync = isLiveSync,
      reviewSync = isReviewSync,
      previewSync = isPreviewSync,
      scopeDomains = requestedDomains,
      scopeSubdomains = requestedSubdomains,
      transferKind = transferKind ~= "" and transferKind or "FULL",
      generation = transferGeneration,
      lane = transferLane ~= "" and transferLane or generationOps.NormalizeProfileTransferLane("", requestedSubdomains, transferKind),
      hostAuthoritativeOverride = hostAuthoritativeOverride,
      startedAt = now,
      updatedAt = now,
      receivedBytes = 0,
      receivedChunkCount = 0,
    }

    local existingSharedProfileName = TrimText(profileId ~= "" and deps.FindLootProfileNameById(profileId) or "")
    if existingSharedProfileName ~= "" then
      profileSyncSessionState.pendingProfileSyncs[transferId].hadLocalSharedProfile = true
      profileSyncSessionState.pendingProfileSyncs[transferId].localRevisionSummary = NormalizeRevisionSummary(
        GetLootProfileRevisionSummary(existingSharedProfileName),
        existingSharedProfileName,
        profileId
      )
    else
      profileSyncSessionState.pendingProfileSyncs[transferId].localRevisionSummary = BuildEmptyRevisionSummary(activeProfileName, profileId)
    end
  end

  local function HandleProfileSyncRequest(fields, sender)
    local payload, payloadError = sessionRuntimeOps.parseInboundProfileSyncRequestPayload(fields, sender)
    if type(payload) ~= "table" then
      sessionRuntimeOps.recordInboundPayloadReject("PSYNC_REQ", sender, fields, payloadError)
      return
    end
    local sessionId = payload.sessionId
    local profileName = payload.profileName
    local profileId = payload.profileId

    local activeSession, activeProfileName = GetActiveLootSession()
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if not sessionRuntimeOps.doesSessionMatch(activeSession, activeProfileName, sessionId, profileName) then
      return
    end
    if not sessionRuntimeOps.isHostSender(activeSession, sender) then
      return
    end
    if not sessionRuntimeOps.isCurrentGroupCharacter(payload.senderKey) then
      return
    end
    if selfKey == "" or not sessionRuntimeOps.isJoinedCharacter(activeSession, selfKey) then
      return
    end

    local localProfileId = TrimText(select(1, GetLootProfileId(activeProfileName)) or "")
    if profileId ~= "" and localProfileId ~= "" and string.lower(profileId) ~= string.lower(localProfileId) then
      return
    end
    local allowed, admissionReason = profileSyncLocalOps.allowInboundResponseRequest(sessionId, payload.senderKey, "PSYNC_REQ")
    if not allowed then
      sessionRuntimeOps.recordInboundPayloadReject("PSYNC_REQ", sender, fields, admissionReason)
      return
    end
    profileSyncLocalOps.queueRequestedProfileSyncResponse(
      sessionId,
      activeProfileName,
      payload.senderKey,
      payload.requestMode,
      payload.requestDomains,
      payload.requestSubdomains,
      payload.expectedPatchManifestToken
    )
  end

  local function HandleProfileSubchecksumRequest(fields, sender)
    local payload, payloadError = sessionRuntimeOps.parseInboundProfileSubchecksumRequestPayload(fields, sender)
    if type(payload) ~= "table" then
      sessionRuntimeOps.recordInboundPayloadReject("PSUB_REQ", sender, fields, payloadError)
      return
    end
    local sessionId = payload.sessionId
    local profileName = payload.profileName
    local profileId = payload.profileId
    local requestedDomains = payload.requestedDomains

    local activeSession, activeProfileName = GetActiveLootSession()
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if not sessionRuntimeOps.doesSessionMatch(activeSession, activeProfileName, sessionId, profileName) then
      return
    end
    if not sessionRuntimeOps.isHostSender(activeSession, sender) then
      return
    end
    if not sessionRuntimeOps.isCurrentGroupCharacter(payload.senderKey) then
      return
    end
    if selfKey == "" or not sessionRuntimeOps.isJoinedCharacter(activeSession, selfKey) then
      return
    end

    local localProfileId = TrimText(select(1, GetLootProfileId(activeProfileName)) or "")
    if profileId ~= "" and localProfileId ~= "" and string.lower(profileId) ~= string.lower(localProfileId) then
      return
    end

    if localProfileId == "" then
      return
    end

    local allowed, admissionReason = profileSyncLocalOps.allowInboundResponseRequest(sessionId, payload.senderKey, "PSUB_REQ")
    if not allowed then
      sessionRuntimeOps.recordInboundPayloadReject("PSUB_REQ", sender, fields, admissionReason)
      return
    end

    profileSyncLocalOps.queueProfileSubchecksumResponse(
      sessionId,
      activeProfileName,
      payload.senderKey,
      requestedDomains,
      payload.requestToken
    )
    -- A checksum request does not mutate local profile state. Initial admission,
    -- completed apply, and explicit readiness actions own PSTATE publication;
    -- replying with leaf evidence must not create a PSTATE/MEMBER feedback edge.
  end

  local function HandleProfileSubchecksumState(fields, sender)
    local payload, payloadError = sessionRuntimeOps.parseInboundProfileSubchecksumStatePayload(fields, sender)
    if type(payload) ~= "table" then
      sessionRuntimeOps.recordInboundPayloadReject("PSUB_STATE", sender, fields, payloadError)
      return
    end
    local sessionId = payload.sessionId
    local profileName = payload.profileName
    local profileId = payload.profileId
    local domain = payload.domain
    local domainChecksum = payload.domainChecksum
    local encodedSubchecks = payload.encodedSubchecks
    local responseToken = payload.responseToken
    local partIndex = payload.partIndex
    local partTotal = payload.partTotal

    local activeSession, activeProfileName = GetActiveLootSession()
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if not sessionRuntimeOps.doesSessionMatch(activeSession, activeProfileName, sessionId, profileName) then
      return
    end
    if selfKey == "" then
      return
    end

    local senderKey = payload.senderKey
    local selfIsHost = sessionRuntimeOps.isHostSender(activeSession, selfKey)
    if selfIsHost then
      if not sessionRuntimeOps.isJoinedCharacter(activeSession, senderKey) then
        return
      end
    else
      if not sessionRuntimeOps.isHostSender(activeSession, sender) then
        return
      end
      if not sessionRuntimeOps.isJoinedCharacter(activeSession, selfKey) then
        return
      end
    end
    if senderKey == "" then
      return
    end

    if not profileSyncLocalOps.isCurrentPreciseResponseToken(
      sessionId,
      senderKey,
      "PSUB",
      { domain },
      payload.requestToken
    ) then
      return
    end

    local preciseProgressed = true
    if responseToken ~= "" and partTotal > 1 then
      encodedSubchecks, preciseProgressed = RememberPendingMemberSubchecksumPayload(
        sessionId,
        senderKey,
        domain,
        responseToken,
        partIndex,
        partTotal,
        encodedSubchecks
      )
      if preciseProgressed then
        profileSyncLocalOps.markPreciseSubchecksumProgress(sessionId, senderKey, payload.requestToken)
      end
      if encodedSubchecks == nil then
        return
      end
    else
      profileSyncLocalOps.markPreciseSubchecksumProgress(sessionId, senderKey, payload.requestToken)
    end

    local _, subchecksumStateChanged = RememberMemberSubchecksumState(
      sessionId,
      senderKey,
      profileName,
      profileId,
      domain,
      domainChecksum,
      DecodeProfileSyncSubchecks(domain, encodedSubchecks)
    )
    local preciseReceiptChanged, preciseRequestComplete = profileSyncLocalOps.markPreciseSubchecksumResponse(
      sessionId,
      senderKey,
      domain,
      payload.requestToken
    )
    if subchecksumStateChanged then
      local patchCache = GetMemberPatchManifestSessionCache(sessionId, false)
      if type(patchCache) == "table" then
        patchCache[string.lower(senderKey)] = nil
      end
      local patchRequestPrefix = string.lower(TrimText(sessionId)) .. "|" .. string.lower(senderKey) .. "|"
      for stamp in pairs(profileSyncCaches.recentPatchManifestRequests) do
        if stamp:sub(1, #patchRequestPrefix) == patchRequestPrefix then
          profileSyncCaches.recentPatchManifestRequests[stamp] = nil
        end
      end
      for stamp in pairs(profileSyncCaches.patchManifestRequestTokensByStamp) do
        if stamp:sub(1, #patchRequestPrefix) == patchRequestPrefix then
          profileSyncCaches.patchManifestRequestTokensByStamp[stamp] = nil
        end
      end
    end
    local senderCandidate = nil
    for _, candidate in ipairs(GetActiveProfileSyncCandidates() or {}) do
      if NormalizeCharacterKey(type(candidate) == "table" and candidate.memberKey or "") == senderKey then
        senderCandidate = candidate
        break
      end
    end
    if subchecksumStateChanged
      and type(senderCandidate) == "table"
      and senderCandidate.patchPushReady ~= true
      and type(senderCandidate.patchPushSubdomains) == "table"
      and #senderCandidate.patchPushSubdomains > 0
    then
      profileSyncLocalOps.queueAutoPatchManifestRequest(senderKey, senderCandidate.patchPushSubdomains)
    end
    if not subchecksumStateChanged and not preciseReceiptChanged and not preciseRequestComplete then
      return
    end
    profileSyncLocalOps.emitPreciseProfileSyncLoadNotice({
      sessionId = sessionId,
      profileName = activeProfileName,
      sender = senderKey,
      kind = "subchecks",
      domain = domain,
    })
    if selfIsHost and preciseRequestComplete then
      if subchecksumStateChanged or preciseReceiptChanged then
        profileSyncLocalOps.updateMemberLootListDifferenceDiagnostics(
          activeSession,
          activeProfileName,
          senderKey
        )
        profileSyncLocalOps.updateMemberItemHistoryDifferenceDiagnostics(
          activeSession,
          activeProfileName,
          senderKey
        )
        profileSyncLocalOps.updateMemberSessionHistoryDifferenceDiagnostics(
          activeSession,
          activeProfileName,
          senderKey
        )
      end
      local publishReadiness = INTERNAL_API.LIDCOUNCIL_HandleReadinessProofUpdated_Impl
      if type(publishReadiness) == "function" then
        pcall(publishReadiness, sessionId, senderKey)
      end
    end
  end

  local function HandleProfileSubdomainPatchManifestRequest(fields, sender)
    local payload, payloadError = sessionRuntimeOps.parseInboundProfilePatchManifestRequestPayload(fields, sender)
    if type(payload) ~= "table" then
      sessionRuntimeOps.recordInboundPayloadReject("PSUBPATCH_REQ", sender, fields, payloadError)
      return
    end
    local sessionId = payload.sessionId
    local profileName = payload.profileName
    local profileId = payload.profileId
    local requestedSubdomains = payload.requestedSubdomains

    local activeSession, activeProfileName = GetActiveLootSession()
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if not sessionRuntimeOps.doesSessionMatch(activeSession, activeProfileName, sessionId, profileName) then
      return
    end
    if not sessionRuntimeOps.isHostSender(activeSession, sender) then
      return
    end
    if not sessionRuntimeOps.isCurrentGroupCharacter(payload.senderKey) then
      return
    end
    if selfKey == "" or not sessionRuntimeOps.isJoinedCharacter(activeSession, selfKey) then
      return
    end

    local localProfileId = TrimText(select(1, GetLootProfileId(activeProfileName)) or "")
    if profileId ~= "" and localProfileId ~= "" and string.lower(profileId) ~= string.lower(localProfileId) then
      return
    end

    if localProfileId == "" then
      return
    end

    local allowed, admissionReason = profileSyncLocalOps.allowInboundResponseRequest(sessionId, payload.senderKey, "PSUBPATCH_REQ")
    if not allowed then
      sessionRuntimeOps.recordInboundPayloadReject("PSUBPATCH_REQ", sender, fields, admissionReason)
      return
    end

    profileSyncLocalOps.queueProfilePatchManifestResponse(
      sessionId,
      activeProfileName,
      payload.senderKey,
      requestedSubdomains,
      payload.requestToken
    )
  end

  local function HandleProfileSubdomainPatchManifestState(fields, sender)
    local payload, payloadError = sessionRuntimeOps.parseInboundProfilePatchManifestStatePayload(fields, sender)
    if type(payload) ~= "table" then
      sessionRuntimeOps.recordInboundPayloadReject("PSUBPATCH_STATE", sender, fields, payloadError)
      return
    end
    local sessionId = payload.sessionId
    local profileName = payload.profileName
    local profileId = payload.profileId
    local responseToken = payload.responseToken
    local requestToken = payload.requestToken
    local partIndex = payload.partIndex
    local partTotal = payload.partTotal
    local chunkPayload = payload.chunkPayload

    local activeSession, activeProfileName = GetActiveLootSession()
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if not sessionRuntimeOps.doesSessionMatch(activeSession, activeProfileName, sessionId, profileName) then
      return
    end
    if selfKey == "" or not sessionRuntimeOps.isHostSender(activeSession, selfKey) then
      return
    end

    local senderKey = payload.senderKey
    if not sessionRuntimeOps.isJoinedCharacter(activeSession, senderKey) then
      return
    end
    local localProfileId = TrimText(select(1, GetLootProfileId(activeProfileName)) or "")
    if profileId ~= "" and localProfileId ~= "" and string.lower(profileId) ~= string.lower(localProfileId) then
      return
    end
    if not profileSyncLocalOps.isKnownPreciseResponseToken(
      sessionId,
      senderKey,
      "PSUBPATCH",
      requestToken
    ) then
      return
    end

    local manifestData = chunkPayload
    if responseToken ~= "" and partTotal > 1 then
      manifestData = RememberPendingMemberPatchManifestPayload(sessionId, senderKey, responseToken, partIndex, partTotal, chunkPayload)
      if manifestData == nil then
        return
      end
    end

    local manifestSummary = type(snapshotTransferOps.previewPatchManifest) == "function"
      and snapshotTransferOps.previewPatchManifest(manifestData)
      or nil
    if type(manifestSummary) ~= "table" then
      return
    end

    local manifestSubdomains = type(FilterLootProfilePatchCapableSubdomains) == "function"
      and FilterLootProfilePatchCapableSubdomains(manifestSummary.scopeSubdomains)
      or CloneProfileSyncSubdomainList(manifestSummary.scopeSubdomains)
    if not profileSyncLocalOps.isCurrentPreciseResponseToken(
      sessionId,
      senderKey,
      "PSUBPATCH",
      manifestSubdomains,
      requestToken
    ) then
      return
    end

    local _, patchManifestChanged = RememberMemberPatchManifestState(
      sessionId,
      senderKey,
      profileName,
      profileId,
      manifestSummary,
      responseToken
    )
    if not patchManifestChanged then
      return
    end
    profileSyncLocalOps.emitPreciseProfileSyncLoadNotice({
      sessionId = sessionId,
      profileName = activeProfileName,
      sender = senderKey,
      kind = "patch_manifest",
    })
  end

  local function HandleProfileSyncChunk(fields, sender)
    local payload, payloadError = sessionRuntimeOps.parseInboundProfileSyncChunkPayload(fields, sender)
    if type(payload) ~= "table" then
      sessionRuntimeOps.recordInboundPayloadReject("PSYNC_CHUNK", sender, fields, payloadError)
      return
    end
    local transferId = payload.transferId
    local chunkIndex = payload.chunkIndex
    local chunkData = payload.chunkData
    profileSyncLocalOps.pruneIncomingProfileSyncs(GetNow())
    local syncState, transferReason = INTERNAL_API.LIDCOUNCIL_ResolveIncomingProfileSyncTransfer_Impl(
      profileSyncSessionState.pendingProfileSyncs,
      transferId,
      payload.senderKey,
      TrimText
    )
    if type(syncState) ~= "table" then
      if transferReason == "sender_mismatch" then
        sessionRuntimeOps.recordInboundPayloadReject(
          "PSYNC_CHUNK",
          sender,
          fields,
          "profile_sync_sender_mismatch",
          type(profileSyncSessionState.pendingProfileSyncs[transferId]) == "table"
            and profileSyncSessionState.pendingProfileSyncs[transferId].sessionId or nil
        )
      end
      return
    end
    local accepted, chunkReason = INTERNAL_API.LIDCOUNCIL_ApplyIncomingProfileSyncChunk_Impl(
      syncState,
      chunkIndex,
      chunkData,
      profileSyncConfig.maxIncomingSnapshotChunkBytes,
      profileSyncConfig.maxIncomingSnapshotBytes,
      GetNow()
    )
    if not accepted then
      profileSyncSessionState.pendingProfileSyncs[transferId] = nil
      sessionRuntimeOps.recordInboundPayloadReject("PSYNC_CHUNK", sender, fields, chunkReason, syncState.sessionId)
      return
    end
  end

  local function HandleProfileSyncEnd(fields, sender)
    local payload, payloadError = sessionRuntimeOps.parseInboundProfileSyncEndPayload(fields, sender)
    if type(payload) ~= "table" then
      sessionRuntimeOps.recordInboundPayloadReject("PSYNC_END", sender, fields, payloadError)
      return
    end
    local transferId = payload.transferId
    profileSyncLocalOps.pruneIncomingProfileSyncs(GetNow())
    local syncState, transferReason = INTERNAL_API.LIDCOUNCIL_ResolveIncomingProfileSyncTransfer_Impl(
      profileSyncSessionState.pendingProfileSyncs,
      transferId,
      payload.senderKey,
      TrimText
    )
    if type(syncState) ~= "table" then
      if transferReason == "sender_mismatch" then
        sessionRuntimeOps.recordInboundPayloadReject(
          "PSYNC_END",
          sender,
          fields,
          "profile_sync_sender_mismatch",
          type(profileSyncSessionState.pendingProfileSyncs[transferId]) == "table"
            and profileSyncSessionState.pendingProfileSyncs[transferId].sessionId or nil
        )
      end
      return
    end
    profileSyncSessionState.pendingProfileSyncs[transferId] = nil

    local activeSession, activeProfileName = GetActiveLootSession()
    if not activeSession or activeSession.id ~= syncState.sessionId then
      return
    end
    if syncState.liveSync or syncState.reviewSync or syncState.previewSync then
      if not sessionRuntimeOps.isJoinedCharacter(activeSession, NormalizeSenderKey(sender)) then
        return
      end
    elseif not sessionRuntimeOps.isHostSender(activeSession, sender) then
      return
    end

    if math.max(0, tonumber(syncState.receivedChunkCount) or 0) ~= math.max(0, tonumber(syncState.chunkCount) or 0) then
      if type(activeSession) == "table" and activeSession.id == syncState.sessionId then
        activeSession.sharedProfileReady = false
      end
      profileSyncLocalOps.emitProfileSyncRuntimeNotice({
        sessionId = syncState.sessionId,
        profileName = syncState.profileName,
        runtimeStateKey = "host_snapshot_incomplete",
        runtimeStateLevel = "warn",
        runtimeStateMessage = "The host snapshot was incomplete. Ask the host to resend the shared profile update.",
        sender = sender,
        skipIfSame = true,
        printMessage = "The shared profile snapshot from the session host was incomplete. Ask the host to use Push Host Repair or resend the invite.",
      })
      return
    end

    local parts = {}
    for index = 1, tonumber(syncState.chunkCount) or 0 do
      local chunk = syncState.chunks[index]
      if type(chunk) ~= "string" then
        if type(activeSession) == "table" and activeSession.id == syncState.sessionId then
          activeSession.sharedProfileReady = false
        end
        profileSyncLocalOps.emitProfileSyncRuntimeNotice({
          sessionId = syncState.sessionId,
          profileName = syncState.profileName,
          runtimeStateKey = "host_snapshot_incomplete",
          runtimeStateLevel = "warn",
          runtimeStateMessage = "The host snapshot was incomplete. Ask the host to resend the shared profile update.",
          sender = sender,
          skipIfSame = true,
          printMessage = "The shared profile snapshot from the session host was incomplete. Ask the host to use Push Host Repair or resend the invite.",
        })
        return
      end
      parts[#parts + 1] = chunk
    end

    local targetProfileName = profileSyncLocalOps.resolveIncomingProfileSyncTargetProfileName(syncState, activeProfileName)
    if targetProfileName == "" then
      return
    end

    local snapshotData = table.concat(parts)
    local previewSummary = profileSyncLocalOps.previewTransferSnapshot(snapshotData)
    if type(previewSummary) ~= "table" then
      profileSyncLocalOps.printIncomingProfileSyncValidationNotice("inspect_failed")
      return
    end
    if syncState.profileId ~= "" and previewSummary.profileId ~= "" and string.lower(previewSummary.profileId) ~= string.lower(syncState.profileId) then
      profileSyncLocalOps.printIncomingProfileSyncValidationNotice("identity_mismatch")
      return
    end

    local comparedDomains = MergeProfileRevisionDomains(syncState.scopeDomains, previewSummary.scopeDomains)
    local reviewState = profileSyncLocalOps.buildIncomingProfileSnapshotReviewState(
      syncState,
      sender,
      targetProfileName,
      snapshotData,
      previewSummary,
      comparedDomains
    )
    local remoteNewerDomains = CloneProfileSyncDomainList(reviewState.remoteNewerDomains or {})
    local localNewerDomains = CloneProfileSyncDomainList(reviewState.localNewerDomains or {})

    if syncState.previewSync then
      profileSyncLocalOps.publishIncomingProfileSnapshotPreview(syncState, sender, snapshotData, previewSummary, reviewState)
      return
    end

    if syncState.reviewSync then
      local reviewApplyMessage = profileSyncLocalOps.buildIncomingProfileApplyRuntimeMessage("review_snapshot_applied", syncState.profileName, sender)
      local applyOptions = {
        activeSession = activeSession,
        syncState = syncState,
        targetProfileName = targetProfileName,
        snapshotData = snapshotData,
        previewSummary = previewSummary,
        sender = sender,
        mode = "review_snapshot_applied",
        successMessage = reviewApplyMessage,
        printMessage = profileSyncLocalOps.buildIncomingProfileApplyPrintMessage("review_snapshot_applied", syncState.profileName, sender),
        remoteNewerDomains = remoteNewerDomains,
        localNewerDomains = localNewerDomains,
        reviewSyncDetailDiff = reviewState.detailDiff,
      }
      if profileSyncLocalOps.stageIncomingProfileSnapshotApplyIfCombat(applyOptions) then
        return
      end
      if not profileSyncLocalOps.applyIncomingProfileSnapshot(applyOptions) then
        return
      end
      return
    end

    -- Deferred archive scopes and explicitly confirmed host overrides apply without
    -- presenting a false local-vs-host conflict. The override marker is honored only
    -- when the active session host sent it.
    local activeHostOverride = profileSyncLocalOps.isActiveHostAuthoritativeOverride(
      syncState,
      activeSession,
      sender
    )
    if not syncState.hadLocalSharedProfile
      or syncState.mode == "BACKGROUND" and sessionRuntimeOps.isHostSender(activeSession, sender)
      or activeHostOverride then
      local automaticApplyMode = activeHostOverride and "host_override_applied"
        or (syncState.mode == "BACKGROUND" and "background_host_applied" or "received_missing_copy")
      local applyOptions = {
        activeSession = activeSession,
        syncState = syncState,
        targetProfileName = targetProfileName,
        snapshotData = snapshotData,
        previewSummary = previewSummary,
        sender = sender,
        mode = automaticApplyMode,
        successMessage = profileSyncLocalOps.buildIncomingProfileApplyRuntimeMessage(
          automaticApplyMode,
          syncState.profileName,
          sender
        ),
        printMessage = profileSyncLocalOps.buildIncomingProfileApplyPrintMessage(
          automaticApplyMode,
          syncState.profileName,
          sender
        ),
        remoteNewerDomains = remoteNewerDomains,
        localNewerDomains = localNewerDomains,
        reviewSyncDetailDiff = reviewState.detailDiff,
      }
      if profileSyncLocalOps.stageIncomingProfileSnapshotApplyIfCombat(applyOptions) then
        return
      end
      if not profileSyncLocalOps.applyIncomingProfileSnapshot(applyOptions) then
        return
      end
      return
    end

    local localRevisionSummary = NormalizeRevisionSummary(syncState.localRevisionSummary, targetProfileName, syncState.profileId)
    remoteNewerDomains, localNewerDomains = profileSyncLocalOps.compareProfileRevisionSummaries(localRevisionSummary, previewSummary, comparedDomains)

    if syncState.liveSync then
      if #remoteNewerDomains == 0 then
        if #localNewerDomains == 0 then
          -- Live snapshots that were already applied still need to close the sender's ACK loop.
          SendProfileSyncAck(syncState, targetProfileName, previewSummary, "APPLIED")
        end
        return
      end
      local applyOptions = {
        activeSession = activeSession,
        syncState = syncState,
        targetProfileName = targetProfileName,
        snapshotData = snapshotData,
        previewSummary = previewSummary,
        sender = sender,
        mode = "live_update_applied",
        successMessage = profileSyncLocalOps.buildIncomingProfileApplyRuntimeMessage("live_update_applied", syncState.profileName, sender),
        remoteNewerDomains = remoteNewerDomains,
        localNewerDomains = localNewerDomains,
        reviewSyncDetailDiff = reviewState.detailDiff,
      }
      if profileSyncLocalOps.stageIncomingProfileSnapshotApplyIfCombat(applyOptions) then
        return
      end
      profileSyncLocalOps.applyIncomingProfileSnapshot(applyOptions)
      return
    end

    if #remoteNewerDomains == 0 then
      if #localNewerDomains > 0 then
        profileSyncLocalOps.emitProfileSyncRuntimeNotice({
          sessionId = syncState.sessionId,
          profileName = syncState.profileName,
          runtimeStateKey = "kept_local_newer",
          runtimeStateLevel = "info",
          runtimeStateMessage = "Kept your local shared profile copy because it is newer than the host copy.",
          sender = sender,
          localDomains = localNewerDomains,
          skipIfSame = true,
          printMessage = "Kept your local shared profile copy for \"" .. tostring(syncState.profileName) .. "\" because it is newer than the session host version.",
        })
      else
        -- The sender still needs a receipt when this scope was already aligned.
        SendProfileSyncAck(syncState, targetProfileName, previewSummary, "APPLIED")
      end
      return
    end

    if #localNewerDomains > 0 then
      profileSyncLocalOps.emitProfileSyncRuntimeNotice({
        sessionId = syncState.sessionId,
        profileName = syncState.profileName,
        runtimeStateKey = "diverged_local_and_host",
        runtimeStateLevel = "warn",
        runtimeStateMessage = "Kept your local shared profile copy because both versions changed.",
        sender = sender,
        remoteDomains = remoteNewerDomains,
        localDomains = localNewerDomains,
        skipIfSame = true,
        printMessage = "Kept your local shared profile copy for \"" .. tostring(syncState.profileName) .. "\" because both versions changed."
          .. " Host newer: " .. profileSyncLocalOps.formatProfileRevisionDomains(remoteNewerDomains)
          .. ". Local newer: " .. profileSyncLocalOps.formatProfileRevisionDomains(localNewerDomains) .. ".",
      })
      return
    end

    local runtimeStateChanged = profileSyncLocalOps.emitProfileSyncRuntimeNotice({
      sessionId = syncState.sessionId,
      profileName = syncState.profileName,
      runtimeStateKey = "update_available",
      runtimeStateLevel = "warn",
      runtimeStateMessage = "A newer host shared profile update is ready for review.",
      sender = sender,
      remoteDomains = remoteNewerDomains,
      skipIfSame = true,
      printMessage = "A newer shared profile update is available from the session host for \"" .. tostring(syncState.profileName)
        .. "\". Review the popup to accept it or keep your local copy.",
    })
    if runtimeStateChanged then
      ShowProfileSyncPopup({
        sessionId = syncState.sessionId,
        profileName = syncState.profileName,
        targetProfileName = targetProfileName,
        profileId = syncState.profileId,
        sender = NormalizeSenderKey(sender),
        snapshotData = snapshotData,
        transferKind = previewSummary.transferKind,
        remoteDomainText = profileSyncLocalOps.formatProfileRevisionDomains(remoteNewerDomains),
        remoteDomains = CloneProfileSyncDomainList(remoteNewerDomains),
      })
    end
  end

  local function HandleProfileSyncAck(fields, sender)
    local payload, payloadError = sessionRuntimeOps.parseInboundProfileSyncAckPayload(fields, sender)
    if type(payload) ~= "table" then
      sessionRuntimeOps.recordInboundPayloadReject("PSYNC_ACK", sender, fields, payloadError)
      return
    end
    local transferId = payload.transferId
    local sessionId = payload.sessionId
    local profileName = payload.profileName
    local sharedProfileId = payload.sharedProfileId
    local chunkCount = payload.chunkCount
    local settingsRevision = payload.settingsRevision
    local permissionsRevision = payload.permissionsRevision
    local operationalRevision = payload.operationalRevision
    local profileUpdatedAt = payload.profileUpdatedAt
    local settingsChecksum = payload.settingsChecksum
    local permissionsChecksum = payload.permissionsChecksum
    local operationalChecksum = payload.operationalChecksum
    local lootRevision = payload.lootRevision
    local sessionRevision = payload.sessionRevision
    local lootChecksum = payload.lootChecksum
    local sessionChecksum = payload.sessionChecksum
    local appliedGeneration = payload.appliedGeneration
    local ackPhase = payload.ackPhase
    local activeSession, activeProfileName = GetActiveLootSession()
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if not sessionRuntimeOps.doesSessionMatch(activeSession, activeProfileName, sessionId, profileName) then
      return
    end
    if selfKey == "" or not sessionRuntimeOps.isHostSender(activeSession, selfKey) then
      return
    end
    if not sessionRuntimeOps.isJoinedCharacter(activeSession, payload.senderKey) then
      return
    end

    local localProfileName = TrimText(activeProfileName) ~= "" and activeProfileName or profileName
    local senderKey = payload.senderKey
    local previousCurrentSessionDisplay = BuildCurrentSessionDisplaySignature(activeSession, localProfileName)
    local outboundTransfer = nil
    local ackRejectReason = "outbound_ack_handler_unavailable"
    if ackPhase == "QUEUED" and type(sessionRuntimeOps.markTransferQueued) == "function" then
      outboundTransfer, ackRejectReason = sessionRuntimeOps.markTransferQueued(
        transferId,
        senderKey,
        sessionId,
        profileName,
        appliedGeneration,
        sharedProfileId,
        chunkCount
      )
    elseif ackPhase == "APPLIED" and type(sessionRuntimeOps.markTransferAcked) == "function" then
      outboundTransfer, ackRejectReason = sessionRuntimeOps.markTransferAcked(
        transferId,
        senderKey,
        sessionId,
        profileName,
        appliedGeneration,
        sharedProfileId,
        chunkCount
      )
    end
    if type(outboundTransfer) ~= "table" then
      sessionRuntimeOps.recordInboundPayloadReject("PSYNC_ACK", sender, fields, ackRejectReason or "unrecognized_outbound_ack")
      return
    end
    local existingMember = type(activeSession) == "table" and type(activeSession.members) == "table"
      and activeSession.members[senderKey]
      or nil
    if ackPhase == "QUEUED" then
      if type(existingMember) == "table" then
        existingMember.profileApplyAckPhase = "QUEUED"
        existingMember.profileApplyQueuedAt = GetNow()
        existingMember.profileApplyPendingId = transferId
        existingMember.profileApplyPendingKind = "SNAPSHOT"
      end
      profileSyncLocalOps.markArchiveTransferState(outboundTransfer, "receiver_queued")
      profileSyncLocalOps.refreshCurrentAndSyncSections(true, {
        defer = false,
        forceImmediate = true,
      })
      return
    end
    if type(existingMember) == "table"
      and (TrimText(existingMember.profileApplyPendingKind) ~= "SNAPSHOT"
        or TrimText(existingMember.profileApplyPendingId) == ""
        or TrimText(existingMember.profileApplyPendingId) == transferId)
    then
      existingMember.profileApplyAckPhase = nil
      existingMember.profileApplyQueuedAt = nil
      existingMember.profileApplyPendingId = nil
      existingMember.profileApplyPendingKind = nil
    end
    if TrimText(outboundTransfer.state) == "superseded_acked" then
      profileSyncLocalOps.refreshCurrentAndSyncSections(true, {
        defer = false,
        forceImmediate = true,
      })
      return
    end
    local appliedLane = generationOps.NormalizeProfileTransferLane(
      outboundTransfer.reason,
      outboundTransfer.scopeSubdomains,
      outboundTransfer.transferKind
    )
    local previousGenerationStateSignature = BuildStableValueSignature(
      generationOps.GetMemberTransferGenerationState(sessionId, senderKey)
    )
    generationOps.RememberTransferGenerationState(
      sessionId,
      senderKey,
      appliedLane,
      appliedGeneration > 0 and appliedGeneration or outboundTransfer.generation,
      GetNow(),
      true
    )
    profileSyncLocalOps.markArchiveTransferState(outboundTransfer, "applied")
    local generationStateChanged = previousGenerationStateSignature ~= BuildStableValueSignature(
      generationOps.GetMemberTransferGenerationState(sessionId, senderKey)
    )
    local patchManifestStateChanged = false
    local liveLootChecksum = ""
    if appliedLane == "live" then
      liveLootChecksum = profileSyncLocalOps.buildLiveLootChecksum(
        GetLootProfileSubchecksumManifest(localProfileName, { "loot" }),
        activeSession
      )
    elseif type(activeSession) == "table" and type(activeSession.members) == "table" then
        liveLootChecksum = TrimText(type(activeSession.members[senderKey]) == "table" and activeSession.members[senderKey].liveLootChecksum or "")
    end
    local previousRevisionState = BuildSessionMemberRevisionStateSignature(
      type(activeSession) == "table" and type(activeSession.members) == "table" and activeSession.members[senderKey] or nil
    )
    local revisionStateChanged = false
    local ok, member
    if type(deps.UpsertLootSessionMember) == "function" then
      ok, member = deps.UpsertLootSessionMember(localProfileName, sessionId, senderKey, {
        sharedProfileId = sharedProfileId,
        settingsRevision = settingsRevision,
        permissionsRevision = permissionsRevision,
        operationalRevision = operationalRevision,
        lootRevision = lootRevision,
        sessionRevision = sessionRevision,
        settingsChecksum = settingsChecksum,
        permissionsChecksum = permissionsChecksum,
        operationalChecksum = operationalChecksum,
        lootChecksum = lootChecksum,
        sessionChecksum = sessionChecksum,
        liveLootChecksum = liveLootChecksum,
        profileUpdatedAt = profileUpdatedAt,
        lastSyncAt = time and time() or 0,
        suppressProfileTouch = true,
      })
    end
    if ok then
      revisionStateChanged = previousRevisionState ~= BuildSessionMemberRevisionStateSignature(
        member or (type(activeSession.members) == "table" and activeSession.members[senderKey]) or nil
      )
      if revisionStateChanged then
        InvalidateMemberPreciseSyncState(sessionId, senderKey, {
          domains = type(outboundTransfer) == "table" and outboundTransfer.scopeDomains or nil,
          subdomains = type(outboundTransfer) == "table" and outboundTransfer.scopeSubdomains or nil,
        })
      end
      if revisionStateChanged then
        profileSyncLocalOps.broadcastSessionMemberUpdate(
          localProfileName,
          sessionId,
          senderKey,
          member or (type(activeSession.members) == "table" and activeSession.members[senderKey]) or {}
        )
      end
    end
    if type(outboundTransfer) == "table" and type(outboundTransfer.patchManifestSummary) == "table" then
      local _, manifestChanged = RememberMemberPatchManifestState(
        sessionId,
        senderKey,
        FirstNonEmptyText(outboundTransfer.profileName, localProfileName),
        FirstNonEmptyText(outboundTransfer.profileId, sharedProfileId),
        outboundTransfer.patchManifestSummary,
        ""
      )
      patchManifestStateChanged = manifestChanged == true
    end
    local currentSectionStateChanged = previousCurrentSessionDisplay ~= BuildCurrentSessionDisplaySignature(activeSession, localProfileName)
    local runtimeStateChanged = profileSyncLocalOps.emitSnapshotAckNotice({
      sessionId = sessionId,
      profileName = localProfileName,
      sender = senderKey,
      chunkCount = chunkCount,
    })
    if runtimeStateChanged or currentSectionStateChanged or generationStateChanged or patchManifestStateChanged then
      profileSyncLocalOps.refreshCurrentAndSyncSections(currentSectionStateChanged, {
        defer = false,
        forceImmediate = true,
      })
    end
  end

  if type(INTERNAL_API.LIDCOUNCIL_RegisterCombatSyncInboxApplier_Impl) ~= "function"
    or not INTERNAL_API.LIDCOUNCIL_RegisterCombatSyncInboxApplier_Impl(
      "PSYNC_END",
      "profile_sync",
      profileSyncLocalOps.applyCombatStagedProfileSnapshot
    )
  then
    error("LidCouncil missing profile snapshot combat inbox registration.")
  end

  return {
    BuildEmptyRevisionSummary = BuildEmptyRevisionSummary,
    NormalizeRevisionSummary = NormalizeRevisionSummary,
    CompareProfileRevisionSummaries = profileSyncLocalOps.compareProfileRevisionSummaries,
    FormatProfileRevisionDomains = profileSyncLocalOps.formatProfileRevisionDomains,
    GetActiveProfileSyncCandidates = GetActiveProfileSyncCandidates,
    GetActiveProfileSyncStatus = profileSyncLocalOps.getActiveProfileSyncStatus,
    GetActiveProfileSyncConflictPreview = profileSyncLocalOps.getActiveProfileSyncConflictPreview,
    ApplyActiveProfilePreviewConflictResolution = ApplyActiveProfilePreviewConflictResolution,
    RememberSharedReplicaPlaceholder = RememberSharedReplicaPlaceholder,
    ResolveLocalSharedProfileName = ResolveLocalSharedProfileName,
    EnsureProfileSyncPopup = EnsureProfileSyncPopup,
    PrepareProfileSnapshotTransfer = profileSyncLocalOps.prepareProfileSnapshotTransfer,
    BuildPreparedProfileRepairTransfers = profileSyncLocalOps.buildPreparedProfileRepairTransfers,
    HasLoadedPatchManifestSubdomains = profileSyncLocalOps.hasLoadedPatchManifestSubdomains,
    SendPatchManifestRequests = profileSyncLocalOps.sendPatchManifestRequests,
    SendProfileSubdomainPatchManifest = SendProfileSubdomainPatchManifest,
    SendPreparedProfileSnapshot = SendPreparedProfileSnapshot,
    SendProfileSnapshot = SendProfileSnapshot,
    SendPreparedProfileSnapshotBatch = SendPreparedProfileSnapshotBatch,
    SendProfileSnapshotBatch = SendProfileSnapshotBatch,
    SendProfileSubchecksumRequests = profileSyncLocalOps.sendProfileSubchecksumRequests,
    GetMemberSubchecksumFreshness = profileSyncLocalOps.getMemberSubchecksumFreshness,
    GetMemberLootListDifferenceDiagnostics = GetMemberLootListDifferenceDiagnostics,
    GetMemberItemHistoryDifferenceDiagnostics = GetMemberItemHistoryDifferenceDiagnostics,
    GetMemberSessionHistoryDifferenceDiagnostics = GetMemberSessionHistoryDifferenceDiagnostics,
    BuildProfileSyncArchiveScopeChecksums = profileSyncLocalOps.buildProfileSyncArchiveScopeChecksums,
    BuildLootListDifferenceDiagnostics = profileSyncLocalOps.buildLootListDifferenceDiagnostics,
    BuildItemHistoryDifferenceDiagnostics = profileSyncLocalOps.buildItemHistoryDifferenceDiagnostics,
    BuildSessionHistoryDifferenceDiagnostics = profileSyncLocalOps.buildSessionHistoryDifferenceDiagnostics,
    GetPreciseResponseSafetyStatus = profileSyncLocalOps.getPreciseResponseSafetyStatus,
    GetOptionalApiSafetyStatus = profileSyncLocalOps.getOptionalApiSafetyStatus,
    SendLocalProfileStateToHost = profileSyncLocalOps.sendLocalProfileStateToHost,
    ScheduleDelayedLocalProfileStateSend = profileSyncLocalOps.scheduleDelayedLocalProfileStateSend,
    MarkArchiveTransferState = profileSyncLocalOps.markArchiveTransferState,
    CanRetryArchiveTransfer = profileSyncLocalOps.canRetryArchiveTransfer,
    ReconcileMemberArchiveTransactions = profileSyncLocalOps.reconcileMemberArchiveTransactions,
    DelayProfileSnapshotBatchForJoins = DelayProfileSnapshotBatchForJoins,
    BeginProfileSnapshotDiagnosticsForSession = profileSyncLocalOps.beginIncomingSnapshotDiagnosticsForSession,
    GetProfileSnapshotBatchStatus = profileSyncLocalOps.getProfileSnapshotBatchStatus,
    CancelProfileSnapshotBatchForSession = profileSyncLocalOps.cancelProfileSnapshotBatchForSession,
    HandleProfileSyncStart = HandleProfileSyncStart,
    HandleProfileSyncRequest = HandleProfileSyncRequest,
    HandleProfileSyncChunk = HandleProfileSyncChunk,
    HandleProfileSyncEnd = HandleProfileSyncEnd,
    SendProfileSyncAck = SendProfileSyncAck,
    HandleProfileSyncAck = HandleProfileSyncAck,
    HandleProfileSubchecksumRequest = HandleProfileSubchecksumRequest,
    HandleProfileSubchecksumState = HandleProfileSubchecksumState,
    HandleProfileSubdomainPatchManifestRequest = HandleProfileSubdomainPatchManifestRequest,
    HandleProfileSubdomainPatchManifestState = HandleProfileSubdomainPatchManifestState,
  }
end
