_G.LIDCOUNCIL_CreateCoreSystemHelpers_Impl = function(deps)
  deps = type(deps) == "table" and deps or {}

  local Print = deps.Print
  local RootDB = deps.RootDB
  local DB = deps.DB
  local TrimText = deps.TrimText
  local EnsureProfileRecord = deps.EnsureProfileRecord
  local RepairSimulationProfileOwnership = deps.RepairSimulationProfileOwnership
  local EnsureLootProfilePermissionState = deps.EnsureLootProfilePermissionState
  local EnsureLootProfileDefaults = deps.EnsureLootProfileDefaults
  local NormalizeActiveLootSessions = deps.NormalizeActiveLootSessions
  local NormalizeLootProfileEnabledState = deps.NormalizeLootProfileEnabledState
  local GetLootProfile = deps.GetLootProfile
  local GetLootProfileAccessInfo = deps.GetLootProfileAccessInfo
  local EnsureLidTableRows = deps.EnsureLidTableRows
  local NormalizePointMode = deps.NormalizePointMode
  local TouchLootProfile = deps.TouchLootProfile
  local TouchLootProfileSettings = deps.TouchLootProfileSettings

  local ROOT_SCHEMA_VERSION = 4

  local function NormalizeLootProfileIdPart(value, fallback)
    local part = string.lower(TrimText(value))
    part = part:gsub("%s+", "_")
    part = part:gsub("[^%w_%-%:]", "")
    if part == "" then
      part = tostring(fallback or "profile")
    end
    return part
  end

  local function BuildKnownLootProfileIdSet(root, skippedProfile)
    local known = {}
    root = type(root) == "table" and root or RootDB()
    for _, profile in pairs(root.profiles or {}) do
      if type(profile) == "table" and profile ~= skippedProfile and type(profile.meta) == "table" then
        local profileId = TrimText(profile.meta.profileId)
        if profileId ~= "" then
          known[string.lower(profileId)] = true
        end
      end
    end
    return known
  end

  local function GenerateLootProfileId(root, creatorKey, profileName, skippedProfile)
    root = type(root) == "table" and root or RootDB()
    root.__profileIdCounter = math.max(0, tonumber(root.__profileIdCounter) or 0)

    local knownIds = BuildKnownLootProfileIdSet(root, skippedProfile)
    local creatorPart = NormalizeLootProfileIdPart(creatorKey, "unknown")
    local profilePart = NormalizeLootProfileIdPart(profileName, "profile")
    local createdAt = tonumber(time and time() or 0) or 0

    while true do
      root.__profileIdCounter = root.__profileIdCounter + 1
      local randomPart = math.random(100000, 999999)
      local candidate = string.format("%s:%d:%d:%d:%s", creatorPart, createdAt, root.__profileIdCounter, randomPart, profilePart)
      if not knownIds[string.lower(candidate)] then
        return candidate
      end
    end
  end

  local function EnsureLootProfileIdentity(profile, profileName, fallbackCreatorKey, rootOverride)
    profile = type(profile) == "table" and profile or {}
    profile.meta = profile.meta or {}

    local profileId = TrimText(profile.meta.profileId)
    if profileId == "" then
      local creatorKey = TrimText(fallbackCreatorKey)
      if creatorKey == "" then
        creatorKey = TrimText(profile.meta.createdBy)
      end
      local permissions = type(profile.meta.permissions) == "table" and profile.meta.permissions or nil
      if creatorKey == "" and permissions then
        creatorKey = TrimText(permissions.master)
      end
      profile.meta.profileId = GenerateLootProfileId(rootOverride or RootDB(), creatorKey, profileName, profile)
    end

    return profile.meta.profileId
  end

  local function AssignNewLootProfileIdentity(profile, profileName, fallbackCreatorKey, rootOverride)
    profile = type(profile) == "table" and profile or {}
    profile.meta = profile.meta or {}

    local creatorKey = TrimText(fallbackCreatorKey)
    if creatorKey == "" then
      creatorKey = TrimText(profile.meta.createdBy)
    end
    local permissions = type(profile.meta.permissions) == "table" and profile.meta.permissions or nil
    if creatorKey == "" and permissions then
      creatorKey = TrimText(permissions.master)
    end

    profile.meta.profileId = GenerateLootProfileId(rootOverride or RootDB(), creatorKey, profileName, profile)
    return profile.meta.profileId
  end

  local function EnsureLootProfileSyncState(profile)
    profile = type(profile) == "table" and profile or {}
    profile.meta = profile.meta or {}
    profile.meta.sync = type(profile.meta.sync) == "table" and profile.meta.sync or {}
    local syncState = profile.meta.sync
    syncState.mode = TrimText(syncState.mode)
    if syncState.mode == "" then
      syncState.mode = "LOCAL"
    end
    syncState.origin = TrimText(syncState.origin)
    if syncState.origin == "" then
      syncState.origin = "CREATE"
    end
    syncState.cloneSourceProfileId = TrimText(syncState.cloneSourceProfileId)
    syncState.cloneSourceProfileName = TrimText(syncState.cloneSourceProfileName)
    syncState.cloneCreatedAt = tonumber(syncState.cloneCreatedAt) or nil
    syncState.sharedSourceProfileId = TrimText(syncState.sharedSourceProfileId)
    syncState.sharedSourceProfileName = TrimText(syncState.sharedSourceProfileName)
    syncState.sharedSourceCharacter = TrimText(syncState.sharedSourceCharacter)
    syncState.sharedAppliedAt = tonumber(syncState.sharedAppliedAt) or nil
    return syncState
  end

  local function MarkLootProfileAsIndependentClone(profile, origin, sourceInfo)
    profile = type(profile) == "table" and profile or {}
    local syncState = EnsureLootProfileSyncState(profile)
    sourceInfo = type(sourceInfo) == "table" and sourceInfo or {}

    syncState.mode = "LOCAL"
    syncState.origin = TrimText(origin)
    if syncState.origin == "" then
      syncState.origin = "CREATE"
    end
    syncState.cloneSourceProfileId = TrimText(sourceInfo.profileId)
    syncState.cloneSourceProfileName = TrimText(sourceInfo.profileName)
    syncState.cloneCreatedAt = tonumber(time and time() or 0) or 0
    syncState.sharedSourceProfileId = ""
    syncState.sharedSourceProfileName = ""
    syncState.sharedSourceCharacter = ""
    syncState.sharedAppliedAt = nil
    return syncState
  end

  local function MarkLootProfileAsSharedReplica(profile, origin, sourceInfo)
    profile = type(profile) == "table" and profile or {}
    local syncState = EnsureLootProfileSyncState(profile)
    sourceInfo = type(sourceInfo) == "table" and sourceInfo or {}

    syncState.mode = "SHARED"
    syncState.origin = TrimText(origin)
    if syncState.origin == "" then
      syncState.origin = "SESSION_SNAPSHOT"
    end
    syncState.sharedSourceProfileId = TrimText(sourceInfo.profileId)
    syncState.sharedSourceProfileName = TrimText(sourceInfo.profileName)
    syncState.sharedSourceCharacter = TrimText(sourceInfo.sourceCharacter)
    syncState.sharedAppliedAt = tonumber(time and time() or 0) or 0
    return syncState
  end

  local function EnsureLootProfileRevisionState(profile)
    profile = type(profile) == "table" and profile or {}
    profile.meta = profile.meta or {}
    profile.meta.domainRevisions = type(profile.meta.domainRevisions) == "table" and profile.meta.domainRevisions or {}

    local currentRevision = math.max(0, tonumber(profile.meta.revision) or 0)
    local currentUpdatedAt = tonumber(profile.meta.updatedAt) or tonumber(profile.meta.createdAt) or (time and time() or 0)
    local domainRevisions = profile.meta.domainRevisions

    local function ensureDomain(domainKey)
      local entry = type(domainRevisions[domainKey]) == "table" and domainRevisions[domainKey] or {}
      entry.revision = math.max(0, tonumber(entry.revision) or currentRevision)
      entry.updatedAt = tonumber(entry.updatedAt) or currentUpdatedAt
      domainRevisions[domainKey] = entry
      return entry
    end

    ensureDomain("settings")
    ensureDomain("permissions")
    ensureDomain("operational")
    ensureDomain("loot")
    ensureDomain("session")
    return domainRevisions
  end

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

  local function GetLootProfileDomainRevision(profile, domain)
    if type(profile) ~= "table" then
      return 0
    end
    local domainKey = NormalizeLootProfileDomainKey(domain)
    local domainRevisions = EnsureLootProfileRevisionState(profile)
    local entry = type(domainRevisions[domainKey]) == "table" and domainRevisions[domainKey] or {}
    return math.max(0, tonumber(entry.revision) or 0)
  end

  local function StableChecksumKey(value)
    return type(value) .. ":" .. tostring(value)
  end

  local function StableSerializeForChecksum(value, seen)
    local valueType = type(value)
    if valueType == "nil" then
      return "n:nil"
    elseif valueType == "boolean" then
      return value and "b:true" or "b:false"
    elseif valueType == "number" then
      return "d:" .. tostring(value)
    elseif valueType == "string" then
      return "s:" .. string.format("%q", value)
    elseif valueType ~= "table" then
      return valueType .. ":" .. tostring(value)
    end

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

    local keys = {}
    for key in pairs(value) do
      local keyType = type(key)
      if keyType == "string" or keyType == "number" or keyType == "boolean" then
        keys[#keys + 1] = key
      end
    end
    table.sort(keys, function(left, right)
      return StableChecksumKey(left) < StableChecksumKey(right)
    end)

    local parts = { "t:{" }
    for index, key in ipairs(keys) do
      parts[#parts + 1] = StableSerializeForChecksum(key, seen)
      parts[#parts + 1] = "="
      parts[#parts + 1] = StableSerializeForChecksum(value[key], seen)
      if index < #keys then
        parts[#parts + 1] = ";"
      end
    end
    parts[#parts + 1] = "}"
    seen[value] = nil
    return table.concat(parts)
  end

  local function CalculateStableChecksum(value)
    local text = StableSerializeForChecksum(value)
    local mod = 65521
    local a = 1
    local b = 0
    for index = 1, #text do
      a = (a + string.byte(text, index)) % mod
      b = (b + a) % mod
    end
    return string.format("%04x%04x", b, a)
  end

  local function BuildLootProfileSettingsChecksumSource(profile)
    local settings = type(profile) == "table" and type(profile.settings) == "table" and profile.settings or {}
    local source = {}
    for key, value in pairs(settings) do
      if key ~= "enabled" then
        source[key] = value
      end
    end
    return source
  end

  local function BuildLootProfilePermissionsChecksumSource(profile)
    local meta = type(profile) == "table" and type(profile.meta) == "table" and profile.meta or {}
    return {
      permissions = meta.permissions,
      permissionPolicy = meta.permissionPolicy,
    }
  end

  local function CopyChecksumTable(value, omittedKeys)
    if type(value) ~= "table" then
      return value
    end
    local copy = {}
    for key, child in pairs(value) do
      local omit = false
      if type(key) == "string" then
        omit = (type(omittedKeys) == "table" and omittedKeys[key] == true) or key:match("^__") ~= nil
      end
      if not omit then
        copy[key] = CopyChecksumTable(child, omittedKeys)
      end
    end
    return copy
  end

  local function RecalculateLootLedgerRowTotal(row)
    if type(row) ~= "table" then
      return 0
    end
    local total = 0
    for _, item in ipairs(type(row.items) == "table" and row.items or {}) do
      total = total + (tonumber(type(item) == "table" and item.points) or 0)
    end
    row.totalPoints = total
    return total
  end

  local function RecalculateLootLedgerTotals(profile)
    if type(profile) ~= "table" or type(profile.lootLedger) ~= "table" then
      return
    end
    for characterKey, row in pairs(profile.lootLedger) do
      if type(row) == "table" then
        if TrimText(row.character) == "" then
          row.character = tostring(characterKey)
        end
        RecalculateLootLedgerRowTotal(row)
      end
    end
  end

  local function BuildNormalizedLootLedgerChecksumSource(lootLedger)
    local normalized = {}
    for characterKey, row in pairs(type(lootLedger) == "table" and lootLedger or {}) do
      if type(row) == "table" then
        local rowCopy = {}
        for key, value in pairs(row) do
          if key ~= "totalPoints" then
            rowCopy[key] = CopyChecksumTable(value)
          end
        end
        local total = 0
        rowCopy.items = {}
        for index, item in ipairs(type(row.items) == "table" and row.items or {}) do
          if type(item) == "table" then
            local itemCopy = CopyChecksumTable(item)
            rowCopy.items[index] = itemCopy
            total = total + (tonumber(itemCopy.points) or 0)
          else
            rowCopy.items[index] = item
          end
        end
        rowCopy.totalPoints = total
        normalized[characterKey] = rowCopy
      else
        normalized[characterKey] = row
      end
    end
    return normalized
  end

  local function BuildNormalizedLootLedgerRowChecksumSource(characterKey, row)
    local normalized = BuildNormalizedLootLedgerChecksumSource({
      [characterKey] = row,
    })
    return normalized[characterKey]
  end

  local PROFILE_SESSION_OMITTED_KEYS = {
    acceptedBySelf = true,
    profileDeltaSequence = true,
    remoteProfileName = true,
    sharedByUpdate = true,
    sharedProfileReady = true,
  }

  local PROFILE_SESSION_MEMBER_OMITTED_KEYS = {
    lastSyncAt = true,
    lastProfileDeltaAck = true,
    lastProfileDeltaRecovery = true,
    localAutoPassEnabled = true,
    lootRevision = true,
    lootChecksum = true,
    operationalRevision = true,
    operationalChecksum = true,
    permissionsRevision = true,
    permissionsChecksum = true,
    profileMaster = true,
    profileUpdatedAt = true,
    role = true,
    sessionRevision = true,
    sessionChecksum = true,
    settingsRevision = true,
    settingsChecksum = true,
    sharedProfileId = true,
  }

  local function BuildLootProfileSessionRecordChecksumSource(session)
    if type(session) ~= "table" then
      return {}
    end
    local sessionCopy = {}
    for key, value in pairs(session) do
      local omit = type(key) == "string" and (PROFILE_SESSION_OMITTED_KEYS[key] == true or key:match("^__") ~= nil)
      if not omit then
        if key == "members" and type(value) == "table" then
          local membersCopy = {}
          for memberKey, member in pairs(value) do
            membersCopy[memberKey] = CopyChecksumTable(member, PROFILE_SESSION_MEMBER_OMITTED_KEYS)
          end
          sessionCopy.members = membersCopy
        else
          sessionCopy[key] = CopyChecksumTable(value)
        end
      end
    end
    return sessionCopy
  end

  local function BuildLootProfileSessionsChecksumSource(sessions)
    if type(sessions) ~= "table" then
      return {}
    end
    local output = {}
    for index, session in ipairs(sessions) do
      if type(session) == "table" then
        local sessionId = TrimText(session.id)
        local identity = sessionId ~= ""
          and ("id:" .. sessionId)
          or ("stamp:" .. tostring(math.max(0, tonumber(session.startedAt) or 0)) .. ":" .. TrimText(session.host))
        output[identity] = BuildLootProfileSessionRecordChecksumSource(session)
      end
    end
    return output
  end

  local function BuildLootProfileLiveBoardChecksumSource(history)
    if type(history) ~= "table" then
      return {}
    end
    local output = {}
    for _, snapshot in ipairs(history) do
      if type(snapshot) == "table" then
        local boardId = TrimText(snapshot.boardId)
        local sessionId = TrimText(snapshot.sessionId)
        local identity = boardId ~= ""
          and ("board:" .. boardId)
          or (sessionId ~= "" and ("session:" .. sessionId) or ("stamp:" .. tostring(math.max(0, tonumber(snapshot.updatedAt) or 0)) .. ":" .. tostring(math.max(0, tonumber(snapshot.createdAt) or 0))))
        output[identity] = DeepCopy(snapshot)
      end
    end
    return output
  end

  local function BuildLootProfileLootChecksumSource(profile)
    profile = type(profile) == "table" and profile or {}
    return {
      lootLedger = BuildNormalizedLootLedgerChecksumSource(profile.lootLedger),
      lootLedgerMeta = profile.lootLedgerMeta,
      lootLedgerEntrySerial = profile.lootLedgerEntrySerial,
      lootRollStats = profile.lootRollStats,
      lootListGroups = profile.lootListGroups,
    }
  end

  local function BuildLootProfileSessionChecksumSource(profile)
    profile = type(profile) == "table" and profile or {}
    return {
      sessions = BuildLootProfileSessionsChecksumSource(profile.sessions),
      liveBoardHistory = BuildLootProfileLiveBoardChecksumSource(profile.liveBoardHistory),
    }
  end

  local function BuildLootProfileOperationalChecksumSource(profile)
    profile = type(profile) == "table" and profile or {}
    return {
      lootLedger = BuildNormalizedLootLedgerChecksumSource(profile.lootLedger),
      lootLedgerMeta = profile.lootLedgerMeta,
      lootLedgerEntrySerial = profile.lootLedgerEntrySerial,
      lootRollStats = profile.lootRollStats,
      lootListGroups = profile.lootListGroups,
      sessions = BuildLootProfileSessionsChecksumSource(profile.sessions),
      liveBoardHistory = BuildLootProfileLiveBoardChecksumSource(profile.liveBoardHistory),
    }
  end

  local function GetLootProfileDomainChecksum(profile, domain)
    if type(profile) ~= "table" then
      return ""
    end
    local domainKey = NormalizeLootProfileDomainKey(domain)
    if domainKey == "settings" then
      return CalculateStableChecksum(BuildLootProfileSettingsChecksumSource(profile))
    elseif domainKey == "permissions" then
      return CalculateStableChecksum(BuildLootProfilePermissionsChecksumSource(profile))
    elseif domainKey == "loot" then
      return CalculateStableChecksum(BuildLootProfileLootChecksumSource(profile))
    elseif domainKey == "session" then
      return CalculateStableChecksum(BuildLootProfileSessionChecksumSource(profile))
    end
    return CalculateStableChecksum(BuildLootProfileOperationalChecksumSource(profile))
  end

  local function FormatDiffPath(parentPath, key)
    local keyType = type(key)
    if parentPath == "" then
      if keyType == "number" then
        return "[" .. tostring(key) .. "]"
      end
      return tostring(key)
    end
    if keyType == "number" then
      return parentPath .. "[" .. tostring(key) .. "]"
    end
    return parentPath .. "." .. tostring(key)
  end

  local function CollectProfileDiffLines(left, right, path, lines, limit, seen)
    lines = type(lines) == "table" and lines or {}
    limit = tonumber(limit) or 16
    if #lines >= limit then
      return lines, 0
    end
    local leftType = type(left)
    local rightType = type(right)
    if leftType ~= rightType then
      lines[#lines + 1] = (path ~= "" and path or "value") .. " type changed: " .. leftType .. " -> " .. rightType
      return lines, 1
    end
    if leftType ~= "table" then
      if StableSerializeForChecksum(left) ~= StableSerializeForChecksum(right) then
        lines[#lines + 1] = (path ~= "" and path or "value") .. " changed"
        return lines, 1
      end
      return lines, 0
    end

    seen = type(seen) == "table" and seen or {}
    if seen[left] or seen[right] then
      return lines, 0
    end
    seen[left] = true
    seen[right] = true

    local keys = {}
    local keyed = {}
    for key in pairs(left) do
      keyed[StableChecksumKey(key)] = key
    end
    for key in pairs(right) do
      keyed[StableChecksumKey(key)] = key
    end
    for _, key in pairs(keyed) do
      keys[#keys + 1] = key
    end
    table.sort(keys, function(a, b)
      return StableSerializeForChecksum(a) < StableSerializeForChecksum(b)
    end)

    local count = 0
    for _, key in ipairs(keys) do
      if #lines >= limit then
        break
      end
      local nextPath = FormatDiffPath(path, key)
      local hasLeft = left[key] ~= nil
      local hasRight = right[key] ~= nil
      if hasLeft and not hasRight then
        lines[#lines + 1] = nextPath .. " exists only locally"
        count = count + 1
      elseif hasRight and not hasLeft then
        lines[#lines + 1] = nextPath .. " exists only in member snapshot"
        count = count + 1
      else
        local _, childCount = CollectProfileDiffLines(left[key], right[key], nextPath, lines, limit, seen)
        count = count + (tonumber(childCount) or 0)
      end
    end
    seen[left] = nil
    seen[right] = nil
    return lines, count
  end

  local function BuildProfileDomainDiff(label, leftSource, rightSource)
    local lines = {}
    local _, count = CollectProfileDiffLines(leftSource or {}, rightSource or {}, "", lines, 18, {})
    return {
      label = label,
      count = tonumber(count) or 0,
      lines = lines,
    }
  end

  local function BuildLootProfileSnapshotDiff(profileName, dataStr)
    local root = RootDB()
    local localProfile = type(root) == "table" and type(root.profiles) == "table" and root.profiles[profileName] or nil
    if type(localProfile) ~= "table" or type(dataStr) ~= "string" or dataStr:sub(1, #PROFILE_SNAPSHOT_EXPORT_PREFIX) ~= PROFILE_SNAPSHOT_EXPORT_PREFIX then
      return nil
    end
    local payload = dataStr:sub(#PROFILE_SNAPSHOT_EXPORT_PREFIX + 1)
    local data = json_decode(payload)
    local remoteProfile = type(data) == "table" and type(data.profile) == "table" and data.profile or nil
    if type(remoteProfile) ~= "table" then
      return nil
    end
    EnsureLootProfileDefaults(localProfile)
    EnsureLootProfileDefaults(remoteProfile)
    RecalculateLootLedgerTotals(localProfile)
    RecalculateLootLedgerTotals(remoteProfile)
    local settingsDiff = BuildProfileDomainDiff("Settings", BuildLootProfileSettingsChecksumSource(localProfile), BuildLootProfileSettingsChecksumSource(remoteProfile))
    local permissionsDiff = BuildProfileDomainDiff("Permissions", BuildLootProfilePermissionsChecksumSource(localProfile), BuildLootProfilePermissionsChecksumSource(remoteProfile))
    local lootDiff = BuildProfileDomainDiff("Loot Data", BuildLootProfileLootChecksumSource(localProfile), BuildLootProfileLootChecksumSource(remoteProfile))
    local sessionDiff = BuildProfileDomainDiff("Session Data", BuildLootProfileSessionChecksumSource(localProfile), BuildLootProfileSessionChecksumSource(remoteProfile))
    local operationalDiff = BuildProfileDomainDiff("Legacy Operational Data", BuildLootProfileOperationalChecksumSource(localProfile), BuildLootProfileOperationalChecksumSource(remoteProfile))
    return {
      profileName = TrimText(profileName),
      snapshotProfileName = TrimText(type(data.source) == "table" and data.source.profileName or ""),
      exportedAt = tonumber(data.exportedAt) or 0,
      settings = settingsDiff,
      permissions = permissionsDiff,
      loot = lootDiff,
      session = sessionDiff,
      operational = operationalDiff,
      hasChanges = (settingsDiff.count + permissionsDiff.count + lootDiff.count + sessionDiff.count) > 0,
    }
  end

  local function BuildLootProfileRevisionSummary(profile, profileName)
    if type(profile) ~= "table" then
      return {
        profileName = TrimText(profileName),
        profileId = "",
        settings = 0,
        permissions = 0,
        operational = 0,
        loot = 0,
        session = 0,
        settingsChecksum = "",
        permissionsChecksum = "",
        operationalChecksum = "",
        lootChecksum = "",
        sessionChecksum = "",
        settingsUpdatedAt = 0,
        permissionsUpdatedAt = 0,
        operationalUpdatedAt = 0,
        lootUpdatedAt = 0,
        sessionUpdatedAt = 0,
        updatedAt = 0,
      }
    end
    EnsureLootProfileDefaults(profile)
    EnsureLootProfileIdentity(profile, profileName)
    EnsureLootProfileSyncState(profile)
    EnsureLootProfileRevisionState(profile)
    local domainRevisions = type(profile.meta) == "table" and type(profile.meta.domainRevisions) == "table" and profile.meta.domainRevisions or {}
    local settingsState = type(domainRevisions.settings) == "table" and domainRevisions.settings or {}
    local permissionsState = type(domainRevisions.permissions) == "table" and domainRevisions.permissions or {}
    local operationalState = type(domainRevisions.operational) == "table" and domainRevisions.operational or {}
    local lootState = type(domainRevisions.loot) == "table" and domainRevisions.loot or {}
    local sessionState = type(domainRevisions.session) == "table" and domainRevisions.session or {}
    local settingsUpdatedAt = tonumber(settingsState.updatedAt) or 0
    local permissionsUpdatedAt = tonumber(permissionsState.updatedAt) or 0
    local operationalUpdatedAt = tonumber(operationalState.updatedAt) or 0
    local lootUpdatedAt = tonumber(lootState.updatedAt) or operationalUpdatedAt
    local sessionUpdatedAt = tonumber(sessionState.updatedAt) or operationalUpdatedAt
    return {
      profileName = TrimText(profileName),
      profileId = TrimText(type(profile.meta) == "table" and profile.meta.profileId),
      settings = GetLootProfileDomainRevision(profile, "settings"),
      permissions = GetLootProfileDomainRevision(profile, "permissions"),
      operational = GetLootProfileDomainRevision(profile, "operational"),
      loot = GetLootProfileDomainRevision(profile, "loot"),
      session = GetLootProfileDomainRevision(profile, "session"),
      settingsChecksum = GetLootProfileDomainChecksum(profile, "settings"),
      permissionsChecksum = GetLootProfileDomainChecksum(profile, "permissions"),
      operationalChecksum = GetLootProfileDomainChecksum(profile, "operational"),
      lootChecksum = GetLootProfileDomainChecksum(profile, "loot"),
      sessionChecksum = GetLootProfileDomainChecksum(profile, "session"),
      settingsUpdatedAt = settingsUpdatedAt,
      permissionsUpdatedAt = permissionsUpdatedAt,
      operationalUpdatedAt = operationalUpdatedAt,
      lootUpdatedAt = lootUpdatedAt,
      sessionUpdatedAt = sessionUpdatedAt,
      updatedAt = math.max(tonumber(profile.meta.updatedAt) or 0, settingsUpdatedAt, permissionsUpdatedAt, operationalUpdatedAt, lootUpdatedAt, sessionUpdatedAt),
    }
  end

  local function GetLootProfileRevisionSummary(profileName)
    local resolvedName = TrimText(profileName)
    if resolvedName == "" then
      return BuildLootProfileRevisionSummary(nil, "")
    end
    local profile = select(1, GetLootProfile(resolvedName))
    return BuildLootProfileRevisionSummary(profile, resolvedName)
  end

  local function TouchLootProfileDomain(profile, domain)
    if type(profile) ~= "table" then
      return
    end
    local updatedAt = (type(GetServerTime) == "function" and GetServerTime()) or (time and time() or 0)
    local requestedDomainKey = NormalizeLootProfileDomainKey(domain)
    local domainRevisions = EnsureLootProfileRevisionState(profile)
    local function touchDomain(domainKey)
      local entry = type(domainRevisions[domainKey]) == "table" and domainRevisions[domainKey] or {}
      entry.revision = math.max(0, tonumber(entry.revision) or 0) + 1
      entry.updatedAt = updatedAt
      domainRevisions[domainKey] = entry
    end
    touchDomain(requestedDomainKey)
    if requestedDomainKey == "operational" then
      touchDomain("loot")
      touchDomain("session")
    elseif requestedDomainKey == "loot" or requestedDomainKey == "session" then
      touchDomain("operational")
    end
    profile.meta.revision = math.max(0, tonumber(profile.meta.revision) or 0) + 1
    profile.meta.updatedAt = updatedAt
  end

  local function DeepCopy(src)
    if type(src) ~= "table" then return src end
    local dst = {}
    for k, v in pairs(src) do dst[k] = DeepCopy(v) end
    return dst
  end

  local EXPORT_PREFIX = "LIDJ1:"
  local PROFILE_SNAPSHOT_EXPORT_PREFIX = "LIDPS1:"
  local PROFILE_DOMAIN_SNAPSHOT_EXPORT_PREFIX = "LIDPD1:"
  local PROFILE_SUBDOMAIN_SNAPSHOT_EXPORT_PREFIX = "LIDPDS1:"
  local PROFILE_SUBDOMAIN_PATCH_EXPORT_PREFIX = "LIDPDP1:"
  local PROFILE_CONFLICT_ROW_PATCH_EXPORT_PREFIX = "LIDPRW1:"
  local PROFILE_SUBDOMAIN_PATCH_MANIFEST_EXPORT_PREFIX = "LIDPPM1:"
  local ROLL_SETTINGS_EXPORT_PREFIX = "LIDROLL1:"
  local POINT_SETTINGS_EXPORT_PREFIX = "LIDPOINT1:"
  local PROFILE_TRANSFER_DOMAINS = { "settings", "permissions", "loot", "session" }

  local function is_array(t)
    local n = 0
    for k, _ in pairs(t) do
      if type(k) ~= "number" or k < 1 or k % 1 ~= 0 then return false end
      if k > n then n = k end
    end
    for i = 1, n do if t[i] == nil then return false end end
    return true, n
  end

  local function json_escape(s)
    s = s:gsub("\\", "\\\\")
    s = s:gsub("\"", "\\\"")
    s = s:gsub("\n", "\\n")
    s = s:gsub("\r", "\\r")
    s = s:gsub("\t", "\\t")
    return s
  end

  local function json_encode(v)
    local tv = type(v)
    if tv == "nil" then
      return "null"
    elseif tv == "boolean" then
      return v and "true" or "false"
    elseif tv == "number" then
      if v ~= v or v == math.huge or v == -math.huge then return "null" end
      return tostring(v)
    elseif tv == "string" then
      return "\"" .. json_escape(v) .. "\""
    elseif tv == "table" then
      local arr, n = is_array(v)
      if arr then
        local parts = {"["}
        for i = 1, n do
          parts[#parts+1] = json_encode(v[i])
          if i < n then parts[#parts+1] = "," end
        end
        parts[#parts+1] = "]"
        return table.concat(parts)
      else
        local parts = {"{"}
        local first = true
        for k, val in pairs(v) do
          local kt = type(k)
          local key
          if kt == "string" then key = k
          elseif kt == "number" then key = tostring(k)
          end
          if key ~= nil then
            if not first then parts[#parts+1] = "," end
            first = false
            parts[#parts+1] = "\"" .. json_escape(key) .. "\":" .. json_encode(val)
          end
        end
        parts[#parts+1] = "}"
        return table.concat(parts)
      end
    end
    return "null"
  end

  local function json_decode(str)
    if type(str) ~= "string" then return nil end
    local i, len = 1, #str

    local function skip_ws()
      while i <= len do
        local c = str:sub(i, i)
        if c == " " or c == "\n" or c == "\r" or c == "\t" then i = i + 1 else break end
      end
    end

    local function parse_string()
      i = i + 1
      local out = {}
      while i <= len do
        local c = str:sub(i, i)
        if c == "\"" then i = i + 1; return table.concat(out) end
        if c == "\\" then
          local n = str:sub(i+1, i+1)
          if n == "\"" or n == "\\" or n == "/" then out[#out+1] = n; i = i + 2
          elseif n == "n" then out[#out+1] = "\n"; i = i + 2
          elseif n == "r" then out[#out+1] = "\r"; i = i + 2
          elseif n == "t" then out[#out+1] = "\t"; i = i + 2
          else return nil end
        else
          out[#out+1] = c
          i = i + 1
        end
      end
      return nil
    end

    local function parse_number()
      local start = i
      local c = str:sub(i, i)
      if c == "-" then i = i + 1 end
      while i <= len and str:sub(i, i):match("%d") do i = i + 1 end
      if str:sub(i, i) == "." then
        i = i + 1
        while i <= len and str:sub(i, i):match("%d") do i = i + 1 end
      end
      c = str:sub(i, i)
      if c == "e" or c == "E" then
        i = i + 1
        c = str:sub(i, i)
        if c == "+" or c == "-" then i = i + 1 end
        while i <= len and str:sub(i, i):match("%d") do i = i + 1 end
      end
      return tonumber(str:sub(start, i-1))
    end

    local parse_value

    local function parse_array()
      i = i + 1
      local arr = {}
      skip_ws()
      if str:sub(i, i) == "]" then i = i + 1; return arr end
      local idx = 1
      while i <= len do
        local v = parse_value()
        if v == nil and str:sub(i-4, i-1) ~= "null" then return nil end
        arr[idx] = v; idx = idx + 1
        skip_ws()
        local c = str:sub(i, i)
        if c == "," then i = i + 1; skip_ws()
        elseif c == "]" then i = i + 1; return arr
        else return nil end
      end
      return nil
    end

    local function parse_object()
      i = i + 1
      local obj = {}
      skip_ws()
      if str:sub(i, i) == "}" then i = i + 1; return obj end
      while i <= len do
        skip_ws()
        if str:sub(i, i) ~= "\"" then return nil end
        local key = parse_string()
        if not key then return nil end
        skip_ws()
        if str:sub(i, i) ~= ":" then return nil end
        i = i + 1
        skip_ws()
        local val = parse_value()
        if val == nil and str:sub(i-4, i-1) ~= "null" then return nil end

        local nkey = tonumber(key)
        if nkey and tostring(nkey) == key then obj[nkey] = val else obj[key] = val end

        skip_ws()
        local c = str:sub(i, i)
        if c == "," then i = i + 1
        elseif c == "}" then i = i + 1; return obj
        else return nil end
      end
      return nil
    end

    parse_value = function()
      skip_ws()
      if i > len then return nil end
      local c = str:sub(i, i)
      if c == "\"" then return parse_string()
      elseif c == "{" then return parse_object()
      elseif c == "[" then return parse_array()
      elseif c == "t" and str:sub(i, i+3) == "true" then i = i + 4; return true
      elseif c == "f" and str:sub(i, i+4) == "false" then i = i + 5; return false
      elseif c == "n" and str:sub(i, i+3) == "null" then i = i + 4; return nil
      elseif c == "-" or c:match("%d") then return parse_number()
      end
      return nil
    end

    local val = parse_value()
    skip_ws()
    if i <= len then return nil end
    return val
  end

  local function MigrateLegacyLootLedgerMeta(profile)
    profile = type(profile) == "table" and profile or {}
    profile.lootLedgerMeta = profile.lootLedgerMeta or {}

    for characterKey, meta in pairs(profile.lootLedgerMeta) do
      local resolvedKey = TrimText(characterKey)
      local entry = type(meta) == "table" and meta or {}
      local legacyMainCharacter = TrimText(entry.summaryWith)
      entry.mainCharacter = TrimText(entry.mainCharacter)
      entry.mainAltRole = string.upper(TrimText(entry.mainAltRole))
      if entry.mainAltRole ~= "ALT" then
        entry.mainAltRole = "MAIN"
      end
      if entry.mainCharacter == "" then
        entry.mainCharacter = legacyMainCharacter
      end
      if entry.mainAltRole == "MAIN" and entry.mainCharacter ~= "" then
        entry.mainAltRole = "ALT"
      end
      if string.lower(entry.mainCharacter) == string.lower(resolvedKey) then
        entry.mainCharacter = ""
        entry.mainAltRole = "MAIN"
      end
      entry.summaryWith = nil
      if resolvedKey ~= characterKey then
        profile.lootLedgerMeta[characterKey] = nil
        if resolvedKey ~= "" then
          profile.lootLedgerMeta[resolvedKey] = entry
        end
      else
        profile.lootLedgerMeta[characterKey] = entry
      end
    end
  end

  local function ApplyBackgroundCategoryMigration(root)
    root.backgroundCategories = root.backgroundCategories or {}

    local function findCategory(name)
      local needle = string.lower(tostring(name or ""))
      for _, cat in ipairs(root.backgroundCategories) do
        if string.lower(tostring(cat.name or "")) == needle then return cat end
      end
      return nil
    end

    local function isLegacyDefaultBackground(name)
      local n = string.lower(tostring(name or ""))
      return n == "xalatath" or n == "chc3" or n == "chc9"
    end

    local function pruneLegacyDefaults(list)
      if type(list) ~= "table" then return end
      for i = #list, 1, -1 do
        if isLegacyDefaultBackground(list[i]) then
          table.remove(list, i)
        end
      end
    end

    local function hasBackground(list, name)
      local needle = string.lower(tostring(name or ""))
      for _, item in ipairs(list or {}) do
        if string.lower(tostring(item or "")) == needle then
          return true
        end
      end
      return false
    end

    local cat = findCategory("My Collection")
    if not cat then
      cat = { name = "My Collection", items = {} }
      root.backgroundCategories[#root.backgroundCategories + 1] = cat
    end
    cat.items = cat.items or {}
    pruneLegacyDefaults(cat.items)
    if not hasBackground(cat.items, "DH_Devourer") then
      cat.items[#cat.items + 1] = "DH_Devourer"
    end
    if not hasBackground(cat.items, "Mage_Fire") then
      cat.items[#cat.items + 1] = "Mage_Fire"
    end

    root.__bgSeedVersion = nil
    root.__bgCategoriesSeeded = nil
  end

  local function RunRootMigrations(root)
    root = type(root) == "table" and root or RootDB()
    local schemaVersion = tonumber(root.__schemaVersion) or 0
    if schemaVersion >= ROOT_SCHEMA_VERSION then
      return schemaVersion
    end

    if schemaVersion < 1 then
      for _, profile in pairs(root.profiles or {}) do
        if type(profile) == "table" then
          profile.panelOrder = nil
        end
      end

      root.ui = root.ui or {}
      root.ui.headerBg = nil
      root.ui.theme = nil
      root.ui.font = nil
      root.ui.__themeFromPreset = nil
      root.ui.__fontFromPreset = nil
      schemaVersion = 1
    end

    if schemaVersion < 2 then
      ApplyBackgroundCategoryMigration(root)
      schemaVersion = 2
    end

    if schemaVersion < 3 then
      for _, profile in pairs(root.profiles or {}) do
        if type(profile) == "table" then
          MigrateLegacyLootLedgerMeta(profile)
        end
      end
      schemaVersion = 3
    end

    if schemaVersion < 4 then
      local seenProfileIds = {}
      for profileName, profile in pairs(root.profiles or {}) do
        if type(profile) == "table" then
          EnsureLootProfileDefaults(profile)
          EnsureLootProfileSyncState(profile)
          EnsureLootProfileRevisionState(profile)
          local profileId = TrimText(profile.meta and profile.meta.profileId)
          local lowerId = string.lower(profileId)
          if profileId == "" or seenProfileIds[lowerId] then
            AssignNewLootProfileIdentity(profile, profileName, nil, root)
            profileId = TrimText(profile.meta and profile.meta.profileId)
            lowerId = string.lower(profileId)
          end
          if profileId ~= "" then
            seenProfileIds[lowerId] = true
          end
        end
      end
      schemaVersion = ROOT_SCHEMA_VERSION
    end

    root.__schemaVersion = ROOT_SCHEMA_VERSION
    return ROOT_SCHEMA_VERSION
  end

  local function ExportProfile(profileName)
    local root = RootDB()
    local p = root.profiles[profileName]
    if not p then return nil end
    return EXPORT_PREFIX .. json_encode({
      kind = "PROFILE_CLONE",
      exportMode = "LOCAL_CLONE",
      exportedAt = tonumber(time and time() or 0) or 0,
      source = {
        profileName = tostring(profileName),
        profileId = type(p.meta) == "table" and p.meta.profileId or nil,
      },
      profile = DeepCopy(p),
    })
  end

  local function ExportLootProfileSnapshot(profileName)
    local root = RootDB()
    local profile = root.profiles[profileName]
    if type(profile) ~= "table" then
      return nil
    end
    EnsureLootProfileDefaults(profile)
    EnsureLootProfileIdentity(profile, profileName)
    EnsureLootProfileSyncState(profile)
    EnsureLootProfileRevisionState(profile)
    RecalculateLootLedgerTotals(profile)
    return PROFILE_SNAPSHOT_EXPORT_PREFIX .. json_encode({
      kind = "PROFILE_SNAPSHOT",
      exportMode = "SHARED",
      exportedAt = tonumber(time and time() or 0) or 0,
      source = {
        profileName = tostring(profileName),
        profileId = type(profile.meta) == "table" and profile.meta.profileId or nil,
      },
      profile = DeepCopy(profile),
    })
  end

  local function CloneLootProfileDomainList(domains)
    local cloned = {}
    for _, domain in ipairs(type(domains) == "table" and domains or {}) do
      cloned[#cloned + 1] = TrimText(domain)
    end
    return cloned
  end

  local function NormalizeLootProfileDomainList(domains)
    local requested = {}
    if type(domains) == "string" then
      for token in string.gmatch(domains, "[^,%s;|]+") do
        requested[#requested + 1] = token
      end
    elseif type(domains) == "table" then
      for _, domain in ipairs(domains) do
        requested[#requested + 1] = domain
      end
    end

    local normalizedByKey = {}
    local addDomain
    addDomain = function(domain)
      local requestedDomain = string.lower(TrimText(domain))
      local domainKey = NormalizeLootProfileDomainKey(domain)
      if requestedDomain == "operational" or domainKey == "operational" then
        if requestedDomain == "operational" then
          addDomain("loot")
          addDomain("session")
        end
        return
      end
      normalizedByKey[domainKey] = true
    end

    for _, domain in ipairs(requested) do
      addDomain(domain)
    end
    if not next(normalizedByKey) then
      for _, domain in ipairs(PROFILE_TRANSFER_DOMAINS) do
        normalizedByKey[domain] = true
      end
    end

    local normalized = {}
    for _, domain in ipairs(PROFILE_TRANSFER_DOMAINS) do
      if normalizedByKey[domain] then
        normalized[#normalized + 1] = domain
      end
    end
    return normalized
  end

  local function BuildLootProfileDomainRevisionEntry(profile, domain)
    local domainKey = NormalizeLootProfileDomainKey(domain)
    local domainRevisions = EnsureLootProfileRevisionState(profile)
    local entry = type(domainRevisions[domainKey]) == "table" and domainRevisions[domainKey] or {}
    return {
      revision = GetLootProfileDomainRevision(profile, domainKey),
      updatedAt = math.max(0, tonumber(entry.updatedAt) or 0),
      checksum = GetLootProfileDomainChecksum(profile, domainKey),
    }
  end

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

  local function DecodeLootProfileSubdomainToken(value)
    local text = tostring(value or "")
    if text == "" then
      return ""
    end
    return (text:gsub("%%(%x%x)", function(hex)
      return string.char(tonumber(hex, 16) or 0)
    end))
  end

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

  local function CollectSortedTextKeys(source)
    local keys = {}
    for key in pairs(type(source) == "table" and source or {}) do
      local resolved = TrimText(key)
      if resolved ~= "" then
        keys[#keys + 1] = resolved
      end
    end
    table.sort(keys, function(left, right)
      return string.lower(tostring(left)) < string.lower(tostring(right))
    end)
    return keys
  end

  local function BuildLootProfileSessionRecordIdentity(session, index)
    local sessionId = TrimText(type(session) == "table" and session.id or "")
    if sessionId ~= "" then
      return "id:" .. sessionId
    end
    local startedAt = math.max(0, tonumber(type(session) == "table" and session.startedAt) or 0)
    local host = TrimText(type(session) == "table" and session.host or "")
    return "stamp:" .. tostring(startedAt) .. ":" .. host
  end

  local function FindLootProfileSessionRecordIndex(sessions, identity)
    local resolvedIdentity = TrimText(identity)
    if resolvedIdentity == "" then
      return nil
    end
    for index, session in ipairs(type(sessions) == "table" and sessions or {}) do
      if BuildLootProfileSessionRecordIdentity(session, index) == resolvedIdentity then
        return index
      end
    end
    return nil
  end

  local function BuildLootProfileLiveBoardIdentity(snapshot, index)
    local boardId = TrimText(type(snapshot) == "table" and snapshot.boardId or "")
    if boardId ~= "" then
      return "board:" .. boardId
    end
    local sessionId = TrimText(type(snapshot) == "table" and snapshot.sessionId or "")
    if sessionId ~= "" then
      return "session:" .. sessionId
    end
    local updatedAt = math.max(0, tonumber(type(snapshot) == "table" and snapshot.updatedAt) or 0)
    local createdAt = math.max(0, tonumber(type(snapshot) == "table" and snapshot.createdAt) or 0)
    return "stamp:" .. tostring(updatedAt) .. ":" .. tostring(createdAt)
  end

  local function FindLootProfileLiveBoardIndex(history, identity)
    local resolvedIdentity = TrimText(identity)
    if resolvedIdentity == "" then
      return nil
    end
    for index, snapshot in ipairs(type(history) == "table" and history or {}) do
      if BuildLootProfileLiveBoardIdentity(snapshot, index) == resolvedIdentity then
        return index
      end
    end
    return nil
  end

  local function ValuesMatchForPatch(left, right)
    return CalculateStableChecksum(left) == CalculateStableChecksum(right)
  end

  local function PatchKeyedTableMap(existingMap, incomingMap)
    existingMap = type(existingMap) == "table" and existingMap or {}
    incomingMap = type(incomingMap) == "table" and incomingMap or {}
    for key in pairs(existingMap) do
      if incomingMap[key] == nil then
        existingMap[key] = nil
      end
    end
    for key, value in pairs(incomingMap) do
      if not ValuesMatchForPatch(existingMap[key], value) then
        existingMap[key] = DeepCopy(value)
      end
    end
    return existingMap
  end

  local function PatchSequentialTable(existingList, incomingList)
    existingList = type(existingList) == "table" and existingList or {}
    incomingList = type(incomingList) == "table" and incomingList or {}
    if ValuesMatchForPatch(existingList, incomingList) then
      return existingList
    end
    local rebuilt = {}
    for index, value in ipairs(incomingList) do
      rebuilt[index] = DeepCopy(value)
    end
    return rebuilt
  end

  local function BuildPatchedListIdentity(value, index, identityKey)
    local identity = TrimText(type(value) == "table" and value[identityKey] or "")
    if identity ~= "" then
      return identity
    end
    return "#" .. tostring(math.max(0, tonumber(index) or 0))
  end

  local function PatchLootLedgerRowPayload(existingRow, incomingRow, characterKey)
    existingRow = type(existingRow) == "table" and existingRow or {}
    incomingRow = type(incomingRow) == "table" and incomingRow or {}

    for key in pairs(existingRow) do
      if key ~= "items" and key ~= "totalPoints" and incomingRow[key] == nil then
        existingRow[key] = nil
      end
    end
    for key, value in pairs(incomingRow) do
      if key ~= "items" and key ~= "totalPoints" and not ValuesMatchForPatch(existingRow[key], value) then
        existingRow[key] = DeepCopy(value)
      end
    end

    local existingByIdentity = {}
    for index, item in ipairs(type(existingRow.items) == "table" and existingRow.items or {}) do
      existingByIdentity[BuildPatchedListIdentity(item, index, "entryId")] = item
    end

    local rebuiltItems = {}
    for index, item in ipairs(type(incomingRow.items) == "table" and incomingRow.items or {}) do
      local identity = BuildPatchedListIdentity(item, index, "entryId")
      local currentItem = existingByIdentity[identity]
      if ValuesMatchForPatch(currentItem, item) then
        rebuiltItems[#rebuiltItems + 1] = currentItem
      else
        rebuiltItems[#rebuiltItems + 1] = DeepCopy(item)
      end
    end
    existingRow.items = rebuiltItems
    existingRow.character = TrimText(existingRow.character) ~= "" and existingRow.character or characterKey
    RecalculateLootLedgerRowTotal(existingRow)
    return existingRow
  end

  local function PatchLootListGroupPayload(existingGroup, incomingGroup, groupName)
    existingGroup = type(existingGroup) == "table" and existingGroup or {}
    incomingGroup = type(incomingGroup) == "table" and incomingGroup or {}
    if existingGroup.collapsed ~= (incomingGroup.collapsed == true) then
      existingGroup.collapsed = incomingGroup.collapsed == true
    end
    local resolvedName = TrimText(incomingGroup.name) ~= "" and TrimText(incomingGroup.name) or groupName
    if TrimText(existingGroup.name) ~= resolvedName then
      existingGroup.name = resolvedName
    end
    existingGroup.members = PatchSequentialTable(existingGroup.members, incomingGroup.members)
    return existingGroup
  end

  local function PatchSessionRecordPayload(existingSession, incomingSession)
    existingSession = type(existingSession) == "table" and existingSession or {}
    incomingSession = type(incomingSession) == "table" and incomingSession or {}
    for key in pairs(existingSession) do
      if incomingSession[key] == nil then
        existingSession[key] = nil
      end
    end
    for key, value in pairs(incomingSession) do
      if key == "members" then
        existingSession.members = PatchKeyedTableMap(existingSession.members, value)
      elseif key == "rollOptions" then
        existingSession.rollOptions = PatchSequentialTable(existingSession.rollOptions, value)
      elseif not ValuesMatchForPatch(existingSession[key], value) then
        existingSession[key] = DeepCopy(value)
      end
    end
    return existingSession
  end

  local function PatchLiveBoardEntryPayload(existingEntry, incomingEntry)
    existingEntry = type(existingEntry) == "table" and existingEntry or {}
    incomingEntry = type(incomingEntry) == "table" and incomingEntry or {}
    for key in pairs(existingEntry) do
      if incomingEntry[key] == nil then
        existingEntry[key] = nil
      end
    end
    for key, value in pairs(incomingEntry) do
      if key == "selections" then
        existingEntry.selections = PatchKeyedTableMap(existingEntry.selections, value)
      elseif not ValuesMatchForPatch(existingEntry[key], value) then
        existingEntry[key] = DeepCopy(value)
      end
    end
    return existingEntry
  end

  local function PatchLiveBoardSnapshotPayload(existingSnapshot, incomingSnapshot)
    existingSnapshot = type(existingSnapshot) == "table" and existingSnapshot or {}
    incomingSnapshot = type(incomingSnapshot) == "table" and incomingSnapshot or {}
    for key in pairs(existingSnapshot) do
      if incomingSnapshot[key] == nil then
        existingSnapshot[key] = nil
      end
    end
    for key, value in pairs(incomingSnapshot) do
      if key == "items" then
        local items = type(existingSnapshot.items) == "table" and existingSnapshot.items or {}
        for itemKey in pairs(items) do
          if type(value) ~= "table" or value[itemKey] == nil then
            items[itemKey] = nil
          end
        end
        for itemKey, incomingEntry in pairs(type(value) == "table" and value or {}) do
          items[itemKey] = PatchLiveBoardEntryPayload(items[itemKey], incomingEntry)
        end
        existingSnapshot.items = items
      elseif key == "itemOrder" then
        existingSnapshot.itemOrder = PatchSequentialTable(existingSnapshot.itemOrder, value)
      elseif not ValuesMatchForPatch(existingSnapshot[key], value) then
        existingSnapshot[key] = DeepCopy(value)
      end
    end
    return existingSnapshot
  end

  local function SortPatchKeys(keys)
    table.sort(keys, function(left, right)
      return string.lower(tostring(left)) < string.lower(tostring(right))
    end)
    return keys
  end

  local function BuildPatchScalarSource(source, omittedKeys)
    local copy = {}
    for key, value in pairs(type(source) == "table" and source or {}) do
      if not (type(key) == "string" and type(omittedKeys) == "table" and omittedKeys[key] == true) then
        copy[key] = DeepCopy(value)
      end
    end
    return copy
  end

  local function ApplyPatchScalarSource(target, fields, preservedKeys)
    target = type(target) == "table" and target or {}
    fields = type(fields) == "table" and fields or {}
    preservedKeys = type(preservedKeys) == "table" and preservedKeys or {}
    for key in pairs(target) do
      if not preservedKeys[key] and fields[key] == nil then
        target[key] = nil
      end
    end
    for key, value in pairs(fields) do
      if not preservedKeys[key] and not ValuesMatchForPatch(target[key], value) then
        target[key] = DeepCopy(value)
      end
    end
    return target
  end

  local function BuildStrictIdentityMap(items, identityKey)
    local byIdentity = {}
    local order = {}
    for _, item in ipairs(type(items) == "table" and items or {}) do
      local identity = TrimText(type(item) == "table" and item[identityKey] or "")
      if identity == "" or byIdentity[identity] ~= nil then
        return nil, nil
      end
      byIdentity[identity] = item
      order[#order + 1] = identity
    end
    return byIdentity, order
  end

  local function BuildPatchChecksumMap(sourceMap)
    local output = {}
    for key, value in pairs(type(sourceMap) == "table" and sourceMap or {}) do
      local normalizedKey = tostring(key)
      if normalizedKey ~= "" then
        output[normalizedKey] = CalculateStableChecksum(value)
      end
    end
    return output
  end

  local function BuildPatchKeyedChanges(localMap, remoteChecksums)
    local changed = {}
    local removed = {}
    local localSource = type(localMap) == "table" and localMap or {}
    local remoteSource = type(remoteChecksums) == "table" and remoteChecksums or {}
    for key, value in pairs(localSource) do
      local normalizedKey = tostring(key)
      if normalizedKey ~= "" and TrimText(remoteSource[normalizedKey]) ~= CalculateStableChecksum(value) then
        changed[normalizedKey] = DeepCopy(value)
      end
    end
    for key in pairs(remoteSource) do
      if localSource[key] == nil then
        removed[#removed + 1] = tostring(key)
      end
    end
    SortPatchKeys(removed)
    return changed, removed
  end

  local function ApplyKeyedPatch(existingMap, changedValues, removedKeys)
    existingMap = type(existingMap) == "table" and existingMap or {}
    for _, key in ipairs(type(removedKeys) == "table" and removedKeys or {}) do
      existingMap[key] = nil
    end
    for key, value in pairs(type(changedValues) == "table" and changedValues or {}) do
      existingMap[key] = DeepCopy(value)
    end
    return existingMap
  end

  local nestedPatchHelpers = (function(factory)
    if type(factory) ~= "function" then
      error("LidCouncil missing core nested patch helpers.")
    end
    return factory({
      TrimText = TrimText,
      DeepCopy = DeepCopy,
      CalculateStableChecksum = CalculateStableChecksum,
      BuildStrictIdentityMap = BuildStrictIdentityMap,
      BuildPatchKeyedChanges = BuildPatchKeyedChanges,
      BuildPatchScalarSource = BuildPatchScalarSource,
      ApplyPatchScalarSource = ApplyPatchScalarSource,
      SortPatchKeys = SortPatchKeys,
    })
  end)(rawget(_G, "LIDCOUNCIL_CreateCoreNestedPatchHelpers_Impl"))

  local conflictResolverHelpers = (function(factory)
    if type(factory) ~= "function" then
      error("LidCouncil missing core profile conflict resolver helpers.")
    end
    return factory({
      TrimText = TrimText,
      DeepCopy = DeepCopy,
      CalculateStableChecksum = CalculateStableChecksum,
      BuildStrictIdentityMap = BuildStrictIdentityMap,
      SortPatchKeys = SortPatchKeys,
    })
  end)(rawget(_G, "LIDCOUNCIL_CreateCoreProfileConflictResolverHelpers_Impl"))

  local PROFILE_PATCH_LOOT_ROW_OMITTED_KEYS = {
    items = true,
    totalPoints = true,
  }

  local PROFILE_PATCH_SESSION_OMITTED_KEYS = {
    members = true,
    rollOptions = true,
  }

  local PROFILE_PATCH_LIVE_BOARD_OMITTED_KEYS = {
    items = true,
    itemOrder = true,
  }

  local function BuildLootLedgerRowPatchManifest(payload)
    payload = type(payload) == "table" and payload or {}
    if payload.deleted == true or type(payload.row) ~= "table" then
      return {
        kind = "loot_row",
        deleted = true,
        character = TrimText(payload.character),
      }
    end
    local row = payload.row
    local itemsByIdentity, itemOrder = BuildStrictIdentityMap(row.items, "entryId")
    if not itemsByIdentity then
      return nil
    end
    local itemChecksums = {}
    for identity, item in pairs(itemsByIdentity) do
      itemChecksums[identity] = CalculateStableChecksum(item)
    end
    return {
      kind = "loot_row",
      deleted = false,
      character = TrimText(payload.character),
      fieldsChecksum = CalculateStableChecksum(BuildPatchScalarSource(row, PROFILE_PATCH_LOOT_ROW_OMITTED_KEYS)),
      itemOrderChecksum = CalculateStableChecksum(itemOrder),
      itemChecksums = itemChecksums,
    }
  end

  local function BuildLootLedgerRowPatchPayload(payload, remoteDetail)
    payload = type(payload) == "table" and payload or {}
    remoteDetail = type(remoteDetail) == "table" and remoteDetail or {}
    local characterKey = TrimText(payload.character)
    if payload.deleted == true or type(payload.row) ~= "table" then
      return {
        kind = "loot_row",
        deleted = true,
        character = characterKey,
      }
    end
    if remoteDetail.kind ~= "loot_row" and remoteDetail.deleted ~= true then
      return nil
    end

    local row = payload.row
    local fields = BuildPatchScalarSource(row, PROFILE_PATCH_LOOT_ROW_OMITTED_KEYS)
    local itemsByIdentity, itemOrder = BuildStrictIdentityMap(row.items, "entryId")
    if not itemsByIdentity then
      return nil
    end

    local changedItems = {}
    local removedItems = {}
    local remoteItemChecksums = type(remoteDetail.itemChecksums) == "table" and remoteDetail.itemChecksums or {}
    for identity, item in pairs(itemsByIdentity) do
      if TrimText(remoteItemChecksums[identity]) ~= CalculateStableChecksum(item) then
        changedItems[identity] = DeepCopy(item)
      end
    end
    for identity in pairs(remoteItemChecksums) do
      if itemsByIdentity[identity] == nil then
        removedItems[#removedItems + 1] = identity
      end
    end
    SortPatchKeys(removedItems)

    local patch = {
      kind = "loot_row",
      deleted = false,
      character = characterKey,
    }
    if remoteDetail.deleted == true or TrimText(remoteDetail.fieldsChecksum) ~= CalculateStableChecksum(fields) then
      patch.fields = fields
    end
    if remoteDetail.deleted == true
      or TrimText(remoteDetail.itemOrderChecksum) ~= CalculateStableChecksum(itemOrder)
      or next(changedItems) ~= nil
      or #removedItems > 0
    then
      patch.itemOrder = itemOrder
    end
    if next(changedItems) ~= nil then
      patch.changedItems = changedItems
    end
    if #removedItems > 0 then
      patch.removedItems = removedItems
    end
    if patch.fields == nil and patch.itemOrder == nil and patch.changedItems == nil and patch.removedItems == nil then
      return nil
    end
    return patch
  end

  local function ApplyLootLedgerRowPatchPayload(profile, characterKey, patch)
    patch = type(patch) == "table" and patch or {}
    profile.lootLedger = type(profile.lootLedger) == "table" and profile.lootLedger or {}
    if patch.deleted == true then
      profile.lootLedger[characterKey] = nil
      return
    end

    local row = type(profile.lootLedger[characterKey]) == "table" and profile.lootLedger[characterKey] or {}
    if type(patch.fields) == "table" then
      ApplyPatchScalarSource(row, patch.fields, PROFILE_PATCH_LOOT_ROW_OMITTED_KEYS)
    end

    if type(patch.itemOrder) == "table" or type(patch.changedItems) == "table" or type(patch.removedItems) == "table" then
      local currentItemsByIdentity = select(1, BuildStrictIdentityMap(row.items, "entryId")) or {}
      for _, identity in ipairs(type(patch.removedItems) == "table" and patch.removedItems or {}) do
        currentItemsByIdentity[identity] = nil
      end
      for identity, item in pairs(type(patch.changedItems) == "table" and patch.changedItems or {}) do
        currentItemsByIdentity[identity] = DeepCopy(item)
      end

      local rebuiltItems = {}
      local seen = {}
      for _, identity in ipairs(type(patch.itemOrder) == "table" and patch.itemOrder or {}) do
        if currentItemsByIdentity[identity] ~= nil then
          rebuiltItems[#rebuiltItems + 1] = currentItemsByIdentity[identity]
          seen[identity] = true
        end
      end
      local extraIdentities = {}
      for identity in pairs(currentItemsByIdentity) do
        if not seen[identity] then
          extraIdentities[#extraIdentities + 1] = identity
        end
      end
      SortPatchKeys(extraIdentities)
      for _, identity in ipairs(extraIdentities) do
        rebuiltItems[#rebuiltItems + 1] = currentItemsByIdentity[identity]
      end
      row.items = rebuiltItems
    end

    row.character = TrimText(row.character) ~= "" and row.character or characterKey
    RecalculateLootLedgerRowTotal(row)
    profile.lootLedger[characterKey] = row
  end

  local function BuildKeyedMapPatchManifest(kind, payload)
    payload = type(payload) == "table" and payload or {}
    local entries = payload.entries
    if payload.deleted == true or type(entries) ~= "table" then
      return {
        kind = kind,
        deleted = true,
      }
    end
    return {
      kind = kind,
      deleted = false,
      entryChecksums = BuildPatchChecksumMap(entries),
    }
  end

  local function BuildKeyedMapPatchPayload(kind, payload, remoteDetail)
    payload = type(payload) == "table" and payload or {}
    remoteDetail = type(remoteDetail) == "table" and remoteDetail or {}
    local entries = payload.entries
    if payload.deleted == true or type(entries) ~= "table" then
      return {
        kind = kind,
        deleted = true,
      }
    end
    if remoteDetail.kind ~= kind and remoteDetail.deleted ~= true then
      return nil
    end
    local changed, removed = BuildPatchKeyedChanges(entries, remoteDetail.entryChecksums)
    if next(changed) == nil and #removed == 0 then
      return nil
    end
    return {
      kind = kind,
      deleted = false,
      changedEntries = next(changed) ~= nil and changed or nil,
      removedEntries = #removed > 0 and removed or nil,
    }
  end

  local function BuildStatsPatchManifest(kind, fields, eventMap)
    return {
      kind = kind,
      deleted = false,
      fieldsChecksum = CalculateStableChecksum(fields or {}),
      entryChecksums = BuildPatchChecksumMap(eventMap),
    }
  end

  local function BuildStatsPatchPayload(kind, fields, eventMap, remoteDetail)
    remoteDetail = type(remoteDetail) == "table" and remoteDetail or {}
    if remoteDetail.kind ~= kind and remoteDetail.deleted ~= true then
      return nil
    end
    local changedEntries, removedEntries = BuildPatchKeyedChanges(eventMap, remoteDetail.entryChecksums)
    local patch = {
      kind = kind,
      deleted = false,
    }
    if remoteDetail.deleted == true or TrimText(remoteDetail.fieldsChecksum) ~= CalculateStableChecksum(fields or {}) then
      patch.fields = DeepCopy(fields or {})
    end
    if next(changedEntries) ~= nil then
      patch.changedEntries = changedEntries
    end
    if #removedEntries > 0 then
      patch.removedEntries = removedEntries
    end
    if patch.fields == nil and patch.changedEntries == nil and patch.removedEntries == nil then
      return nil
    end
    return patch
  end

  local function BuildSessionRecordPatchManifest(payload)
    payload = type(payload) == "table" and payload or {}
    if payload.deleted == true or type(payload.session) ~= "table" then
      return {
        kind = "session_record",
        deleted = true,
        identity = TrimText(payload.identity),
      }
    end
    local session = payload.session
    local rollOptions = type(session.rollOptions) == "table" and session.rollOptions or {}
    local rollOptionsDetail = nestedPatchHelpers.BuildRollOptionsPatchManifest(rollOptions)
    return {
      kind = "session_record",
      deleted = false,
      identity = TrimText(payload.identity),
      fieldsChecksum = CalculateStableChecksum(BuildPatchScalarSource(session, PROFILE_PATCH_SESSION_OMITTED_KEYS)),
      memberChecksums = BuildPatchChecksumMap(session.members),
      rollOptionsChecksum = CalculateStableChecksum(rollOptions),
      rollOptionChecksums = type(rollOptionsDetail) == "table" and rollOptionsDetail.entryChecksums or nil,
      rollOptionOrderChecksum = type(rollOptionsDetail) == "table" and rollOptionsDetail.orderChecksum or nil,
    }
  end

  local function BuildSessionRecordPatchPayload(payload, remoteDetail)
    payload = type(payload) == "table" and payload or {}
    remoteDetail = type(remoteDetail) == "table" and remoteDetail or {}
    local identity = TrimText(payload.identity)
    if payload.deleted == true or type(payload.session) ~= "table" then
      return {
        kind = "session_record",
        deleted = true,
        identity = identity,
      }
    end
    if remoteDetail.kind ~= "session_record" and remoteDetail.deleted ~= true then
      return nil
    end

    local session = payload.session
    local fields = BuildPatchScalarSource(session, PROFILE_PATCH_SESSION_OMITTED_KEYS)
    local changedMembers, removedMembers = BuildPatchKeyedChanges(session.members, remoteDetail.memberChecksums)
    local rollOptions = type(session.rollOptions) == "table" and session.rollOptions or {}
    local patch = {
      kind = "session_record",
      deleted = false,
      identity = identity,
    }
    if remoteDetail.deleted == true or TrimText(remoteDetail.fieldsChecksum) ~= CalculateStableChecksum(fields) then
      patch.fields = fields
    end
    if next(changedMembers) ~= nil then
      patch.changedMembers = changedMembers
    end
    if #removedMembers > 0 then
      patch.removedMembers = removedMembers
    end
    if remoteDetail.deleted == true
      or TrimText(remoteDetail.rollOptionsChecksum) ~= CalculateStableChecksum(rollOptions)
    then
      local rollOptionsPatch = nestedPatchHelpers.BuildRollOptionsPatchPayload(rollOptions, remoteDetail)
      if type(rollOptionsPatch) == "table" then
        patch.rollOptionsPatch = rollOptionsPatch
      else
        patch.rollOptions = DeepCopy(rollOptions)
      end
    end
    if patch.fields == nil
      and patch.changedMembers == nil
      and patch.removedMembers == nil
      and patch.rollOptions == nil
      and patch.rollOptionsPatch == nil then
      return nil
    end
    return patch
  end

  local function ApplySessionRecordPatchPayload(profile, identity, patch)
    patch = type(patch) == "table" and patch or {}
    profile.sessions = type(profile.sessions) == "table" and profile.sessions or {}
    local index = FindLootProfileSessionRecordIndex(profile.sessions, identity)
    if patch.deleted == true then
      if index then
        table.remove(profile.sessions, index)
      end
      return
    end

    local session = index and profile.sessions[index] or {}
    if type(patch.fields) == "table" then
      ApplyPatchScalarSource(session, patch.fields, PROFILE_PATCH_SESSION_OMITTED_KEYS)
    end
    if type(patch.changedMembers) == "table" or type(patch.removedMembers) == "table" then
      session.members = ApplyKeyedPatch(session.members, patch.changedMembers, patch.removedMembers)
    end
    if type(patch.rollOptionsPatch) == "table" then
      session.rollOptions = nestedPatchHelpers.ApplyRollOptionsPatch(session.rollOptions, patch.rollOptionsPatch)
    elseif patch.rollOptions ~= nil then
      session.rollOptions = PatchSequentialTable(session.rollOptions, patch.rollOptions)
    end

    if index then
      profile.sessions[index] = session
    else
      profile.sessions[#profile.sessions + 1] = session
    end
  end

  local function BuildLiveBoardSnapshotPatchManifest(payload)
    payload = type(payload) == "table" and payload or {}
    if payload.deleted == true or type(payload.snapshot) ~= "table" then
      return {
        kind = "live_board",
        deleted = true,
        identity = TrimText(payload.identity),
      }
    end
    local snapshot = payload.snapshot
    local itemChecksums = {}
    local itemDetails = {}
    for itemKey, item in pairs(type(snapshot.items) == "table" and snapshot.items or {}) do
      local normalizedItemKey = tostring(itemKey)
      if normalizedItemKey ~= "" then
        itemChecksums[normalizedItemKey] = CalculateStableChecksum(item)
        local itemDetail = nestedPatchHelpers.BuildLiveBoardItemPatchManifest(item)
        if type(itemDetail) == "table" then
          itemDetails[normalizedItemKey] = itemDetail
        end
      end
    end
    return {
      kind = "live_board",
      deleted = false,
      identity = TrimText(payload.identity),
      fieldsChecksum = CalculateStableChecksum(BuildPatchScalarSource(snapshot, PROFILE_PATCH_LIVE_BOARD_OMITTED_KEYS)),
      itemChecksums = itemChecksums,
      itemDetails = next(itemDetails) ~= nil and itemDetails or nil,
      itemOrderChecksum = CalculateStableChecksum(type(snapshot.itemOrder) == "table" and snapshot.itemOrder or {}),
    }
  end

  local function BuildLiveBoardSnapshotPatchPayload(payload, remoteDetail)
    payload = type(payload) == "table" and payload or {}
    remoteDetail = type(remoteDetail) == "table" and remoteDetail or {}
    local identity = TrimText(payload.identity)
    if payload.deleted == true or type(payload.snapshot) ~= "table" then
      return {
        kind = "live_board",
        deleted = true,
        identity = identity,
      }
    end
    if remoteDetail.kind ~= "live_board" and remoteDetail.deleted ~= true then
      return nil
    end

    local snapshot = payload.snapshot
    local fields = BuildPatchScalarSource(snapshot, PROFILE_PATCH_LIVE_BOARD_OMITTED_KEYS)
    local changedItems = {}
    local removedItems = {}
    local localItemKeys = {}
    local remoteItemChecksums = type(remoteDetail.itemChecksums) == "table" and remoteDetail.itemChecksums or {}
    local remoteItemDetails = type(remoteDetail.itemDetails) == "table" and remoteDetail.itemDetails or {}
    for itemKey, item in pairs(type(snapshot.items) == "table" and snapshot.items or {}) do
      local normalizedItemKey = tostring(itemKey)
      if normalizedItemKey ~= "" then
        localItemKeys[normalizedItemKey] = true
        if remoteDetail.deleted == true or TrimText(remoteItemChecksums[normalizedItemKey]) ~= CalculateStableChecksum(item) then
          local itemPatch = type(remoteItemDetails[normalizedItemKey]) == "table"
            and nestedPatchHelpers.BuildLiveBoardItemPatchPayload(item, remoteItemDetails[normalizedItemKey])
            or nil
          changedItems[normalizedItemKey] = type(itemPatch) == "table" and itemPatch or DeepCopy(item)
        end
      end
    end
    for itemKey in pairs(remoteItemChecksums) do
      if not localItemKeys[tostring(itemKey)] then
        removedItems[#removedItems + 1] = tostring(itemKey)
      end
    end
    SortPatchKeys(removedItems)
    local patch = {
      kind = "live_board",
      deleted = false,
      identity = identity,
    }
    if remoteDetail.deleted == true or TrimText(remoteDetail.fieldsChecksum) ~= CalculateStableChecksum(fields) then
      patch.fields = fields
    end
    if next(changedItems) ~= nil then
      patch.changedItems = changedItems
    end
    if #removedItems > 0 then
      patch.removedItems = removedItems
    end
    if remoteDetail.deleted == true
      or TrimText(remoteDetail.itemOrderChecksum) ~= CalculateStableChecksum(type(snapshot.itemOrder) == "table" and snapshot.itemOrder or {})
    then
      patch.itemOrder = DeepCopy(type(snapshot.itemOrder) == "table" and snapshot.itemOrder or {})
    end
    if patch.fields == nil and patch.changedItems == nil and patch.removedItems == nil and patch.itemOrder == nil then
      return nil
    end
    return patch
  end

  local function ApplyLiveBoardSnapshotPatchPayload(profile, identity, patch)
    patch = type(patch) == "table" and patch or {}
    profile.liveBoardHistory = type(profile.liveBoardHistory) == "table" and profile.liveBoardHistory or {}
    local index = FindLootProfileLiveBoardIndex(profile.liveBoardHistory, identity)
    if patch.deleted == true then
      if index then
        table.remove(profile.liveBoardHistory, index)
      end
      return
    end

    local snapshot = index and profile.liveBoardHistory[index] or {}
    if type(patch.fields) == "table" then
      ApplyPatchScalarSource(snapshot, patch.fields, PROFILE_PATCH_LIVE_BOARD_OMITTED_KEYS)
    end
    if type(patch.changedItems) == "table" or type(patch.removedItems) == "table" then
      snapshot.items = type(snapshot.items) == "table" and snapshot.items or {}
      for _, itemKey in ipairs(type(patch.removedItems) == "table" and patch.removedItems or {}) do
        snapshot.items[itemKey] = nil
      end
      for itemKey, itemPayload in pairs(type(patch.changedItems) == "table" and patch.changedItems or {}) do
        if type(itemPayload) == "table" and itemPayload.kind == "live_board_item" then
          snapshot.items[itemKey] = nestedPatchHelpers.ApplyLiveBoardItemPatchPayload(snapshot.items[itemKey], itemPayload, itemKey)
        else
          snapshot.items[itemKey] = DeepCopy(itemPayload)
        end
      end
    end
    if patch.itemOrder ~= nil then
      snapshot.itemOrder = PatchSequentialTable(snapshot.itemOrder, patch.itemOrder)
    end

    if index then
      profile.liveBoardHistory[index] = snapshot
      local updated = table.remove(profile.liveBoardHistory, index)
      table.insert(profile.liveBoardHistory, 1, updated)
    else
      profile.liveBoardHistory[#profile.liveBoardHistory + 1] = snapshot
    end
    while #profile.liveBoardHistory > 40 do
      table.remove(profile.liveBoardHistory)
    end
  end

  local PROFILE_TRANSFER_SUBDOMAIN_DEFS = {
    {
      key = "settings_raid",
      domain = "settings",
      label = "Raid Setup",
      source = function(profile)
        return {
          raid = DeepCopy(type(profile.settings) == "table" and profile.settings.raid or {}),
        }
      end,
      apply = function(profile, payload)
        profile.settings.raid = DeepCopy(type(payload) == "table" and payload.raid or {})
      end,
    },
    {
      key = "settings_roll",
      domain = "settings",
      label = "Roll Options",
      source = function(profile)
        return {
          rollTemplate = type(profile.settings) == "table" and profile.settings.rollTemplate or nil,
          rollOptions = DeepCopy(type(profile.settings) == "table" and profile.settings.rollOptions or {}),
        }
      end,
      apply = function(profile, payload)
        payload = type(payload) == "table" and payload or {}
        profile.settings.rollTemplate = payload.rollTemplate
        profile.settings.rollOptions = DeepCopy(payload.rollOptions or {})
      end,
    },
    {
      key = "settings_point_mode",
      domain = "settings",
      label = "Point Mode",
      source = function(profile)
        return {
          pointMode = type(profile.settings) == "table" and profile.settings.pointMode or nil,
        }
      end,
      apply = function(profile, payload)
        profile.settings.pointMode = type(payload) == "table" and payload.pointMode or nil
      end,
    },
    {
      key = "settings_lid_table",
      domain = "settings",
      label = "Lid Table",
      source = function(profile)
        return {
          lidTable = DeepCopy(type(profile.settings) == "table" and profile.settings.lidTable or {}),
        }
      end,
      apply = function(profile, payload)
        profile.settings.lidTable = DeepCopy(type(payload) == "table" and payload.lidTable or {})
      end,
    },
    {
      key = "settings_point_rules",
      domain = "settings",
      label = "Point Rules",
      source = function(profile)
        return {
          pointRules = DeepCopy(type(profile.settings) == "table" and profile.settings.pointRules or {}),
        }
      end,
      apply = function(profile, payload)
        profile.settings.pointRules = DeepCopy(type(payload) == "table" and payload.pointRules or {})
      end,
    },
    {
      key = "permissions_members",
      domain = "permissions",
      label = "Member Roles",
      source = function(profile)
        local meta = type(profile.meta) == "table" and profile.meta or {}
        return {
          permissions = DeepCopy(meta.permissions or {}),
        }
      end,
      apply = function(profile, payload)
        profile.meta.permissions = DeepCopy(type(payload) == "table" and payload.permissions or {})
      end,
    },
    {
      key = "permissions_policy",
      domain = "permissions",
      label = "Rights Policy",
      source = function(profile)
        local meta = type(profile.meta) == "table" and profile.meta or {}
        return {
          permissionPolicy = DeepCopy(meta.permissionPolicy or {}),
        }
      end,
      apply = function(profile, payload)
        profile.meta.permissionPolicy = DeepCopy(type(payload) == "table" and payload.permissionPolicy or {})
      end,
    },
    {
      key = "lls",
      domain = "loot",
      label = "Loot Ledger Serial",
      source = function(profile)
        return {
          lootLedgerEntrySerial = tonumber(profile.lootLedgerEntrySerial) or 0,
        }
      end,
      apply = function(profile, payload)
        payload = type(payload) == "table" and payload or {}
        profile.lootLedgerEntrySerial = math.max(
          tonumber(profile.lootLedgerEntrySerial) or 0,
          tonumber(payload.lootLedgerEntrySerial) or 0
        )
      end,
    },
    {
      key = "lrsr",
      domain = "loot",
      label = "Fun Award Rolls",
      source = function(profile)
        local stats = type(profile.lootRollStats) == "table" and profile.lootRollStats or {}
        return {
          schemaVersion = tonumber(stats.schemaVersion) or nil,
          updatedAt = tonumber(stats.updatedAt) or nil,
          events = DeepCopy(stats.events or {}),
        }
      end,
      apply = function(profile, payload)
        payload = type(payload) == "table" and payload or {}
        profile.lootRollStats = type(profile.lootRollStats) == "table" and profile.lootRollStats or {}
        profile.lootRollStats.schemaVersion = tonumber(payload.schemaVersion) or profile.lootRollStats.schemaVersion
        profile.lootRollStats.updatedAt = tonumber(payload.updatedAt) or profile.lootRollStats.updatedAt
        profile.lootRollStats.events = PatchKeyedTableMap(profile.lootRollStats.events, payload.events)
      end,
    },
    {
      key = "lrsv",
      domain = "loot",
      label = "Vote History",
      source = function(profile)
        local stats = type(profile.lootRollStats) == "table" and profile.lootRollStats or {}
        return {
          schemaVersion = tonumber(stats.schemaVersion) or nil,
          voteUpdatedAt = tonumber(stats.voteUpdatedAt) or nil,
          voteEvents = DeepCopy(stats.voteEvents or {}),
        }
      end,
      apply = function(profile, payload)
        payload = type(payload) == "table" and payload or {}
        profile.lootRollStats = type(profile.lootRollStats) == "table" and profile.lootRollStats or {}
        profile.lootRollStats.schemaVersion = tonumber(payload.schemaVersion) or profile.lootRollStats.schemaVersion
        profile.lootRollStats.voteUpdatedAt = tonumber(payload.voteUpdatedAt) or profile.lootRollStats.voteUpdatedAt
        profile.lootRollStats.voteEvents = PatchKeyedTableMap(profile.lootRollStats.voteEvents, payload.voteEvents)
      end,
    },
    {
      key = "loot_ledger",
      domain = "loot",
      label = "Loot Ledger",
      legacy = true,
      source = function(profile)
        return {
          lootLedger = DeepCopy(profile.lootLedger or {}),
          lootLedgerEntrySerial = tonumber(profile.lootLedgerEntrySerial) or 0,
        }
      end,
      apply = function(profile, payload)
        payload = type(payload) == "table" and payload or {}
        profile.lootLedger = DeepCopy(payload.lootLedger or {})
        profile.lootLedgerEntrySerial = tonumber(payload.lootLedgerEntrySerial) or 0
      end,
    },
    {
      key = "loot_meta",
      domain = "loot",
      label = "Ledger Meta",
      legacy = true,
      source = function(profile)
        return {
          lootLedgerMeta = DeepCopy(profile.lootLedgerMeta or {}),
        }
      end,
      apply = function(profile, payload)
        profile.lootLedgerMeta = DeepCopy(type(payload) == "table" and payload.lootLedgerMeta or {})
      end,
    },
    {
      key = "loot_roll_stats",
      domain = "loot",
      label = "Fun Awards",
      legacy = true,
      source = function(profile)
        return {
          lootRollStats = DeepCopy(profile.lootRollStats or {}),
        }
      end,
      apply = function(profile, payload)
        profile.lootRollStats = DeepCopy(type(payload) == "table" and payload.lootRollStats or {})
      end,
    },
    {
      key = "loot_list_groups",
      domain = "loot",
      label = "Loot List Groups",
      legacy = true,
      source = function(profile)
        return {
          lootListGroups = DeepCopy(profile.lootListGroups or {}),
        }
      end,
      apply = function(profile, payload)
        profile.lootListGroups = DeepCopy(type(payload) == "table" and payload.lootListGroups or {})
      end,
    },
    {
      key = "session_sessions",
      domain = "session",
      label = "Session Records",
      legacy = true,
      source = function(profile)
        return {
          sessions = DeepCopy(profile.sessions or {}),
        }
      end,
      apply = function(profile, payload)
        profile.sessions = DeepCopy(type(payload) == "table" and payload.sessions or {})
      end,
    },
    {
      key = "session_live_board",
      domain = "session",
      label = "Live Board History",
      legacy = true,
      source = function(profile)
        return {
          liveBoardHistory = DeepCopy(profile.liveBoardHistory or {}),
        }
      end,
      apply = function(profile, payload)
        profile.liveBoardHistory = DeepCopy(type(payload) == "table" and payload.liveBoardHistory or {})
      end,
    },
  }
  local PROFILE_TRANSFER_SUBDOMAINS_BY_KEY = {}
  local PROFILE_TRANSFER_SUBDOMAINS_BY_DOMAIN = {}
  for _, def in ipairs(PROFILE_TRANSFER_SUBDOMAIN_DEFS) do
    PROFILE_TRANSFER_SUBDOMAINS_BY_KEY[def.key] = def
    PROFILE_TRANSFER_SUBDOMAINS_BY_DOMAIN[def.domain] = PROFILE_TRANSFER_SUBDOMAINS_BY_DOMAIN[def.domain] or {}
    PROFILE_TRANSFER_SUBDOMAINS_BY_DOMAIN[def.domain][#PROFILE_TRANSFER_SUBDOMAINS_BY_DOMAIN[def.domain] + 1] = def.key
  end

  local PROFILE_TRANSFER_DYNAMIC_SUBDOMAIN_DEFS = {
    {
      prefix = "llr",
      domain = "loot",
      label = function(characterKey)
        return "Loot Ledger: " .. tostring(characterKey)
      end,
      enumerate = function(profile)
        local keys = CollectSortedTextKeys(type(profile) == "table" and profile.lootLedger or nil)
        local output = {}
        for _, characterKey in ipairs(keys) do
          local key = BuildDynamicLootProfileSubdomainKey("llr", characterKey)
          if key ~= "" then
            output[#output + 1] = key
          end
        end
        return output
      end,
      source = function(profile, characterKey)
        local row = type(profile.lootLedger) == "table" and profile.lootLedger[characterKey] or nil
        if type(row) ~= "table" then
          return {
            deleted = true,
            character = characterKey,
          }
        end
        local copy = DeepCopy(row)
        copy.character = TrimText(copy.character) ~= "" and copy.character or characterKey
        RecalculateLootLedgerRowTotal(copy)
        return {
          deleted = false,
          character = characterKey,
          row = copy,
        }
      end,
      checksumSource = function(profile, characterKey)
        local row = type(profile.lootLedger) == "table" and profile.lootLedger[characterKey] or nil
        if type(row) ~= "table" then
          return {
            deleted = true,
            character = characterKey,
          }
        end
        return {
          deleted = false,
          character = characterKey,
          row = BuildNormalizedLootLedgerRowChecksumSource(characterKey, row),
        }
      end,
      apply = function(profile, characterKey, payload)
        payload = type(payload) == "table" and payload or {}
        profile.lootLedger = type(profile.lootLedger) == "table" and profile.lootLedger or {}
        if payload.deleted == true or type(payload.row) ~= "table" then
          profile.lootLedger[characterKey] = nil
          return
        end
        profile.lootLedger[characterKey] = PatchLootLedgerRowPayload(profile.lootLedger[characterKey], payload.row, characterKey)
      end,
    },
    {
      prefix = "lmr",
      domain = "loot",
      label = function(characterKey)
        return "Member Meta: " .. tostring(characterKey)
      end,
      enumerate = function(profile)
        local keys = CollectSortedTextKeys(type(profile) == "table" and profile.lootLedgerMeta or nil)
        local output = {}
        for _, characterKey in ipairs(keys) do
          local key = BuildDynamicLootProfileSubdomainKey("lmr", characterKey)
          if key ~= "" then
            output[#output + 1] = key
          end
        end
        return output
      end,
      source = function(profile, characterKey)
        local meta = type(profile.lootLedgerMeta) == "table" and profile.lootLedgerMeta[characterKey] or nil
        if type(meta) ~= "table" then
          return {
            deleted = true,
            character = characterKey,
          }
        end
        return {
          deleted = false,
          character = characterKey,
          meta = DeepCopy(meta),
        }
      end,
      apply = function(profile, characterKey, payload)
        payload = type(payload) == "table" and payload or {}
        profile.lootLedgerMeta = type(profile.lootLedgerMeta) == "table" and profile.lootLedgerMeta or {}
        if payload.deleted == true or type(payload.meta) ~= "table" then
          profile.lootLedgerMeta[characterKey] = nil
          return
        end
        profile.lootLedgerMeta[characterKey] = PatchKeyedTableMap(profile.lootLedgerMeta[characterKey], payload.meta)
      end,
    },
    {
      prefix = "llg",
      domain = "loot",
      label = function(groupName)
        return "Loot Group: " .. tostring(groupName)
      end,
      enumerate = function(profile)
        local output = {}
        for _, group in ipairs(type(profile) == "table" and type(profile.lootListGroups) == "table" and profile.lootListGroups or {}) do
          local groupName = TrimText(type(group) == "table" and group.name or "")
          local key = BuildDynamicLootProfileSubdomainKey("llg", groupName)
          if key ~= "" then
            output[#output + 1] = key
          end
        end
        table.sort(output, function(left, right)
          return string.lower(tostring(left)) < string.lower(tostring(right))
        end)
        return output
      end,
      source = function(profile, groupName)
        local groups = type(profile.lootListGroups) == "table" and profile.lootListGroups or {}
        for _, group in ipairs(groups) do
          if string.lower(TrimText(type(group) == "table" and group.name or "")) == string.lower(groupName) then
            return {
              deleted = false,
              groupName = groupName,
              group = DeepCopy(group),
            }
          end
        end
        return {
          deleted = true,
          groupName = groupName,
        }
      end,
      apply = function(profile, groupName, payload)
        payload = type(payload) == "table" and payload or {}
        profile.lootListGroups = type(profile.lootListGroups) == "table" and profile.lootListGroups or {}
        local foundIndex = nil
        for index, group in ipairs(profile.lootListGroups) do
          if string.lower(TrimText(type(group) == "table" and group.name or "")) == string.lower(groupName) then
            foundIndex = index
            break
          end
        end
        if payload.deleted == true or type(payload.group) ~= "table" then
          if foundIndex then
            table.remove(profile.lootListGroups, foundIndex)
          end
          return
        end
        local copy = PatchLootListGroupPayload(
          foundIndex and profile.lootListGroups[foundIndex] or nil,
          payload.group,
          groupName
        )
        if foundIndex then
          profile.lootListGroups[foundIndex] = copy
        else
          profile.lootListGroups[#profile.lootListGroups + 1] = copy
        end
        table.sort(profile.lootListGroups, function(left, right)
          return string.lower(tostring(type(left) == "table" and left.name or "")) < string.lower(tostring(type(right) == "table" and right.name or ""))
        end)
      end,
    },
    {
      prefix = "ssr",
      domain = "session",
      label = function(identity)
        local display = identity:match("^id:(.+)$") or identity:match("^stamp:(.+)$") or identity
        return "Session Record: " .. tostring(display)
      end,
      enumerate = function(profile)
        local output = {}
        for index, session in ipairs(type(profile) == "table" and type(profile.sessions) == "table" and profile.sessions or {}) do
          local key = BuildDynamicLootProfileSubdomainKey("ssr", BuildLootProfileSessionRecordIdentity(session, index))
          if key ~= "" then
            output[#output + 1] = key
          end
        end
        return output
      end,
      source = function(profile, identity)
        local index = FindLootProfileSessionRecordIndex(type(profile.sessions) == "table" and profile.sessions or {}, identity)
        local session = index and profile.sessions[index] or nil
        if type(session) ~= "table" then
          return {
            deleted = true,
            identity = identity,
          }
        end
        return {
          deleted = false,
          identity = identity,
          session = BuildLootProfileSessionRecordChecksumSource(session),
        }
      end,
      apply = function(profile, identity, payload)
        payload = type(payload) == "table" and payload or {}
        profile.sessions = type(profile.sessions) == "table" and profile.sessions or {}
        local index = FindLootProfileSessionRecordIndex(profile.sessions, identity)
        if payload.deleted == true or type(payload.session) ~= "table" then
          if index then
            table.remove(profile.sessions, index)
          end
          return
        end
        if index then
          profile.sessions[index] = PatchSessionRecordPayload(profile.sessions[index], payload.session)
        else
          profile.sessions[#profile.sessions + 1] = PatchSessionRecordPayload(nil, payload.session)
        end
      end,
    },
    {
      prefix = "slb",
      domain = "session",
      label = function(identity)
        local display = identity:match("^board:(.+)$") or identity:match("^session:(.+)$") or identity:match("^stamp:(.+)$") or identity
        return "Live Board: " .. tostring(display)
      end,
      enumerate = function(profile)
        local output = {}
        for index, snapshot in ipairs(type(profile) == "table" and type(profile.liveBoardHistory) == "table" and profile.liveBoardHistory or {}) do
          local key = BuildDynamicLootProfileSubdomainKey("slb", BuildLootProfileLiveBoardIdentity(snapshot, index))
          if key ~= "" then
            output[#output + 1] = key
          end
        end
        return output
      end,
      source = function(profile, identity)
        local history = type(profile.liveBoardHistory) == "table" and profile.liveBoardHistory or {}
        local index = FindLootProfileLiveBoardIndex(history, identity)
        local snapshot = index and history[index] or nil
        if type(snapshot) ~= "table" then
          return {
            deleted = true,
            identity = identity,
          }
        end
        return {
          deleted = false,
          identity = identity,
          snapshot = DeepCopy(snapshot),
        }
      end,
      apply = function(profile, identity, payload)
        payload = type(payload) == "table" and payload or {}
        profile.liveBoardHistory = type(profile.liveBoardHistory) == "table" and profile.liveBoardHistory or {}
        local index = FindLootProfileLiveBoardIndex(profile.liveBoardHistory, identity)
        if payload.deleted == true or type(payload.snapshot) ~= "table" then
          if index then
            table.remove(profile.liveBoardHistory, index)
          end
          return
        end
        if index then
          profile.liveBoardHistory[index] = PatchLiveBoardSnapshotPayload(profile.liveBoardHistory[index], payload.snapshot)
          local updated = table.remove(profile.liveBoardHistory, index)
          table.insert(profile.liveBoardHistory, 1, updated)
        else
          profile.liveBoardHistory[#profile.liveBoardHistory + 1] = PatchLiveBoardSnapshotPayload(nil, payload.snapshot)
        end
        while #profile.liveBoardHistory > 40 do
          table.remove(profile.liveBoardHistory)
        end
      end,
    },
  }

  local PROFILE_TRANSFER_DYNAMIC_SUBDOMAINS_BY_PREFIX = {}
  for _, def in ipairs(PROFILE_TRANSFER_DYNAMIC_SUBDOMAIN_DEFS) do
    PROFILE_TRANSFER_DYNAMIC_SUBDOMAINS_BY_PREFIX[def.prefix] = def
  end

  local function ParseDynamicLootProfileSubdomainKey(subdomain)
    local raw = TrimText(subdomain)
    local prefix, token = raw:match("^([^:]+):(.*)$")
    prefix = string.lower(TrimText(prefix))
    local def = PROFILE_TRANSFER_DYNAMIC_SUBDOMAINS_BY_PREFIX[prefix]
    if type(def) ~= "table" or TrimText(token) == "" then
      return nil, "", ""
    end
    local identity = DecodeLootProfileSubdomainToken(token)
    local normalizedKey = BuildDynamicLootProfileSubdomainKey(prefix, identity)
    if identity == "" or normalizedKey == "" then
      return nil, "", ""
    end
    return def, normalizedKey, identity
  end

  local function NormalizeLootProfileSubdomainKey(subdomain)
    local raw = TrimText(subdomain)
    local key = string.lower(raw)
    if PROFILE_TRANSFER_SUBDOMAINS_BY_KEY[key] then
      return key
    end
    local _, dynamicKey = ParseDynamicLootProfileSubdomainKey(raw)
    if dynamicKey ~= "" then
      return dynamicKey
    end
    return ""
  end

  local function GetLootProfileSubdomainLabel(subdomain)
    local normalizedKey = NormalizeLootProfileSubdomainKey(subdomain)
    local def = PROFILE_TRANSFER_SUBDOMAINS_BY_KEY[normalizedKey]
    if type(def) == "table" then
      return type(def.label) == "string" and def.label or tostring(def.key or "")
    end
    local dynamicDef, _, identity = ParseDynamicLootProfileSubdomainKey(normalizedKey)
    if type(dynamicDef) == "table" and type(dynamicDef.label) == "function" then
      return tostring(dynamicDef.label(identity))
    end
    return ""
  end

  local function GetLootProfileSubdomainParentDomain(subdomain)
    local normalizedKey = NormalizeLootProfileSubdomainKey(subdomain)
    local def = PROFILE_TRANSFER_SUBDOMAINS_BY_KEY[normalizedKey]
    if type(def) == "table" then
      return tostring(def.domain or "")
    end
    local dynamicDef = select(1, ParseDynamicLootProfileSubdomainKey(normalizedKey))
    return type(dynamicDef) == "table" and tostring(dynamicDef.domain or "") or ""
  end

  local function GetLootProfileSubdomainKeysForDomain(domain, profile)
    local domainKey = NormalizeLootProfileDomainKey(domain)
    local keys = {}
    for _, key in ipairs(PROFILE_TRANSFER_SUBDOMAINS_BY_DOMAIN[domainKey] or {}) do
      local def = PROFILE_TRANSFER_SUBDOMAINS_BY_KEY[key]
      if type(def) == "table" and def.legacy ~= true then
        keys[#keys + 1] = key
      end
    end
    for _, def in ipairs(PROFILE_TRANSFER_DYNAMIC_SUBDOMAIN_DEFS) do
      if def.domain == domainKey and type(def.enumerate) == "function" then
        for _, key in ipairs(def.enumerate(profile) or {}) do
          local normalizedKey = NormalizeLootProfileSubdomainKey(key)
          if normalizedKey ~= "" then
            keys[#keys + 1] = normalizedKey
          end
        end
      end
    end
    return keys
  end

  local function ResolveLootProfileDomainsForSubdomains(subdomains)
    local seen = {}
    local resolved = {}
    for _, subdomain in ipairs(type(subdomains) == "table" and subdomains or {}) do
      local domain = GetLootProfileSubdomainParentDomain(subdomain)
      if domain ~= "" and not seen[domain] then
        seen[domain] = true
        resolved[#resolved + 1] = domain
      end
    end
    if #resolved == 0 then
      for _, domain in ipairs(PROFILE_TRANSFER_DOMAINS) do
        resolved[#resolved + 1] = domain
      end
    end
    return NormalizeLootProfileDomainList(resolved)
  end

  local function NormalizeLootProfileSubdomainList(subdomains, domains, profile)
    local requested = {}
    if type(subdomains) == "string" then
      for token in string.gmatch(subdomains, "[^,%s;|]+") do
        requested[#requested + 1] = token
      end
    elseif type(subdomains) == "table" then
      for _, subdomain in ipairs(subdomains) do
        requested[#requested + 1] = subdomain
      end
    end

    if #requested == 0 then
      for _, domain in ipairs(NormalizeLootProfileDomainList(domains)) do
        for _, key in ipairs(GetLootProfileSubdomainKeysForDomain(domain, profile) or {}) do
          requested[#requested + 1] = key
        end
      end
    end
    if #requested == 0 then
      for _, domain in ipairs(PROFILE_TRANSFER_DOMAINS) do
        for _, key in ipairs(GetLootProfileSubdomainKeysForDomain(domain, profile) or {}) do
          requested[#requested + 1] = key
        end
      end
    end

    local normalizedByKey = {}
    local normalized = {}
    for _, subdomain in ipairs(requested) do
      local subdomainKey = NormalizeLootProfileSubdomainKey(subdomain)
      if subdomainKey ~= "" and not normalizedByKey[subdomainKey] then
        normalizedByKey[subdomainKey] = true
        normalized[#normalized + 1] = subdomainKey
      end
    end
    return normalized
  end

  local function CloneLootProfileSubdomainList(subdomains)
    local clone = {}
    for index, subdomain in ipairs(type(subdomains) == "table" and subdomains or {}) do
      clone[index] = tostring(subdomain)
    end
    return clone
  end

  local BuildLootProfileSubdomainSnapshotSource

  local PROFILE_PATCH_CAPABLE_STATIC_SUBDOMAINS = {
    lrsr = true,
    lrsv = true,
  }

  local PROFILE_PATCH_CAPABLE_DYNAMIC_PREFIXES = {
    llr = true,
    lmr = true,
    ssr = true,
    slb = true,
  }

  local function IsLootProfileSubdomainPatchCapable(subdomain)
    local normalizedKey = NormalizeLootProfileSubdomainKey(subdomain)
    if normalizedKey == "" then
      return false
    end
    if PROFILE_PATCH_CAPABLE_STATIC_SUBDOMAINS[normalizedKey] == true then
      return true
    end
    local dynamicDef = select(1, ParseDynamicLootProfileSubdomainKey(normalizedKey))
    return type(dynamicDef) == "table" and PROFILE_PATCH_CAPABLE_DYNAMIC_PREFIXES[dynamicDef.prefix] == true or false
  end

  local function FilterLootProfilePatchCapableSubdomains(subdomains, domains, profile)
    local filtered = {}
    for _, subdomain in ipairs(NormalizeLootProfileSubdomainList(subdomains, domains, profile)) do
      if IsLootProfileSubdomainPatchCapable(subdomain) then
        filtered[#filtered + 1] = subdomain
      end
    end
    return filtered
  end

  local function BuildLootProfileSubdomainPatchManifestEntry(profile, subdomain)
    local normalizedKey = NormalizeLootProfileSubdomainKey(subdomain)
    if normalizedKey == "" then
      return nil
    end

    local payload = BuildLootProfileSubdomainSnapshotSource(profile, normalizedKey)
    if normalizedKey == "lrsr" then
      payload = type(payload) == "table" and payload or {}
      return BuildStatsPatchManifest("roll_events", {
        schemaVersion = tonumber(payload.schemaVersion) or nil,
        updatedAt = tonumber(payload.updatedAt) or nil,
      }, payload.events)
    elseif normalizedKey == "lrsv" then
      payload = type(payload) == "table" and payload or {}
      return BuildStatsPatchManifest("vote_events", {
        schemaVersion = tonumber(payload.schemaVersion) or nil,
        voteUpdatedAt = tonumber(payload.voteUpdatedAt) or nil,
      }, payload.voteEvents)
    end

    local dynamicDef = select(1, ParseDynamicLootProfileSubdomainKey(normalizedKey))
    if type(dynamicDef) ~= "table" then
      return nil
    end
    if dynamicDef.prefix == "llr" then
      return BuildLootLedgerRowPatchManifest(payload)
    elseif dynamicDef.prefix == "lmr" then
      payload = type(payload) == "table" and payload or {}
      return BuildKeyedMapPatchManifest("ledger_meta", {
        deleted = payload.deleted == true,
        entries = payload.meta,
      })
    elseif dynamicDef.prefix == "ssr" then
      return BuildSessionRecordPatchManifest(payload)
    elseif dynamicDef.prefix == "slb" then
      return BuildLiveBoardSnapshotPatchManifest(payload)
    end
    return nil
  end

  local function BuildLootProfileSubdomainPatchPayloadEntry(profile, subdomain, remoteDetail)
    local normalizedKey = NormalizeLootProfileSubdomainKey(subdomain)
    if normalizedKey == "" then
      return nil
    end

    local payload = BuildLootProfileSubdomainSnapshotSource(profile, normalizedKey)
    if normalizedKey == "lrsr" then
      payload = type(payload) == "table" and payload or {}
      return BuildStatsPatchPayload("roll_events", {
        schemaVersion = tonumber(payload.schemaVersion) or nil,
        updatedAt = tonumber(payload.updatedAt) or nil,
      }, payload.events, remoteDetail)
    elseif normalizedKey == "lrsv" then
      payload = type(payload) == "table" and payload or {}
      return BuildStatsPatchPayload("vote_events", {
        schemaVersion = tonumber(payload.schemaVersion) or nil,
        voteUpdatedAt = tonumber(payload.voteUpdatedAt) or nil,
      }, payload.voteEvents, remoteDetail)
    end

    local dynamicDef, _, identity = ParseDynamicLootProfileSubdomainKey(normalizedKey)
    if type(dynamicDef) ~= "table" then
      return nil
    end
    if dynamicDef.prefix == "llr" then
      return BuildLootLedgerRowPatchPayload(payload, remoteDetail)
    elseif dynamicDef.prefix == "lmr" then
      payload = type(payload) == "table" and payload or {}
      local patch = BuildKeyedMapPatchPayload("ledger_meta", {
        deleted = payload.deleted == true,
        entries = payload.meta,
      }, remoteDetail)
      if type(patch) == "table" then
        patch.character = identity
      end
      return patch
    elseif dynamicDef.prefix == "ssr" then
      return BuildSessionRecordPatchPayload(payload, remoteDetail)
    elseif dynamicDef.prefix == "slb" then
      return BuildLiveBoardSnapshotPatchPayload(payload, remoteDetail)
    end
    return nil
  end

  local function ApplyLootProfileSubdomainPatchPayload(profile, subdomain, payload)
    local normalizedKey = NormalizeLootProfileSubdomainKey(subdomain)
    if normalizedKey == "" then
      return false
    end

    if normalizedKey == "lrsr" then
      payload = type(payload) == "table" and payload or {}
      profile.lootRollStats = type(profile.lootRollStats) == "table" and profile.lootRollStats or {}
      if type(payload.fields) == "table" then
        profile.lootRollStats.schemaVersion = tonumber(payload.fields.schemaVersion) or profile.lootRollStats.schemaVersion
        profile.lootRollStats.updatedAt = tonumber(payload.fields.updatedAt) or profile.lootRollStats.updatedAt
      end
      if payload.deleted == true then
        profile.lootRollStats.events = {}
      else
        profile.lootRollStats.events = ApplyKeyedPatch(profile.lootRollStats.events, payload.changedEntries, payload.removedEntries)
      end
      return true
    elseif normalizedKey == "lrsv" then
      payload = type(payload) == "table" and payload or {}
      profile.lootRollStats = type(profile.lootRollStats) == "table" and profile.lootRollStats or {}
      if type(payload.fields) == "table" then
        profile.lootRollStats.schemaVersion = tonumber(payload.fields.schemaVersion) or profile.lootRollStats.schemaVersion
        profile.lootRollStats.voteUpdatedAt = tonumber(payload.fields.voteUpdatedAt) or profile.lootRollStats.voteUpdatedAt
      end
      if payload.deleted == true then
        profile.lootRollStats.voteEvents = {}
      else
        profile.lootRollStats.voteEvents = ApplyKeyedPatch(profile.lootRollStats.voteEvents, payload.changedEntries, payload.removedEntries)
      end
      return true
    end

    local dynamicDef, _, identity = ParseDynamicLootProfileSubdomainKey(normalizedKey)
    if type(dynamicDef) ~= "table" then
      return false
    end
    if dynamicDef.prefix == "llr" then
      ApplyLootLedgerRowPatchPayload(profile, identity, payload)
      return true
    elseif dynamicDef.prefix == "lmr" then
      payload = type(payload) == "table" and payload or {}
      profile.lootLedgerMeta = type(profile.lootLedgerMeta) == "table" and profile.lootLedgerMeta or {}
      if payload.deleted == true then
        profile.lootLedgerMeta[identity] = nil
      else
        profile.lootLedgerMeta[identity] = ApplyKeyedPatch(profile.lootLedgerMeta[identity], payload.changedEntries, payload.removedEntries)
      end
      return true
    elseif dynamicDef.prefix == "ssr" then
      ApplySessionRecordPatchPayload(profile, identity, payload)
      return true
    elseif dynamicDef.prefix == "slb" then
      ApplyLiveBoardSnapshotPatchPayload(profile, identity, payload)
      return true
    end
    return false
  end

  BuildLootProfileSubdomainSnapshotSource = function(profile, subdomain)
    profile = type(profile) == "table" and profile or {}
    local normalizedKey = NormalizeLootProfileSubdomainKey(subdomain)
    local def = PROFILE_TRANSFER_SUBDOMAINS_BY_KEY[normalizedKey]
    if type(def) == "table" and type(def.source) == "function" then
      return def.source(profile)
    end
    local dynamicDef, _, identity = ParseDynamicLootProfileSubdomainKey(normalizedKey)
    if type(dynamicDef) == "table" and type(dynamicDef.source) == "function" then
      return dynamicDef.source(profile, identity)
    end
    return nil
  end

  local function BuildLootProfileSubdomainChecksumSource(profile, subdomain)
    profile = type(profile) == "table" and profile or {}
    local normalizedKey = NormalizeLootProfileSubdomainKey(subdomain)
    local def = PROFILE_TRANSFER_SUBDOMAINS_BY_KEY[normalizedKey]
    if type(def) == "table" then
      if type(def.checksumSource) == "function" then
        return def.checksumSource(profile)
      end
      if type(def.source) == "function" then
        return def.source(profile)
      end
      return nil
    end
    local dynamicDef, _, identity = ParseDynamicLootProfileSubdomainKey(normalizedKey)
    if type(dynamicDef) == "table" then
      if type(dynamicDef.checksumSource) == "function" then
        return dynamicDef.checksumSource(profile, identity)
      end
      if type(dynamicDef.source) == "function" then
        return dynamicDef.source(profile, identity)
      end
    end
    return nil
  end

  local function ApplyLootProfileSubdomainSnapshotSource(profile, subdomain, payload)
    local normalizedKey = NormalizeLootProfileSubdomainKey(subdomain)
    local def = PROFILE_TRANSFER_SUBDOMAINS_BY_KEY[normalizedKey]
    if type(def) == "table" and type(def.apply) == "function" then
      def.apply(profile, payload)
      return true
    end
    local dynamicDef, _, identity = ParseDynamicLootProfileSubdomainKey(normalizedKey)
    if type(dynamicDef) == "table" and type(dynamicDef.apply) == "function" then
      dynamicDef.apply(profile, identity, payload)
      return true
    end
    return false
  end

  local function BuildLootProfileSubchecksumManifestFromProfile(profile, domains)
    profile = type(profile) == "table" and profile or {}
    local normalizedDomains = NormalizeLootProfileDomainList(domains)
    local normalizedSubdomains = NormalizeLootProfileSubdomainList(nil, normalizedDomains, profile)
    local manifest = {
      domains = normalizedDomains,
      subdomains = normalizedSubdomains,
      byDomain = {},
      checksums = {},
    }

    for _, domain in ipairs(normalizedDomains) do
      manifest.byDomain[domain] = {
        checksum = GetLootProfileDomainChecksum(profile, domain),
        subchecksums = {},
      }
    end
    for _, subdomain in ipairs(normalizedSubdomains) do
      local payload = BuildLootProfileSubdomainChecksumSource(profile, subdomain)
      local domain = GetLootProfileSubdomainParentDomain(subdomain)
      local checksum = CalculateStableChecksum(payload or {})
      manifest.checksums[subdomain] = checksum
      if manifest.byDomain[domain] then
        manifest.byDomain[domain].subchecksums[subdomain] = checksum
      end
    end
    return manifest
  end

  local function GetLootProfileSubchecksumManifest(profileName, domains)
    local root = RootDB()
    local resolvedName = TrimText(profileName)
    local profile = type(root) == "table" and type(root.profiles) == "table" and root.profiles[resolvedName] or nil
    if type(profile) ~= "table" then
      return nil
    end
    EnsureLootProfileDefaults(profile)
    EnsureLootProfileIdentity(profile, resolvedName)
    EnsureLootProfileSyncState(profile)
    EnsureLootProfileRevisionState(profile)
    RecalculateLootLedgerTotals(profile)

    local manifest = BuildLootProfileSubchecksumManifestFromProfile(profile, domains)
    manifest.profileName = resolvedName
    manifest.profileId = TrimText(type(profile.meta) == "table" and profile.meta.profileId or "")
    return manifest
  end

  local function ExportLootProfileSubdomainPatchManifest(profileName, subdomains)
    local root = RootDB()
    local profile = type(root) == "table" and type(root.profiles) == "table" and root.profiles[profileName] or nil
    if type(profile) ~= "table" then
      return nil
    end
    EnsureLootProfileDefaults(profile)
    EnsureLootProfileIdentity(profile, profileName)
    EnsureLootProfileSyncState(profile)
    EnsureLootProfileRevisionState(profile)
    RecalculateLootLedgerTotals(profile)

    local normalizedSubdomains = FilterLootProfilePatchCapableSubdomains(subdomains, nil, profile)
    if #normalizedSubdomains == 0 then
      return nil
    end

    local exportedSubdomains = {}
    local detailsBySubdomain = {}
    for _, subdomain in ipairs(normalizedSubdomains) do
      local detail = BuildLootProfileSubdomainPatchManifestEntry(profile, subdomain)
      if type(detail) == "table" then
        detailsBySubdomain[subdomain] = detail
        exportedSubdomains[#exportedSubdomains + 1] = subdomain
      end
    end
    if #exportedSubdomains == 0 then
      return nil
    end

    return PROFILE_SUBDOMAIN_PATCH_MANIFEST_EXPORT_PREFIX .. json_encode({
      kind = "PROFILE_SUBDOMAIN_PATCH_MANIFEST",
      exportMode = "PATCH_DETAIL",
      exportedAt = tonumber(time and time() or 0) or 0,
      source = {
        profileName = tostring(profileName),
        profileId = type(profile.meta) == "table" and profile.meta.profileId or nil,
      },
      domains = ResolveLootProfileDomainsForSubdomains(exportedSubdomains),
      subdomains = exportedSubdomains,
      details = detailsBySubdomain,
    })
  end

  local function PreviewLootProfileSubdomainPatchManifest(dataStr)
    if type(dataStr) ~= "string" or dataStr:sub(1, #PROFILE_SUBDOMAIN_PATCH_MANIFEST_EXPORT_PREFIX) ~= PROFILE_SUBDOMAIN_PATCH_MANIFEST_EXPORT_PREFIX then
      return nil
    end
    local payload = dataStr:sub(#PROFILE_SUBDOMAIN_PATCH_MANIFEST_EXPORT_PREFIX + 1)
    local data = json_decode(payload)
    if type(data) ~= "table" or type(data.details) ~= "table" then
      return nil
    end

    local normalizedSubdomains = FilterLootProfilePatchCapableSubdomains(data.subdomains, data.domains)
    local detailsBySubdomain = {}
    for _, subdomain in ipairs(normalizedSubdomains) do
      if type(data.details[subdomain]) == "table" then
        detailsBySubdomain[subdomain] = data.details[subdomain]
      end
    end

    return {
      profileName = TrimText(type(data.source) == "table" and data.source.profileName or ""),
      profileId = TrimText(type(data.source) == "table" and data.source.profileId or ""),
      exportedAt = tonumber(data.exportedAt) or 0,
      scopeDomains = ResolveLootProfileDomainsForSubdomains(normalizedSubdomains),
      scopeSubdomains = normalizedSubdomains,
      detailsBySubdomain = detailsBySubdomain,
    }
  end

  local function ExportLootProfileSubdomainPatch(profileName, subdomains, remoteManifest)
    local root = RootDB()
    local profile = type(root) == "table" and type(root.profiles) == "table" and root.profiles[profileName] or nil
    if type(profile) ~= "table" then
      return nil
    end
    EnsureLootProfileDefaults(profile)
    EnsureLootProfileIdentity(profile, profileName)
    EnsureLootProfileSyncState(profile)
    EnsureLootProfileRevisionState(profile)
    RecalculateLootLedgerTotals(profile)

    local normalizedSubdomains = FilterLootProfilePatchCapableSubdomains(subdomains, nil, profile)
    if #normalizedSubdomains == 0 then
      return nil
    end

    local remoteDetailsBySubdomain = type(remoteManifest) == "table"
      and (
        type(remoteManifest.detailsBySubdomain) == "table" and remoteManifest.detailsBySubdomain
        or type(remoteManifest.bySubdomain) == "table" and remoteManifest.bySubdomain
        or type(remoteManifest.details) == "table" and remoteManifest.details
        or nil
      )
      or nil
    if type(remoteDetailsBySubdomain) ~= "table" then
      return nil
    end

    local patchPayloads = {}
    for _, subdomain in ipairs(normalizedSubdomains) do
      local remoteDetail = type(remoteDetailsBySubdomain[subdomain]) == "table" and remoteDetailsBySubdomain[subdomain] or nil
      local patchPayload = remoteDetail and BuildLootProfileSubdomainPatchPayloadEntry(profile, subdomain, remoteDetail) or nil
      if type(patchPayload) ~= "table" then
        return nil
      end
      patchPayloads[subdomain] = patchPayload
    end

    local normalizedDomains = ResolveLootProfileDomainsForSubdomains(normalizedSubdomains)
    local revisions = {}
    for _, domain in ipairs(normalizedDomains) do
      revisions[domain] = BuildLootProfileDomainRevisionEntry(profile, domain)
    end

    return PROFILE_SUBDOMAIN_PATCH_EXPORT_PREFIX .. json_encode({
      kind = "PROFILE_SUBDOMAIN_PATCH",
      exportMode = "SHARED_REPAIR_PATCH",
      exportedAt = tonumber(time and time() or 0) or 0,
      source = {
        profileName = tostring(profileName),
        profileId = type(profile.meta) == "table" and profile.meta.profileId or nil,
      },
      domains = normalizedDomains,
      subdomains = normalizedSubdomains,
      revisions = revisions,
      profile = patchPayloads,
    })
  end

  local function ExportLootProfileConflictRowPatch(profileName, selectionsBySubdomain, rowMapsBySubdomain, prebuiltRowsBySubdomain)
    local root = RootDB()
    local profile = type(root) == "table" and type(root.profiles) == "table" and root.profiles[profileName] or nil
    if type(profile) ~= "table" or type(selectionsBySubdomain) ~= "table" then
      return nil
    end
    EnsureLootProfileDefaults(profile)
    EnsureLootProfileIdentity(profile, profileName)
    EnsureLootProfileSyncState(profile)
    EnsureLootProfileRevisionState(profile)
    RecalculateLootLedgerTotals(profile)

    local requestedSubdomains = {}
    for subdomain, selectedRows in pairs(selectionsBySubdomain) do
      if type(selectedRows) == "table" and #selectedRows > 0 then
        requestedSubdomains[#requestedSubdomains + 1] = tostring(subdomain)
      end
    end
    local normalizedSubdomains = NormalizeLootProfileSubdomainList(requestedSubdomains, nil, profile)
    if #normalizedSubdomains == 0 then
      return nil
    end

    local rowsBySubdomain = {}
    local exportedSubdomains = {}
    local selectedRowCount = 0
    for _, subdomain in ipairs(normalizedSubdomains) do
      local exportedRows = {}
      if type(prebuiltRowsBySubdomain) == "table" and type(prebuiltRowsBySubdomain[subdomain]) == "table" then
        for _, row in ipairs(prebuiltRowsBySubdomain[subdomain]) do
          if type(row) == "table" and type(row.applySpec) == "table" and type(row.remotePayload) == "table" then
            exportedRows[#exportedRows + 1] = DeepCopy(row)
          end
        end
        table.sort(exportedRows, function(left, right)
          return tostring(type(left) == "table" and left.id or "") < tostring(type(right) == "table" and right.id or "")
        end)
      else
        local localPayload = BuildLootProfileSubdomainSnapshotSource(profile, subdomain)
        local selectedRows = type(selectionsBySubdomain[subdomain]) == "table" and selectionsBySubdomain[subdomain] or {}
        local rowMap = type(rowMapsBySubdomain) == "table" and type(rowMapsBySubdomain[subdomain]) == "table" and rowMapsBySubdomain[subdomain] or {}
        exportedRows = type(conflictResolverHelpers.BuildSelectedRemoteRowPayloads) == "function"
          and conflictResolverHelpers.BuildSelectedRemoteRowPayloads(subdomain, localPayload, selectedRows, rowMap)
          or {}
      end
      if type(exportedRows) == "table" and #exportedRows > 0 then
        rowsBySubdomain[subdomain] = exportedRows
        exportedSubdomains[#exportedSubdomains + 1] = subdomain
        selectedRowCount = selectedRowCount + #exportedRows
      end
    end
    if #exportedSubdomains == 0 then
      return nil
    end

    local normalizedDomains = ResolveLootProfileDomainsForSubdomains(exportedSubdomains)
    local revisions = {}
    for _, domain in ipairs(normalizedDomains) do
      revisions[domain] = BuildLootProfileDomainRevisionEntry(profile, domain)
    end

    return PROFILE_CONFLICT_ROW_PATCH_EXPORT_PREFIX .. json_encode({
      kind = "PROFILE_CONFLICT_ROW_PATCH",
      exportMode = "SELECTED_CONFLICT_ROWS",
      exportedAt = tonumber(time and time() or 0) or 0,
      source = {
        profileName = tostring(profileName),
        profileId = type(profile.meta) == "table" and profile.meta.profileId or nil,
      },
      domains = normalizedDomains,
      subdomains = exportedSubdomains,
      revisions = revisions,
      selectedRowCount = selectedRowCount,
      rowsBySubdomain = rowsBySubdomain,
    })
  end

  local function PreviewLootProfileConflictRowPatch(dataStr)
    if type(dataStr) ~= "string" or dataStr:sub(1, #PROFILE_CONFLICT_ROW_PATCH_EXPORT_PREFIX) ~= PROFILE_CONFLICT_ROW_PATCH_EXPORT_PREFIX then
      return nil
    end
    local payload = dataStr:sub(#PROFILE_CONFLICT_ROW_PATCH_EXPORT_PREFIX + 1)
    local data = json_decode(payload)
    if type(data) ~= "table" or type(data.rowsBySubdomain) ~= "table" then
      return nil
    end

    local summary = {
      profileName = TrimText(type(data.source) == "table" and data.source.profileName or ""),
      profileId = TrimText(type(data.source) == "table" and data.source.profileId or ""),
      settings = 0,
      permissions = 0,
      operational = 0,
      loot = 0,
      session = 0,
      settingsChecksum = "",
      permissionsChecksum = "",
      operationalChecksum = "",
      lootChecksum = "",
      sessionChecksum = "",
      settingsUpdatedAt = 0,
      permissionsUpdatedAt = 0,
      operationalUpdatedAt = 0,
      lootUpdatedAt = 0,
      sessionUpdatedAt = 0,
      updatedAt = 0,
      exportedAt = tonumber(data.exportedAt) or nil,
      sourceCharacter = "",
      scopeDomains = NormalizeLootProfileDomainList(data.domains),
      scopeSubdomains = NormalizeLootProfileSubdomainList(data.subdomains, data.domains),
      transferKind = "ROWPATCHES",
      selectedRowCount = math.max(0, tonumber(data.selectedRowCount) or 0),
    }

    local revisions = type(data.revisions) == "table" and data.revisions or {}
    for _, domain in ipairs(summary.scopeDomains) do
      local entry = type(revisions[domain]) == "table" and revisions[domain] or {}
      local revision = math.max(0, tonumber(entry.revision) or 0)
      local updatedAt = math.max(0, tonumber(entry.updatedAt) or 0)
      local checksum = TrimText(entry.checksum)
      summary[domain] = revision
      summary[domain .. "Checksum"] = checksum
      summary[domain .. "UpdatedAt"] = updatedAt
      summary.updatedAt = math.max(summary.updatedAt, updatedAt)
    end

    summary.operational = math.max(summary.loot or 0, summary.session or 0)
    summary.operationalUpdatedAt = math.max(summary.lootUpdatedAt or 0, summary.sessionUpdatedAt or 0)
    if summary.lootChecksum ~= "" and summary.lootChecksum == summary.sessionChecksum then
      summary.operationalChecksum = summary.lootChecksum
    elseif summary.lootChecksum ~= "" and summary.sessionChecksum == "" then
      summary.operationalChecksum = summary.lootChecksum
    elseif summary.sessionChecksum ~= "" and summary.lootChecksum == "" then
      summary.operationalChecksum = summary.sessionChecksum
    end
    summary.updatedAt = math.max(summary.updatedAt, summary.operationalUpdatedAt or 0)
    return summary
  end

  local function BuildLootProfileDomainSnapshotSource(profile, domain)
    profile = type(profile) == "table" and profile or {}
    local domainKey = NormalizeLootProfileDomainKey(domain)
    if domainKey == "settings" then
      local settings = DeepCopy(type(profile.settings) == "table" and profile.settings or {})
      settings.enabled = nil
      return settings
    elseif domainKey == "permissions" then
      local meta = type(profile.meta) == "table" and profile.meta or {}
      return {
        permissions = DeepCopy(meta.permissions or {}),
        permissionPolicy = DeepCopy(meta.permissionPolicy or {}),
      }
    elseif domainKey == "loot" then
      return {
        lootLedger = DeepCopy(profile.lootLedger or {}),
        lootLedgerMeta = DeepCopy(profile.lootLedgerMeta or {}),
        lootLedgerEntrySerial = tonumber(profile.lootLedgerEntrySerial) or 0,
        lootRollStats = DeepCopy(profile.lootRollStats or {}),
        lootListGroups = DeepCopy(profile.lootListGroups or {}),
      }
    elseif domainKey == "session" then
      return {
        sessions = DeepCopy(profile.sessions or {}),
        liveBoardHistory = DeepCopy(profile.liveBoardHistory or {}),
      }
    end
    return nil
  end

  local function PreviewLootProfileDomainSnapshot(dataStr)
    if type(dataStr) ~= "string" or dataStr:sub(1, #PROFILE_DOMAIN_SNAPSHOT_EXPORT_PREFIX) ~= PROFILE_DOMAIN_SNAPSHOT_EXPORT_PREFIX then
      return nil
    end
    local payload = dataStr:sub(#PROFILE_DOMAIN_SNAPSHOT_EXPORT_PREFIX + 1)
    local data = json_decode(payload)
    if type(data) ~= "table" or type(data.profile) ~= "table" then
      return nil
    end

    local summary = {
      profileName = TrimText(type(data.source) == "table" and data.source.profileName or ""),
      profileId = TrimText(type(data.source) == "table" and data.source.profileId or ""),
      settings = 0,
      permissions = 0,
      operational = 0,
      loot = 0,
      session = 0,
      settingsChecksum = "",
      permissionsChecksum = "",
      operationalChecksum = "",
      lootChecksum = "",
      sessionChecksum = "",
      settingsUpdatedAt = 0,
      permissionsUpdatedAt = 0,
      operationalUpdatedAt = 0,
      lootUpdatedAt = 0,
      sessionUpdatedAt = 0,
      updatedAt = 0,
      exportedAt = tonumber(data.exportedAt) or nil,
      sourceCharacter = "",
      scopeDomains = NormalizeLootProfileDomainList(data.domains),
      transferKind = "DOMAINS",
    }

    local revisions = type(data.revisions) == "table" and data.revisions or {}
    for _, domain in ipairs(summary.scopeDomains) do
      local entry = type(revisions[domain]) == "table" and revisions[domain] or {}
      local revision = math.max(0, tonumber(entry.revision) or 0)
      local updatedAt = math.max(0, tonumber(entry.updatedAt) or 0)
      local checksum = TrimText(entry.checksum)
      summary[domain] = revision
      summary[domain .. "Checksum"] = checksum
      summary[domain .. "UpdatedAt"] = updatedAt
      summary.updatedAt = math.max(summary.updatedAt, updatedAt)
    end

    summary.operational = math.max(summary.loot or 0, summary.session or 0)
    summary.operationalUpdatedAt = math.max(summary.lootUpdatedAt or 0, summary.sessionUpdatedAt or 0)
    if summary.lootChecksum ~= "" and summary.lootChecksum == summary.sessionChecksum then
      summary.operationalChecksum = summary.lootChecksum
    elseif summary.lootChecksum ~= "" and summary.sessionChecksum == "" then
      summary.operationalChecksum = summary.lootChecksum
    elseif summary.sessionChecksum ~= "" and summary.lootChecksum == "" then
      summary.operationalChecksum = summary.sessionChecksum
    end
    summary.updatedAt = math.max(summary.updatedAt, summary.operationalUpdatedAt or 0)
    return summary
  end

  local function PreviewLootProfileSubdomainSnapshot(dataStr)
    if type(dataStr) ~= "string" or dataStr:sub(1, #PROFILE_SUBDOMAIN_SNAPSHOT_EXPORT_PREFIX) ~= PROFILE_SUBDOMAIN_SNAPSHOT_EXPORT_PREFIX then
      return nil
    end
    local payload = dataStr:sub(#PROFILE_SUBDOMAIN_SNAPSHOT_EXPORT_PREFIX + 1)
    local data = json_decode(payload)
    if type(data) ~= "table" or type(data.profile) ~= "table" then
      return nil
    end

    local summary = {
      profileName = TrimText(type(data.source) == "table" and data.source.profileName or ""),
      profileId = TrimText(type(data.source) == "table" and data.source.profileId or ""),
      settings = 0,
      permissions = 0,
      operational = 0,
      loot = 0,
      session = 0,
      settingsChecksum = "",
      permissionsChecksum = "",
      operationalChecksum = "",
      lootChecksum = "",
      sessionChecksum = "",
      settingsUpdatedAt = 0,
      permissionsUpdatedAt = 0,
      operationalUpdatedAt = 0,
      lootUpdatedAt = 0,
      sessionUpdatedAt = 0,
      updatedAt = 0,
      exportedAt = tonumber(data.exportedAt) or nil,
      sourceCharacter = "",
      scopeDomains = NormalizeLootProfileDomainList(data.domains),
      scopeSubdomains = NormalizeLootProfileSubdomainList(data.subdomains, data.domains),
      transferKind = "SUBDOMAINS",
    }

    local revisions = type(data.revisions) == "table" and data.revisions or {}
    for _, domain in ipairs(summary.scopeDomains) do
      local entry = type(revisions[domain]) == "table" and revisions[domain] or {}
      local revision = math.max(0, tonumber(entry.revision) or 0)
      local updatedAt = math.max(0, tonumber(entry.updatedAt) or 0)
      local checksum = TrimText(entry.checksum)
      summary[domain] = revision
      summary[domain .. "Checksum"] = checksum
      summary[domain .. "UpdatedAt"] = updatedAt
      summary.updatedAt = math.max(summary.updatedAt, updatedAt)
    end

    summary.operational = math.max(summary.loot or 0, summary.session or 0)
    summary.operationalUpdatedAt = math.max(summary.lootUpdatedAt or 0, summary.sessionUpdatedAt or 0)
    if summary.lootChecksum ~= "" and summary.lootChecksum == summary.sessionChecksum then
      summary.operationalChecksum = summary.lootChecksum
    elseif summary.lootChecksum ~= "" and summary.sessionChecksum == "" then
      summary.operationalChecksum = summary.lootChecksum
    elseif summary.sessionChecksum ~= "" and summary.lootChecksum == "" then
      summary.operationalChecksum = summary.sessionChecksum
    end
    summary.updatedAt = math.max(summary.updatedAt, summary.operationalUpdatedAt or 0)
    return summary
  end

  local function PreviewLootProfileSubdomainPatch(dataStr)
    if type(dataStr) ~= "string" or dataStr:sub(1, #PROFILE_SUBDOMAIN_PATCH_EXPORT_PREFIX) ~= PROFILE_SUBDOMAIN_PATCH_EXPORT_PREFIX then
      return nil
    end
    local payload = dataStr:sub(#PROFILE_SUBDOMAIN_PATCH_EXPORT_PREFIX + 1)
    local data = json_decode(payload)
    if type(data) ~= "table" or type(data.profile) ~= "table" then
      return nil
    end

    local summary = {
      profileName = TrimText(type(data.source) == "table" and data.source.profileName or ""),
      profileId = TrimText(type(data.source) == "table" and data.source.profileId or ""),
      settings = 0,
      permissions = 0,
      operational = 0,
      loot = 0,
      session = 0,
      settingsChecksum = "",
      permissionsChecksum = "",
      operationalChecksum = "",
      lootChecksum = "",
      sessionChecksum = "",
      settingsUpdatedAt = 0,
      permissionsUpdatedAt = 0,
      operationalUpdatedAt = 0,
      lootUpdatedAt = 0,
      sessionUpdatedAt = 0,
      updatedAt = 0,
      exportedAt = tonumber(data.exportedAt) or nil,
      sourceCharacter = "",
      scopeDomains = NormalizeLootProfileDomainList(data.domains),
      scopeSubdomains = NormalizeLootProfileSubdomainList(data.subdomains, data.domains),
      transferKind = "PATCHES",
    }

    local revisions = type(data.revisions) == "table" and data.revisions or {}
    for _, domain in ipairs(summary.scopeDomains) do
      local entry = type(revisions[domain]) == "table" and revisions[domain] or {}
      local revision = math.max(0, tonumber(entry.revision) or 0)
      local updatedAt = math.max(0, tonumber(entry.updatedAt) or 0)
      local checksum = TrimText(entry.checksum)
      summary[domain] = revision
      summary[domain .. "Checksum"] = checksum
      summary[domain .. "UpdatedAt"] = updatedAt
      summary.updatedAt = math.max(summary.updatedAt, updatedAt)
    end

    summary.operational = math.max(summary.loot or 0, summary.session or 0)
    summary.operationalUpdatedAt = math.max(summary.lootUpdatedAt or 0, summary.sessionUpdatedAt or 0)
    if summary.lootChecksum ~= "" and summary.lootChecksum == summary.sessionChecksum then
      summary.operationalChecksum = summary.lootChecksum
    elseif summary.lootChecksum ~= "" and summary.sessionChecksum == "" then
      summary.operationalChecksum = summary.lootChecksum
    elseif summary.sessionChecksum ~= "" and summary.lootChecksum == "" then
      summary.operationalChecksum = summary.sessionChecksum
    end
    summary.updatedAt = math.max(summary.updatedAt, summary.operationalUpdatedAt or 0)
    return summary
  end

  local function BuildLootProfileDomainSnapshotDiff(profileName, dataStr)
    local root = RootDB()
    local localProfile = type(root) == "table" and type(root.profiles) == "table" and root.profiles[profileName] or nil
    if type(localProfile) ~= "table" or type(dataStr) ~= "string" or dataStr:sub(1, #PROFILE_DOMAIN_SNAPSHOT_EXPORT_PREFIX) ~= PROFILE_DOMAIN_SNAPSHOT_EXPORT_PREFIX then
      return nil
    end
    local payload = dataStr:sub(#PROFILE_DOMAIN_SNAPSHOT_EXPORT_PREFIX + 1)
    local data = json_decode(payload)
    if type(data) ~= "table" or type(data.profile) ~= "table" then
      return nil
    end

    local includedDomains = {}
    for _, domain in ipairs(NormalizeLootProfileDomainList(data.domains)) do
      includedDomains[domain] = true
    end
    EnsureLootProfileDefaults(localProfile)
    RecalculateLootLedgerTotals(localProfile)

    local remoteProfile = type(data.profile) == "table" and data.profile or {}
    local settingsDiff = includedDomains.settings
      and BuildProfileDomainDiff("Settings", BuildLootProfileSettingsChecksumSource(localProfile), remoteProfile.settings or {})
      or nil
    local permissionsDiff = includedDomains.permissions
      and BuildProfileDomainDiff("Permissions", BuildLootProfilePermissionsChecksumSource(localProfile), remoteProfile.permissions or {})
      or nil
    local lootDiff = includedDomains.loot
      and BuildProfileDomainDiff("Loot Data", BuildLootProfileLootChecksumSource(localProfile), remoteProfile.loot or {})
      or nil
    local sessionDiff = includedDomains.session
      and BuildProfileDomainDiff("Session Data", BuildLootProfileSessionChecksumSource(localProfile), remoteProfile.session or {})
      or nil

    local totalChanges = 0
    for _, diff in ipairs({ settingsDiff or false, permissionsDiff or false, lootDiff or false, sessionDiff or false }) do
      totalChanges = totalChanges + math.max(0, tonumber(type(diff) == "table" and diff.count) or 0)
    end

    return {
      profileName = TrimText(profileName),
      snapshotProfileName = TrimText(type(data.source) == "table" and data.source.profileName or ""),
      exportedAt = tonumber(data.exportedAt) or 0,
      settings = settingsDiff,
      permissions = permissionsDiff,
      loot = lootDiff,
      session = sessionDiff,
      hasChanges = totalChanges > 0,
      scopeDomains = NormalizeLootProfileDomainList(data.domains),
    }
  end

  local function BuildLootProfileSubdomainSnapshotDiff(profileName, dataStr)
    local root = RootDB()
    local localProfile = type(root) == "table" and type(root.profiles) == "table" and root.profiles[profileName] or nil
    if type(localProfile) ~= "table" or type(dataStr) ~= "string" or dataStr:sub(1, #PROFILE_SUBDOMAIN_SNAPSHOT_EXPORT_PREFIX) ~= PROFILE_SUBDOMAIN_SNAPSHOT_EXPORT_PREFIX then
      return nil
    end
    local payload = dataStr:sub(#PROFILE_SUBDOMAIN_SNAPSHOT_EXPORT_PREFIX + 1)
    local data = json_decode(payload)
    if type(data) ~= "table" or type(data.profile) ~= "table" then
      return nil
    end

    EnsureLootProfileDefaults(localProfile)
    RecalculateLootLedgerTotals(localProfile)

    local includedSubdomains = NormalizeLootProfileSubdomainList(data.subdomains, data.domains)
    local remoteProfile = type(data.profile) == "table" and data.profile or {}
    local aggregated = {}
    local totalChanges = 0

    local function EnsureAggregate(domain)
      local domainKey = NormalizeLootProfileDomainKey(domain)
      if not aggregated[domainKey] then
        aggregated[domainKey] = {
          label = PROFILE_REVISION_DOMAIN_LABELS[domainKey] or tostring(domainKey),
          count = 0,
          lines = {},
        }
      end
      return aggregated[domainKey]
    end

    for _, subdomain in ipairs(includedSubdomains) do
      local domainKey = GetLootProfileSubdomainParentDomain(subdomain)
      local subdomainLabel = GetLootProfileSubdomainLabel(subdomain)
      local diff = BuildProfileDomainDiff(
        subdomainLabel ~= "" and subdomainLabel or tostring(subdomain),
        BuildLootProfileSubdomainSnapshotSource(localProfile, subdomain) or {},
        type(remoteProfile[subdomain]) == "table" and remoteProfile[subdomain] or {}
      )
      totalChanges = totalChanges + math.max(0, tonumber(diff.count) or 0)
      if (tonumber(diff.count) or 0) > 0 then
        local aggregate = EnsureAggregate(domainKey)
        aggregate.count = aggregate.count + math.max(0, tonumber(diff.count) or 0)
        if type(diff.lines) == "table" and #diff.lines > 0 then
          for _, line in ipairs(diff.lines) do
            aggregate.lines[#aggregate.lines + 1] = "[" .. tostring(subdomainLabel or subdomain) .. "] " .. tostring(line)
          end
        else
          aggregate.lines[#aggregate.lines + 1] = "[" .. tostring(subdomainLabel or subdomain) .. "] changed"
        end
      end
    end

    return {
      profileName = TrimText(profileName),
      snapshotProfileName = TrimText(type(data.source) == "table" and data.source.profileName or ""),
      exportedAt = tonumber(data.exportedAt) or 0,
      settings = aggregated.settings,
      permissions = aggregated.permissions,
      loot = aggregated.loot,
      session = aggregated.session,
      hasChanges = totalChanges > 0,
      scopeDomains = NormalizeLootProfileDomainList(data.domains),
      scopeSubdomains = includedSubdomains,
    }
  end

  local function BuildLootProfileSubdomainPatchDiff(profileName, dataStr)
    local root = RootDB()
    local localProfile = type(root) == "table" and type(root.profiles) == "table" and root.profiles[profileName] or nil
    if type(localProfile) ~= "table" or type(dataStr) ~= "string" or dataStr:sub(1, #PROFILE_SUBDOMAIN_PATCH_EXPORT_PREFIX) ~= PROFILE_SUBDOMAIN_PATCH_EXPORT_PREFIX then
      return nil
    end
    local payload = dataStr:sub(#PROFILE_SUBDOMAIN_PATCH_EXPORT_PREFIX + 1)
    local data = json_decode(payload)
    if type(data) ~= "table" or type(data.profile) ~= "table" then
      return nil
    end

    EnsureLootProfileDefaults(localProfile)
    RecalculateLootLedgerTotals(localProfile)

    local simulatedProfile = DeepCopy(localProfile)
    EnsureLootProfileDefaults(simulatedProfile)
    RecalculateLootLedgerTotals(simulatedProfile)

    local includedSubdomains = NormalizeLootProfileSubdomainList(data.subdomains, data.domains)
    local patchPayloads = type(data.profile) == "table" and data.profile or {}
    for _, subdomain in ipairs(includedSubdomains) do
      ApplyLootProfileSubdomainPatchPayload(simulatedProfile, subdomain, patchPayloads[subdomain])
    end
    EnsureLootProfileDefaults(simulatedProfile)
    RecalculateLootLedgerTotals(simulatedProfile)

    local aggregated = {}
    local totalChanges = 0

    local function EnsureAggregate(domain)
      local domainKey = NormalizeLootProfileDomainKey(domain)
      if not aggregated[domainKey] then
        aggregated[domainKey] = {
          label = PROFILE_REVISION_DOMAIN_LABELS[domainKey] or tostring(domainKey),
          count = 0,
          lines = {},
        }
      end
      return aggregated[domainKey]
    end

    for _, subdomain in ipairs(includedSubdomains) do
      local domainKey = GetLootProfileSubdomainParentDomain(subdomain)
      local subdomainLabel = GetLootProfileSubdomainLabel(subdomain)
      local diff = BuildProfileDomainDiff(
        subdomainLabel ~= "" and subdomainLabel or tostring(subdomain),
        BuildLootProfileSubdomainSnapshotSource(localProfile, subdomain) or {},
        BuildLootProfileSubdomainSnapshotSource(simulatedProfile, subdomain) or {}
      )
      totalChanges = totalChanges + math.max(0, tonumber(diff.count) or 0)
      if (tonumber(diff.count) or 0) > 0 then
        local aggregate = EnsureAggregate(domainKey)
        aggregate.count = aggregate.count + math.max(0, tonumber(diff.count) or 0)
        if type(diff.lines) == "table" and #diff.lines > 0 then
          for _, line in ipairs(diff.lines) do
            aggregate.lines[#aggregate.lines + 1] = "[" .. tostring(subdomainLabel or subdomain) .. "] " .. tostring(line)
          end
        else
          aggregate.lines[#aggregate.lines + 1] = "[" .. tostring(subdomainLabel or subdomain) .. "] changed"
        end
      end
    end

    return {
      profileName = TrimText(profileName),
      snapshotProfileName = TrimText(type(data.source) == "table" and data.source.profileName or ""),
      exportedAt = tonumber(data.exportedAt) or 0,
      settings = aggregated.settings,
      permissions = aggregated.permissions,
      loot = aggregated.loot,
      session = aggregated.session,
      hasChanges = totalChanges > 0,
      scopeDomains = NormalizeLootProfileDomainList(data.domains),
      scopeSubdomains = includedSubdomains,
    }
  end

  local function BuildLootProfileConflictRowPatchDiff(profileName, dataStr)
    local root = RootDB()
    local localProfile = type(root) == "table" and type(root.profiles) == "table" and root.profiles[profileName] or nil
    if type(localProfile) ~= "table" or type(dataStr) ~= "string" or dataStr:sub(1, #PROFILE_CONFLICT_ROW_PATCH_EXPORT_PREFIX) ~= PROFILE_CONFLICT_ROW_PATCH_EXPORT_PREFIX then
      return nil
    end
    local payload = dataStr:sub(#PROFILE_CONFLICT_ROW_PATCH_EXPORT_PREFIX + 1)
    local data = json_decode(payload)
    if type(data) ~= "table" or type(data.rowsBySubdomain) ~= "table" then
      return nil
    end

    EnsureLootProfileDefaults(localProfile)
    RecalculateLootLedgerTotals(localProfile)

    local simulatedProfile = DeepCopy(localProfile)
    EnsureLootProfileDefaults(simulatedProfile)
    RecalculateLootLedgerTotals(simulatedProfile)

    local includedSubdomains = NormalizeLootProfileSubdomainList(data.subdomains, data.domains)
    local rowsBySubdomain = type(data.rowsBySubdomain) == "table" and data.rowsBySubdomain or {}
    for _, subdomain in ipairs(includedSubdomains) do
      local localPayload = BuildLootProfileSubdomainSnapshotSource(simulatedProfile, subdomain)
      local mergedPayload = type(conflictResolverHelpers.ApplySelectedRemoteRowPayloads) == "function"
        and conflictResolverHelpers.ApplySelectedRemoteRowPayloads(subdomain, localPayload, rowsBySubdomain[subdomain])
        or localPayload
      if CalculateStableChecksum(mergedPayload) ~= CalculateStableChecksum(localPayload) then
        ApplyLootProfileSubdomainSnapshotSource(simulatedProfile, subdomain, mergedPayload)
      end
    end
    EnsureLootProfileDefaults(simulatedProfile)
    RecalculateLootLedgerTotals(simulatedProfile)

    local aggregated = {}
    local totalChanges = 0

    local function EnsureAggregate(domain)
      local domainKey = NormalizeLootProfileDomainKey(domain)
      if not aggregated[domainKey] then
        aggregated[domainKey] = {
          label = PROFILE_REVISION_DOMAIN_LABELS[domainKey] or tostring(domainKey),
          count = 0,
          lines = {},
        }
      end
      return aggregated[domainKey]
    end

    for _, subdomain in ipairs(includedSubdomains) do
      local domainKey = GetLootProfileSubdomainParentDomain(subdomain)
      local subdomainLabel = GetLootProfileSubdomainLabel(subdomain)
      local diff = BuildProfileDomainDiff(
        subdomainLabel ~= "" and subdomainLabel or tostring(subdomain),
        BuildLootProfileSubdomainSnapshotSource(localProfile, subdomain) or {},
        BuildLootProfileSubdomainSnapshotSource(simulatedProfile, subdomain) or {}
      )
      totalChanges = totalChanges + math.max(0, tonumber(diff.count) or 0)
      if (tonumber(diff.count) or 0) > 0 then
        local aggregate = EnsureAggregate(domainKey)
        aggregate.count = aggregate.count + math.max(0, tonumber(diff.count) or 0)
        if type(diff.lines) == "table" and #diff.lines > 0 then
          for _, line in ipairs(diff.lines) do
            aggregate.lines[#aggregate.lines + 1] = "[" .. tostring(subdomainLabel or subdomain) .. "] " .. tostring(line)
          end
        else
          aggregate.lines[#aggregate.lines + 1] = "[" .. tostring(subdomainLabel or subdomain) .. "] changed"
        end
      end
    end

    return {
      profileName = TrimText(profileName),
      snapshotProfileName = TrimText(type(data.source) == "table" and data.source.profileName or ""),
      exportedAt = tonumber(data.exportedAt) or 0,
      settings = aggregated.settings,
      permissions = aggregated.permissions,
      loot = aggregated.loot,
      session = aggregated.session,
      hasChanges = totalChanges > 0,
      scopeDomains = NormalizeLootProfileDomainList(data.domains),
      scopeSubdomains = includedSubdomains,
    }
  end

  local function BuildLootProfileTransferConflictPayloads(profileName, dataStr)
    local root = RootDB()
    local localProfile = type(root) == "table" and type(root.profiles) == "table" and root.profiles[profileName] or nil
    if type(localProfile) ~= "table" or type(dataStr) ~= "string" then
      return nil
    end

    EnsureLootProfileDefaults(localProfile)
    EnsureLootProfileIdentity(localProfile, profileName)
    EnsureLootProfileSyncState(localProfile)
    EnsureLootProfileRevisionState(localProfile)
    RecalculateLootLedgerTotals(localProfile)

    local payloadPrefix
    local transferKind
    if dataStr:sub(1, #PROFILE_SUBDOMAIN_SNAPSHOT_EXPORT_PREFIX) == PROFILE_SUBDOMAIN_SNAPSHOT_EXPORT_PREFIX then
      payloadPrefix = PROFILE_SUBDOMAIN_SNAPSHOT_EXPORT_PREFIX
      transferKind = "SUBDOMAINS"
    elseif dataStr:sub(1, #PROFILE_SUBDOMAIN_PATCH_EXPORT_PREFIX) == PROFILE_SUBDOMAIN_PATCH_EXPORT_PREFIX then
      payloadPrefix = PROFILE_SUBDOMAIN_PATCH_EXPORT_PREFIX
      transferKind = "PATCHES"
    else
      return nil
    end

    local payload = dataStr:sub(#payloadPrefix + 1)
    local data = json_decode(payload)
    if type(data) ~= "table" or type(data.profile) ~= "table" then
      return nil
    end

    local normalizedSubdomains = FilterLootProfilePatchCapableSubdomains(data.subdomains, data.domains, localProfile)
    if #normalizedSubdomains == 0 then
      return nil
    end

    local remotePayloads = {}
    if transferKind == "SUBDOMAINS" then
      for _, subdomain in ipairs(normalizedSubdomains) do
        local snapshotPayload = type(data.profile[subdomain]) == "table" and data.profile[subdomain] or {}
        remotePayloads[subdomain] = DeepCopy(snapshotPayload)
      end
    else
      local simulatedProfile = DeepCopy(localProfile)
      EnsureLootProfileDefaults(simulatedProfile)
      EnsureLootProfileIdentity(simulatedProfile, profileName)
      EnsureLootProfileSyncState(simulatedProfile)
      EnsureLootProfileRevisionState(simulatedProfile)
      RecalculateLootLedgerTotals(simulatedProfile)
      for _, subdomain in ipairs(normalizedSubdomains) do
        ApplyLootProfileSubdomainPatchPayload(simulatedProfile, subdomain, data.profile[subdomain])
      end
      EnsureLootProfileDefaults(simulatedProfile)
      RecalculateLootLedgerTotals(simulatedProfile)
      for _, subdomain in ipairs(normalizedSubdomains) do
        remotePayloads[subdomain] = BuildLootProfileSubdomainSnapshotSource(simulatedProfile, subdomain)
      end
    end

    return {
      profileName = TrimText(type(data.source) == "table" and data.source.profileName or profileName),
      profileId = TrimText(type(data.source) == "table" and data.source.profileId or ""),
      exportedAt = tonumber(data.exportedAt) or 0,
      transferKind = transferKind,
      scopeDomains = ResolveLootProfileDomainsForSubdomains(normalizedSubdomains),
      scopeSubdomains = normalizedSubdomains,
      remotePayloads = remotePayloads,
    }
  end

  local function BuildLootProfileTransferConflictPreview(profileName, dataStr)
    local root = RootDB()
    local localProfile = type(root) == "table" and type(root.profiles) == "table" and root.profiles[profileName] or nil
    local transferPayloads = BuildLootProfileTransferConflictPayloads(profileName, dataStr)
    if type(localProfile) ~= "table" or type(transferPayloads) ~= "table" then
      return nil
    end

    local leaves = {}
    local totalRows = 0
    for _, subdomain in ipairs(transferPayloads.scopeSubdomains or {}) do
      local localPayload = BuildLootProfileSubdomainSnapshotSource(localProfile, subdomain)
      local remotePayload = transferPayloads.remotePayloads[subdomain]
      local rows = type(conflictResolverHelpers.BuildSubdomainConflictRows) == "function"
        and conflictResolverHelpers.BuildSubdomainConflictRows(subdomain, localPayload, remotePayload)
        or {}
      if type(rows) == "table" and #rows > 0 then
        local rowMap = {}
        for _, row in ipairs(rows) do
          rowMap[tostring(type(row) == "table" and row.id or "")] = row
        end
        leaves[#leaves + 1] = {
          subdomain = subdomain,
          label = GetLootProfileSubdomainLabel(subdomain),
          domain = GetLootProfileSubdomainParentDomain(subdomain),
          rows = rows,
          rowMap = rowMap,
          rowCount = #rows,
        }
        totalRows = totalRows + #rows
      end
    end

    return {
      profileName = TrimText(profileName),
      snapshotProfileName = transferPayloads.profileName,
      profileId = transferPayloads.profileId,
      exportedAt = tonumber(transferPayloads.exportedAt) or 0,
      transferKind = transferPayloads.transferKind,
      scopeDomains = CloneLootProfileDomainList(transferPayloads.scopeDomains),
      scopeSubdomains = CloneLootProfileSubdomainList(transferPayloads.scopeSubdomains),
      leaves = leaves,
      totalRows = totalRows,
      hasConflicts = totalRows > 0,
    }
  end

  local function ApplyLootProfileTransferConflictResolution(targetName, dataStr, resolution, options)
    local root = RootDB()
    local resolvedName = TrimText(targetName)
    local profile = type(root) == "table" and type(root.profiles) == "table" and root.profiles[resolvedName] or nil
    local transferPayloads = BuildLootProfileTransferConflictPayloads(resolvedName, dataStr)
    if resolvedName == "" or type(profile) ~= "table" then
      return false, "Target profile was not found."
    end
    if type(transferPayloads) ~= "table" then
      return false, "Preview payload is not eligible for nested conflict resolution."
    end

    resolution = type(resolution) == "table" and resolution or {}
    options = type(options) == "table" and options or {}
    local expectedProfileId = TrimText(options.expectedProfileId)
    if expectedProfileId ~= "" and transferPayloads.profileId ~= "" and string.lower(expectedProfileId) ~= string.lower(transferPayloads.profileId) then
      return false, "Preview payload profile id did not match the expected shared profile."
    end

    local selectionsBySubdomain = type(resolution.selectionsBySubdomain) == "table"
      and resolution.selectionsBySubdomain
      or type(resolution.selectedBySubdomain) == "table" and resolution.selectedBySubdomain
      or {}

    local preview = BuildLootProfileTransferConflictPreview(resolvedName, dataStr)
    if type(preview) ~= "table" or type(preview.leaves) ~= "table" or #preview.leaves == 0 then
      return false, "No nested preview conflicts are available for this transfer."
    end

    EnsureLootProfileDefaults(profile)
    EnsureLootProfileIdentity(profile, resolvedName)
    EnsureLootProfileSyncState(profile)
    EnsureLootProfileRevisionState(profile)
    RecalculateLootLedgerTotals(profile)

    local changedDomains = {}
    local changedSubdomains = {}
    local appliedSubdomains = 0
    local appliedRows = 0

    for _, leaf in ipairs(preview.leaves) do
      local selectedRows = type(selectionsBySubdomain[leaf.subdomain]) == "table" and selectionsBySubdomain[leaf.subdomain] or nil
      if selectedRows and #selectedRows > 0 then
        local localPayload = BuildLootProfileSubdomainSnapshotSource(profile, leaf.subdomain)
        local remotePayload = transferPayloads.remotePayloads[leaf.subdomain]
        local mergedPayload = type(conflictResolverHelpers.ApplySelectedRemoteRows) == "function"
          and conflictResolverHelpers.ApplySelectedRemoteRows(leaf.subdomain, localPayload, remotePayload, selectedRows, leaf.rowMap)
          or localPayload
        if CalculateStableChecksum(mergedPayload) ~= CalculateStableChecksum(localPayload) then
          ApplyLootProfileSubdomainSnapshotSource(profile, leaf.subdomain, mergedPayload)
          changedDomains[GetLootProfileSubdomainParentDomain(leaf.subdomain)] = true
          changedSubdomains[#changedSubdomains + 1] = tostring(leaf.subdomain)
          appliedSubdomains = appliedSubdomains + 1
          appliedRows = appliedRows + #selectedRows
        end
      end
    end

    if appliedSubdomains == 0 then
      return false, "No selected preview rows changed the local host copy."
    end

    EnsureLootProfileDefaults(profile)
    RecalculateLootLedgerTotals(profile)
    for domain in pairs(changedDomains) do
      TouchLootProfileDomain(profile, domain)
    end
    if transferPayloads.profileId ~= "" then
      profile.meta = type(profile.meta) == "table" and profile.meta or {}
      profile.meta.profileId = transferPayloads.profileId
    end
    EnsureLootProfileIdentity(profile, resolvedName, nil, root)
    EnsureLootProfileSyncState(profile)
    EnsureLootProfileRevisionState(profile)
    MarkLootProfileAsSharedReplica(profile, "SESSION_CONFLICT_RESOLVE", {
      profileId = transferPayloads.profileId,
      profileName = transferPayloads.profileName,
      sourceCharacter = TrimText(options.sourceCharacter),
    })

    local touchedDomains = {}
    for domain in pairs(changedDomains) do
      touchedDomains[#touchedDomains + 1] = domain
    end
    table.sort(touchedDomains)

    return true, {
      appliedSubdomains = appliedSubdomains,
      appliedRows = appliedRows,
      domains = touchedDomains,
      subdomains = changedSubdomains,
      profileId = transferPayloads.profileId,
    }
  end

  local function ExportLootProfileDomainSnapshot(profileName, domains)
    local root = RootDB()
    local profile = type(root) == "table" and type(root.profiles) == "table" and root.profiles[profileName] or nil
    if type(profile) ~= "table" then
      return nil
    end
    EnsureLootProfileDefaults(profile)
    EnsureLootProfileIdentity(profile, profileName)
    EnsureLootProfileSyncState(profile)
    EnsureLootProfileRevisionState(profile)
    RecalculateLootLedgerTotals(profile)

    local normalizedDomains = NormalizeLootProfileDomainList(domains)
    local domainPayloads = {}
    local revisions = {}
    for _, domain in ipairs(normalizedDomains) do
      domainPayloads[domain] = BuildLootProfileDomainSnapshotSource(profile, domain)
      revisions[domain] = BuildLootProfileDomainRevisionEntry(profile, domain)
    end

    return PROFILE_DOMAIN_SNAPSHOT_EXPORT_PREFIX .. json_encode({
      kind = "PROFILE_DOMAIN_SNAPSHOT",
      exportMode = "SHARED_REPAIR",
      exportedAt = tonumber(time and time() or 0) or 0,
      source = {
        profileName = tostring(profileName),
        profileId = type(profile.meta) == "table" and profile.meta.profileId or nil,
      },
      domains = normalizedDomains,
      revisions = revisions,
      profile = domainPayloads,
    })
  end

  local function ExportLootProfileSubdomainSnapshot(profileName, subdomains)
    local root = RootDB()
    local profile = type(root) == "table" and type(root.profiles) == "table" and root.profiles[profileName] or nil
    if type(profile) ~= "table" then
      return nil
    end
    EnsureLootProfileDefaults(profile)
    EnsureLootProfileIdentity(profile, profileName)
    EnsureLootProfileSyncState(profile)
    EnsureLootProfileRevisionState(profile)
    RecalculateLootLedgerTotals(profile)

    local normalizedSubdomains = NormalizeLootProfileSubdomainList(subdomains, nil, profile)
    local normalizedDomains = ResolveLootProfileDomainsForSubdomains(normalizedSubdomains)
    local subdomainPayloads = {}
    local revisions = {}
    for _, subdomain in ipairs(normalizedSubdomains) do
      subdomainPayloads[subdomain] = BuildLootProfileSubdomainSnapshotSource(profile, subdomain)
    end
    for _, domain in ipairs(normalizedDomains) do
      revisions[domain] = BuildLootProfileDomainRevisionEntry(profile, domain)
    end

    return PROFILE_SUBDOMAIN_SNAPSHOT_EXPORT_PREFIX .. json_encode({
      kind = "PROFILE_SUBDOMAIN_SNAPSHOT",
      exportMode = "SHARED_REPAIR",
      exportedAt = tonumber(time and time() or 0) or 0,
      source = {
        profileName = tostring(profileName),
        profileId = type(profile.meta) == "table" and profile.meta.profileId or nil,
      },
      domains = normalizedDomains,
      subdomains = normalizedSubdomains,
      revisions = revisions,
      profile = subdomainPayloads,
    })
  end

  local function PreviewLootProfileSnapshot(dataStr)
    if type(dataStr) ~= "string" or dataStr:sub(1, #PROFILE_SNAPSHOT_EXPORT_PREFIX) ~= PROFILE_SNAPSHOT_EXPORT_PREFIX then
      return nil
    end
    local payload = dataStr:sub(#PROFILE_SNAPSHOT_EXPORT_PREFIX + 1)
    local data = json_decode(payload)
    if type(data) ~= "table" or type(data.profile) ~= "table" then
      return nil
    end
    local profile = data.profile
    local profileName = TrimText(type(data.source) == "table" and data.source.profileName or "")
    RecalculateLootLedgerTotals(profile)
    local summary = BuildLootProfileRevisionSummary(profile, profileName)
    summary.profileName = profileName ~= "" and profileName or summary.profileName
    summary.exportedAt = tonumber(data.exportedAt) or nil
    summary.sourceCharacter = ""
    summary.scopeDomains = CloneLootProfileDomainList(PROFILE_TRANSFER_DOMAINS)
    summary.transferKind = "FULL"
    return summary
  end

  local function ImportProfile(newName, dataStr)
    local root = RootDB()
    if root.profiles[newName] then
      Print("Profile already exists: " .. newName)
      return false
    end
    if type(dataStr) ~= "string" or dataStr:sub(1, #EXPORT_PREFIX) ~= EXPORT_PREFIX then
      Print("Import failed: string not recognized (missing Lid prefix).")
      return false
    end

    local payload = dataStr:sub(#EXPORT_PREFIX + 1)
    local data = json_decode(payload)
    local sourceInfo = {}
    if type(data) == "table" and type(data.profile) == "table" then
      sourceInfo.profileId = type(data.source) == "table" and data.source.profileId or nil
      sourceInfo.profileName = type(data.source) == "table" and data.source.profileName or nil
      data = data.profile
    end

    if type(data) ~= "table" or type(data.panels) ~= "table" then
      Print("Import failed: invalid data.")
      return false
    end

    data.positions = data.positions or {}
    data.spec = data.spec or { auto = false, layouts = {} }
    data.spec.layouts = data.spec.layouts or {}
    data.profileSpec = data.profileSpec or { enabled = false, mode = "SPEC", specID = nil, character = nil }
    if data.profileSpec.mode ~= "CHARACTER" then data.profileSpec.mode = "SPEC" end
    data.panelOrder = nil
    MigrateLegacyLootLedgerMeta(data)
    data.meta = type(data.meta) == "table" and data.meta or {}
    if TrimText(sourceInfo.profileId) == "" then
      sourceInfo.profileId = data.meta.profileId
    end
    if TrimText(sourceInfo.profileName) == "" then
      sourceInfo.profileName = newName
    end
    data.meta.profileId = nil

    root.profiles[newName] = data
    EnsureLootProfileDefaults(data)
    RecalculateLootLedgerTotals(data)
    AssignNewLootProfileIdentity(data, newName)
    MarkLootProfileAsIndependentClone(data, "IMPORT", sourceInfo)
    Print("Imported profile: " .. newName)
    return true
  end

  local function ImportLootProfileSnapshot(targetName, dataStr, options)
    local root = RootDB()
    local resolvedName = TrimText(targetName)
    if resolvedName == "" then
      return false, "Target profile name is required."
    end
    if type(dataStr) ~= "string" or dataStr:sub(1, #PROFILE_SNAPSHOT_EXPORT_PREFIX) ~= PROFILE_SNAPSHOT_EXPORT_PREFIX then
      return false, "Snapshot import failed: string not recognized."
    end

    local payload = dataStr:sub(#PROFILE_SNAPSHOT_EXPORT_PREFIX + 1)
    local data = json_decode(payload)
    if type(data) ~= "table" or type(data.profile) ~= "table" then
      return false, "Snapshot import failed: invalid data."
    end

    local snapshotProfile = data.profile
    snapshotProfile.positions = snapshotProfile.positions or {}
    snapshotProfile.spec = snapshotProfile.spec or { auto = false, layouts = {} }
    snapshotProfile.spec.layouts = snapshotProfile.spec.layouts or {}
    snapshotProfile.profileSpec = snapshotProfile.profileSpec or { enabled = false, mode = "SPEC", specID = nil, character = nil }
    if snapshotProfile.profileSpec.mode ~= "CHARACTER" then
      snapshotProfile.profileSpec.mode = "SPEC"
    end
    snapshotProfile.panelOrder = nil
    MigrateLegacyLootLedgerMeta(snapshotProfile)
    RecalculateLootLedgerTotals(snapshotProfile)
    snapshotProfile.meta = type(snapshotProfile.meta) == "table" and snapshotProfile.meta or {}

    local snapshotProfileId = TrimText(type(data.source) == "table" and data.source.profileId or snapshotProfile.meta.profileId)
    if snapshotProfileId == "" then
      return false, "Snapshot import failed: missing profile id."
    end

    local optionsTable = type(options) == "table" and options or {}
    local expectedProfileId = TrimText(optionsTable.expectedProfileId)
    if expectedProfileId ~= "" and string.lower(expectedProfileId) ~= string.lower(snapshotProfileId) then
      return false, "Snapshot import failed: profile id mismatch."
    end

    snapshotProfile.meta.profileId = snapshotProfileId
    root.profiles[resolvedName] = snapshotProfile
    EnsureLootProfileDefaults(snapshotProfile)
    RecalculateLootLedgerTotals(snapshotProfile)
    EnsureLootProfileIdentity(snapshotProfile, resolvedName, nil, root)
    EnsureLootProfileSyncState(snapshotProfile)
    EnsureLootProfileRevisionState(snapshotProfile)
    MarkLootProfileAsSharedReplica(snapshotProfile, "SESSION_SNAPSHOT", {
      profileId = snapshotProfileId,
      profileName = TrimText(type(data.source) == "table" and data.source.profileName or resolvedName),
      sourceCharacter = TrimText(optionsTable.sourceCharacter),
    })
    return true, resolvedName, snapshotProfileId
  end

  local function ImportLootProfileDomainSnapshot(targetName, dataStr, options)
    local root = RootDB()
    local resolvedName = TrimText(targetName)
    if resolvedName == "" then
      return false, "Target profile name is required."
    end
    if type(dataStr) ~= "string" or dataStr:sub(1, #PROFILE_DOMAIN_SNAPSHOT_EXPORT_PREFIX) ~= PROFILE_DOMAIN_SNAPSHOT_EXPORT_PREFIX then
      return false, "Domain snapshot import failed: string not recognized."
    end

    local payload = dataStr:sub(#PROFILE_DOMAIN_SNAPSHOT_EXPORT_PREFIX + 1)
    local data = json_decode(payload)
    if type(data) ~= "table" or type(data.profile) ~= "table" then
      return false, "Domain snapshot import failed: invalid data."
    end

    local snapshotProfileId = TrimText(type(data.source) == "table" and data.source.profileId or "")
    if snapshotProfileId == "" then
      return false, "Domain snapshot import failed: missing profile id."
    end

    local optionsTable = type(options) == "table" and options or {}
    local expectedProfileId = TrimText(optionsTable.expectedProfileId)
    if expectedProfileId ~= "" and string.lower(expectedProfileId) ~= string.lower(snapshotProfileId) then
      return false, "Domain snapshot import failed: profile id mismatch."
    end

    local profile = type(root.profiles) == "table" and root.profiles[resolvedName] or nil
    if type(profile) ~= "table" then
      return false, "Domain snapshot import failed: target profile was not found."
    end

    EnsureLootProfileDefaults(profile)
    profile.meta = type(profile.meta) == "table" and profile.meta or {}

    local domainPayloads = type(data.profile) == "table" and data.profile or {}
    local revisions = type(data.revisions) == "table" and data.revisions or {}
    local normalizedDomains = NormalizeLootProfileDomainList(data.domains)
    local includedDomains = {}
    for _, domain in ipairs(normalizedDomains) do
      includedDomains[domain] = true
    end

    local enabledState = type(profile.settings) == "table" and profile.settings.enabled == true or false
    if includedDomains.settings then
      profile.settings = DeepCopy(type(domainPayloads.settings) == "table" and domainPayloads.settings or {})
      profile.settings.enabled = enabledState
    end

    if includedDomains.permissions then
      local permissionsPayload = type(domainPayloads.permissions) == "table" and domainPayloads.permissions or {}
      profile.meta.permissions = DeepCopy(type(permissionsPayload.permissions) == "table" and permissionsPayload.permissions or {})
      profile.meta.permissionPolicy = DeepCopy(type(permissionsPayload.permissionPolicy) == "table" and permissionsPayload.permissionPolicy or { version = 1, roles = {} })
    end

    if includedDomains.loot then
      local lootPayload = type(domainPayloads.loot) == "table" and domainPayloads.loot or {}
      profile.lootLedger = DeepCopy(type(lootPayload.lootLedger) == "table" and lootPayload.lootLedger or {})
      profile.lootLedgerMeta = DeepCopy(type(lootPayload.lootLedgerMeta) == "table" and lootPayload.lootLedgerMeta or {})
      profile.lootLedgerEntrySerial = tonumber(lootPayload.lootLedgerEntrySerial) or 0
      profile.lootRollStats = DeepCopy(type(lootPayload.lootRollStats) == "table" and lootPayload.lootRollStats or {})
      profile.lootListGroups = DeepCopy(type(lootPayload.lootListGroups) == "table" and lootPayload.lootListGroups or {})
    end

    if includedDomains.session then
      local sessionPayload = type(domainPayloads.session) == "table" and domainPayloads.session or {}
      profile.sessions = DeepCopy(type(sessionPayload.sessions) == "table" and sessionPayload.sessions or {})
      profile.liveBoardHistory = DeepCopy(type(sessionPayload.liveBoardHistory) == "table" and sessionPayload.liveBoardHistory or {})
    end

    EnsureLootProfileDefaults(profile)
    RecalculateLootLedgerTotals(profile)
    profile.meta.profileId = snapshotProfileId
    EnsureLootProfileIdentity(profile, resolvedName, nil, root)
    EnsureLootProfileSyncState(profile)

    local domainRevisions = EnsureLootProfileRevisionState(profile)
    local maxRevision = math.max(0, tonumber(profile.meta.revision) or 0)
    local maxUpdatedAt = math.max(0, tonumber(profile.meta.updatedAt) or 0)
    for _, domain in ipairs(normalizedDomains) do
      local revisionPayload = type(revisions[domain]) == "table" and revisions[domain] or {}
      local entry = type(domainRevisions[domain]) == "table" and domainRevisions[domain] or {}
      entry.revision = math.max(0, tonumber(revisionPayload.revision) or tonumber(entry.revision) or 0)
      entry.updatedAt = math.max(0, tonumber(revisionPayload.updatedAt) or tonumber(entry.updatedAt) or 0)
      domainRevisions[domain] = entry
      maxRevision = math.max(maxRevision, entry.revision)
      maxUpdatedAt = math.max(maxUpdatedAt, entry.updatedAt)
    end

    if includedDomains.loot or includedDomains.session then
      local operationalPayload = type(revisions.operational) == "table" and revisions.operational or {}
      local lootEntry = type(domainRevisions.loot) == "table" and domainRevisions.loot or {}
      local sessionEntry = type(domainRevisions.session) == "table" and domainRevisions.session or {}
      local operationalEntry = type(domainRevisions.operational) == "table" and domainRevisions.operational or {}
      operationalEntry.revision = math.max(
        0,
        tonumber(operationalPayload.revision) or 0,
        tonumber(lootEntry.revision) or 0,
        tonumber(sessionEntry.revision) or 0
      )
      operationalEntry.updatedAt = math.max(
        0,
        tonumber(operationalPayload.updatedAt) or 0,
        tonumber(lootEntry.updatedAt) or 0,
        tonumber(sessionEntry.updatedAt) or 0
      )
      domainRevisions.operational = operationalEntry
      maxRevision = math.max(maxRevision, operationalEntry.revision)
      maxUpdatedAt = math.max(maxUpdatedAt, operationalEntry.updatedAt)
    end

    profile.meta.revision = maxRevision
    profile.meta.updatedAt = maxUpdatedAt
    MarkLootProfileAsSharedReplica(profile, "SESSION_DOMAIN_SNAPSHOT", {
      profileId = snapshotProfileId,
      profileName = TrimText(type(data.source) == "table" and data.source.profileName or resolvedName),
      sourceCharacter = TrimText(optionsTable.sourceCharacter),
    })
    return true, resolvedName, snapshotProfileId
  end

  local function ImportLootProfileSubdomainSnapshot(targetName, dataStr, options)
    local root = RootDB()
    local resolvedName = TrimText(targetName)
    if resolvedName == "" then
      return false, "Target profile name is required."
    end
    if type(dataStr) ~= "string" or dataStr:sub(1, #PROFILE_SUBDOMAIN_SNAPSHOT_EXPORT_PREFIX) ~= PROFILE_SUBDOMAIN_SNAPSHOT_EXPORT_PREFIX then
      return false, "Subdomain snapshot import failed: string not recognized."
    end

    local payload = dataStr:sub(#PROFILE_SUBDOMAIN_SNAPSHOT_EXPORT_PREFIX + 1)
    local data = json_decode(payload)
    if type(data) ~= "table" or type(data.profile) ~= "table" then
      return false, "Subdomain snapshot import failed: invalid data."
    end

    local snapshotProfileId = TrimText(type(data.source) == "table" and data.source.profileId or "")
    if snapshotProfileId == "" then
      return false, "Subdomain snapshot import failed: missing profile id."
    end

    local optionsTable = type(options) == "table" and options or {}
    local expectedProfileId = TrimText(optionsTable.expectedProfileId)
    if expectedProfileId ~= "" and string.lower(expectedProfileId) ~= string.lower(snapshotProfileId) then
      return false, "Subdomain snapshot import failed: profile id mismatch."
    end

    local profile = type(root.profiles) == "table" and root.profiles[resolvedName] or nil
    if type(profile) ~= "table" then
      return false, "Subdomain snapshot import failed: target profile was not found."
    end

    EnsureLootProfileDefaults(profile)
    profile.meta = type(profile.meta) == "table" and profile.meta or {}

    local subdomainPayloads = type(data.profile) == "table" and data.profile or {}
    local revisions = type(data.revisions) == "table" and data.revisions or {}
    local normalizedSubdomains = NormalizeLootProfileSubdomainList(data.subdomains, data.domains)
    local normalizedDomains = ResolveLootProfileDomainsForSubdomains(normalizedSubdomains)

    for _, subdomain in ipairs(normalizedSubdomains) do
      ApplyLootProfileSubdomainSnapshotSource(profile, subdomain, subdomainPayloads[subdomain])
    end

    EnsureLootProfileDefaults(profile)
    RecalculateLootLedgerTotals(profile)
    profile.meta.profileId = snapshotProfileId
    EnsureLootProfileIdentity(profile, resolvedName, nil, root)
    EnsureLootProfileSyncState(profile)

    local domainRevisions = EnsureLootProfileRevisionState(profile)
    local maxRevision = math.max(0, tonumber(profile.meta.revision) or 0)
    local maxUpdatedAt = math.max(0, tonumber(profile.meta.updatedAt) or 0)
    for _, domain in ipairs(normalizedDomains) do
      local revisionPayload = type(revisions[domain]) == "table" and revisions[domain] or {}
      local entry = type(domainRevisions[domain]) == "table" and domainRevisions[domain] or {}
      entry.revision = math.max(0, tonumber(revisionPayload.revision) or tonumber(entry.revision) or 0)
      entry.updatedAt = math.max(0, tonumber(revisionPayload.updatedAt) or tonumber(entry.updatedAt) or 0)
      domainRevisions[domain] = entry
      maxRevision = math.max(maxRevision, entry.revision)
      maxUpdatedAt = math.max(maxUpdatedAt, entry.updatedAt)
    end

    if domainRevisions.loot or domainRevisions.session then
      local operationalEntry = type(domainRevisions.operational) == "table" and domainRevisions.operational or {}
      local lootEntry = type(domainRevisions.loot) == "table" and domainRevisions.loot or {}
      local sessionEntry = type(domainRevisions.session) == "table" and domainRevisions.session or {}
      operationalEntry.revision = math.max(
        0,
        tonumber(operationalEntry.revision) or 0,
        tonumber(lootEntry.revision) or 0,
        tonumber(sessionEntry.revision) or 0
      )
      operationalEntry.updatedAt = math.max(
        0,
        tonumber(operationalEntry.updatedAt) or 0,
        tonumber(lootEntry.updatedAt) or 0,
        tonumber(sessionEntry.updatedAt) or 0
      )
      domainRevisions.operational = operationalEntry
      maxRevision = math.max(maxRevision, operationalEntry.revision)
      maxUpdatedAt = math.max(maxUpdatedAt, operationalEntry.updatedAt)
    end

    profile.meta.revision = maxRevision
    profile.meta.updatedAt = maxUpdatedAt
    MarkLootProfileAsSharedReplica(profile, "SESSION_SUBDOMAIN_SNAPSHOT", {
      profileId = snapshotProfileId,
      profileName = TrimText(type(data.source) == "table" and data.source.profileName or resolvedName),
      sourceCharacter = TrimText(optionsTable.sourceCharacter),
    })
    return true, resolvedName, snapshotProfileId
  end

  local function ImportLootProfileSubdomainPatch(targetName, dataStr, options)
    local root = RootDB()
    local resolvedName = TrimText(targetName)
    if resolvedName == "" then
      return false, "Target profile name is required."
    end
    if type(dataStr) ~= "string" or dataStr:sub(1, #PROFILE_SUBDOMAIN_PATCH_EXPORT_PREFIX) ~= PROFILE_SUBDOMAIN_PATCH_EXPORT_PREFIX then
      return false, "Subdomain patch import failed: string not recognized."
    end

    local payload = dataStr:sub(#PROFILE_SUBDOMAIN_PATCH_EXPORT_PREFIX + 1)
    local data = json_decode(payload)
    if type(data) ~= "table" or type(data.profile) ~= "table" then
      return false, "Subdomain patch import failed: invalid data."
    end

    local snapshotProfileId = TrimText(type(data.source) == "table" and data.source.profileId or "")
    if snapshotProfileId == "" then
      return false, "Subdomain patch import failed: missing profile id."
    end

    local optionsTable = type(options) == "table" and options or {}
    local expectedProfileId = TrimText(optionsTable.expectedProfileId)
    if expectedProfileId ~= "" and string.lower(expectedProfileId) ~= string.lower(snapshotProfileId) then
      return false, "Subdomain patch import failed: profile id mismatch."
    end

    local profile = type(root.profiles) == "table" and root.profiles[resolvedName] or nil
    if type(profile) ~= "table" then
      return false, "Subdomain patch import failed: target profile was not found."
    end

    EnsureLootProfileDefaults(profile)
    profile.meta = type(profile.meta) == "table" and profile.meta or {}

    local patchPayloads = type(data.profile) == "table" and data.profile or {}
    local revisions = type(data.revisions) == "table" and data.revisions or {}
    local normalizedSubdomains = NormalizeLootProfileSubdomainList(data.subdomains, data.domains)
    local normalizedDomains = ResolveLootProfileDomainsForSubdomains(normalizedSubdomains)

    local appliedAny = false
    for _, subdomain in ipairs(normalizedSubdomains) do
      appliedAny = ApplyLootProfileSubdomainPatchPayload(profile, subdomain, patchPayloads[subdomain]) or appliedAny
    end
    if not appliedAny and #normalizedSubdomains > 0 then
      return false, "Subdomain patch import failed: no supported patch scope was applied."
    end

    EnsureLootProfileDefaults(profile)
    RecalculateLootLedgerTotals(profile)
    profile.meta.profileId = snapshotProfileId
    EnsureLootProfileIdentity(profile, resolvedName, nil, root)
    EnsureLootProfileSyncState(profile)

    local domainRevisions = EnsureLootProfileRevisionState(profile)
    local maxRevision = math.max(0, tonumber(profile.meta.revision) or 0)
    local maxUpdatedAt = math.max(0, tonumber(profile.meta.updatedAt) or 0)
    for _, domain in ipairs(normalizedDomains) do
      local revisionPayload = type(revisions[domain]) == "table" and revisions[domain] or {}
      local entry = type(domainRevisions[domain]) == "table" and domainRevisions[domain] or {}
      entry.revision = math.max(0, tonumber(revisionPayload.revision) or tonumber(entry.revision) or 0)
      entry.updatedAt = math.max(0, tonumber(revisionPayload.updatedAt) or tonumber(entry.updatedAt) or 0)
      domainRevisions[domain] = entry
      maxRevision = math.max(maxRevision, entry.revision)
      maxUpdatedAt = math.max(maxUpdatedAt, entry.updatedAt)
    end

    if domainRevisions.loot or domainRevisions.session then
      local operationalEntry = type(domainRevisions.operational) == "table" and domainRevisions.operational or {}
      local lootEntry = type(domainRevisions.loot) == "table" and domainRevisions.loot or {}
      local sessionEntry = type(domainRevisions.session) == "table" and domainRevisions.session or {}
      operationalEntry.revision = math.max(
        0,
        tonumber(operationalEntry.revision) or 0,
        tonumber(lootEntry.revision) or 0,
        tonumber(sessionEntry.revision) or 0
      )
      operationalEntry.updatedAt = math.max(
        0,
        tonumber(operationalEntry.updatedAt) or 0,
        tonumber(lootEntry.updatedAt) or 0,
        tonumber(sessionEntry.updatedAt) or 0
      )
      domainRevisions.operational = operationalEntry
      maxRevision = math.max(maxRevision, operationalEntry.revision)
      maxUpdatedAt = math.max(maxUpdatedAt, operationalEntry.updatedAt)
    end

    profile.meta.revision = maxRevision
    profile.meta.updatedAt = maxUpdatedAt
    MarkLootProfileAsSharedReplica(profile, "SESSION_SUBDOMAIN_PATCH", {
      profileId = snapshotProfileId,
      profileName = TrimText(type(data.source) == "table" and data.source.profileName or resolvedName),
      sourceCharacter = TrimText(optionsTable.sourceCharacter),
    })
    return true, resolvedName, snapshotProfileId
  end

  local function ImportLootProfileConflictRowPatch(targetName, dataStr, options)
    local root = RootDB()
    local resolvedName = TrimText(targetName)
    if resolvedName == "" then
      return false, "Target profile name is required."
    end
    if type(dataStr) ~= "string" or dataStr:sub(1, #PROFILE_CONFLICT_ROW_PATCH_EXPORT_PREFIX) ~= PROFILE_CONFLICT_ROW_PATCH_EXPORT_PREFIX then
      return false, "Conflict row patch import failed: string not recognized."
    end

    local payload = dataStr:sub(#PROFILE_CONFLICT_ROW_PATCH_EXPORT_PREFIX + 1)
    local data = json_decode(payload)
    if type(data) ~= "table" or type(data.rowsBySubdomain) ~= "table" then
      return false, "Conflict row patch import failed: invalid data."
    end

    local snapshotProfileId = TrimText(type(data.source) == "table" and data.source.profileId or "")
    if snapshotProfileId == "" then
      return false, "Conflict row patch import failed: missing profile id."
    end

    local optionsTable = type(options) == "table" and options or {}
    local expectedProfileId = TrimText(optionsTable.expectedProfileId)
    if expectedProfileId ~= "" and string.lower(expectedProfileId) ~= string.lower(snapshotProfileId) then
      return false, "Conflict row patch import failed: profile id mismatch."
    end

    local profile = type(root.profiles) == "table" and root.profiles[resolvedName] or nil
    if type(profile) ~= "table" then
      return false, "Conflict row patch import failed: target profile was not found."
    end

    EnsureLootProfileDefaults(profile)
    profile.meta = type(profile.meta) == "table" and profile.meta or {}

    local rowsBySubdomain = type(data.rowsBySubdomain) == "table" and data.rowsBySubdomain or {}
    local revisions = type(data.revisions) == "table" and data.revisions or {}
    local normalizedSubdomains = NormalizeLootProfileSubdomainList(data.subdomains, data.domains)
    local normalizedDomains = ResolveLootProfileDomainsForSubdomains(normalizedSubdomains)

    local appliedAny = false
    for _, subdomain in ipairs(normalizedSubdomains) do
      local localPayload = BuildLootProfileSubdomainSnapshotSource(profile, subdomain)
      local mergedPayload = type(conflictResolverHelpers.ApplySelectedRemoteRowPayloads) == "function"
        and conflictResolverHelpers.ApplySelectedRemoteRowPayloads(subdomain, localPayload, rowsBySubdomain[subdomain])
        or localPayload
      if CalculateStableChecksum(mergedPayload) ~= CalculateStableChecksum(localPayload) then
        ApplyLootProfileSubdomainSnapshotSource(profile, subdomain, mergedPayload)
        appliedAny = true
      end
    end
    if not appliedAny and #normalizedSubdomains > 0 then
      return false, "Conflict row patch import failed: no selected row changed the target profile."
    end

    EnsureLootProfileDefaults(profile)
    RecalculateLootLedgerTotals(profile)
    profile.meta.profileId = snapshotProfileId
    EnsureLootProfileIdentity(profile, resolvedName, nil, root)
    EnsureLootProfileSyncState(profile)

    local domainRevisions = EnsureLootProfileRevisionState(profile)
    local maxRevision = math.max(0, tonumber(profile.meta.revision) or 0)
    local maxUpdatedAt = math.max(0, tonumber(profile.meta.updatedAt) or 0)
    for _, domain in ipairs(normalizedDomains) do
      local revisionPayload = type(revisions[domain]) == "table" and revisions[domain] or {}
      local entry = type(domainRevisions[domain]) == "table" and domainRevisions[domain] or {}
      entry.revision = math.max(0, tonumber(revisionPayload.revision) or tonumber(entry.revision) or 0)
      entry.updatedAt = math.max(0, tonumber(revisionPayload.updatedAt) or tonumber(entry.updatedAt) or 0)
      domainRevisions[domain] = entry
      maxRevision = math.max(maxRevision, entry.revision)
      maxUpdatedAt = math.max(maxUpdatedAt, entry.updatedAt)
    end

    if domainRevisions.loot or domainRevisions.session then
      local operationalEntry = type(domainRevisions.operational) == "table" and domainRevisions.operational or {}
      local lootEntry = type(domainRevisions.loot) == "table" and domainRevisions.loot or {}
      local sessionEntry = type(domainRevisions.session) == "table" and domainRevisions.session or {}
      operationalEntry.revision = math.max(
        0,
        tonumber(operationalEntry.revision) or 0,
        tonumber(lootEntry.revision) or 0,
        tonumber(sessionEntry.revision) or 0
      )
      operationalEntry.updatedAt = math.max(
        0,
        tonumber(operationalEntry.updatedAt) or 0,
        tonumber(lootEntry.updatedAt) or 0,
        tonumber(sessionEntry.updatedAt) or 0
      )
      domainRevisions.operational = operationalEntry
      maxRevision = math.max(maxRevision, operationalEntry.revision)
      maxUpdatedAt = math.max(maxUpdatedAt, operationalEntry.updatedAt)
    end

    profile.meta.revision = maxRevision
    profile.meta.updatedAt = maxUpdatedAt
    MarkLootProfileAsSharedReplica(profile, "SESSION_ROW_PATCH", {
      profileId = snapshotProfileId,
      profileName = TrimText(type(data.source) == "table" and data.source.profileName or resolvedName),
      sourceCharacter = TrimText(optionsTable.sourceCharacter),
    })
    return true, resolvedName, snapshotProfileId
  end

  local function ExportLootRollSettings(profileName)
    local profile = select(1, GetLootProfile(profileName))
    if type(profile) ~= "table" then
      return nil
    end
    local payload = {
      rollTemplate = profile.settings and profile.settings.rollTemplate or nil,
      rollOptions = DeepCopy(profile.settings and profile.settings.rollOptions or {}),
    }
    return ROLL_SETTINGS_EXPORT_PREFIX .. json_encode(payload)
  end

  local function ImportLootRollSettings(profileName, dataStr)
    local access = GetLootProfileAccessInfo(profileName)
    if not access or not access.canManageProfile then
      return false, "Only the Master or a Council Member can edit this profile."
    end
    if type(dataStr) ~= "string" or dataStr:sub(1, #ROLL_SETTINGS_EXPORT_PREFIX) ~= ROLL_SETTINGS_EXPORT_PREFIX then
      return false, "Import failed: string not recognized for roll settings."
    end
    local payload = dataStr:sub(#ROLL_SETTINGS_EXPORT_PREFIX + 1)
    local data = json_decode(payload)
    if type(data) ~= "table" or type(data.rollOptions) ~= "table" then
      return false, "Import failed: invalid roll settings data."
    end

    local profile = select(1, GetLootProfile(profileName))
    EnsureLootProfileDefaults(profile)
    profile.settings.rollTemplate = data.rollTemplate
    profile.settings.rollOptions = DeepCopy(data.rollOptions)
    EnsureLootProfileDefaults(profile)
    if type(TouchLootProfileSettings) == "function" then
      TouchLootProfileSettings(profile)
    else
      TouchLootProfile(profile)
    end
    return true
  end

  local function CopyLootRollSettings(sourceProfileName, targetProfileName)
    local access = GetLootProfileAccessInfo(targetProfileName)
    if not access or not access.canManageProfile then
      return false, "Only the Master or a Council Member can edit this profile."
    end
    local sourceProfile = select(1, GetLootProfile(sourceProfileName))
    local targetProfile = select(1, GetLootProfile(targetProfileName))
    if type(sourceProfile) ~= "table" or type(targetProfile) ~= "table" then
      return false, "Profile not found."
    end
    EnsureLootProfileDefaults(sourceProfile)
    EnsureLootProfileDefaults(targetProfile)
    targetProfile.settings.rollTemplate = sourceProfile.settings and sourceProfile.settings.rollTemplate or nil
    targetProfile.settings.rollOptions = DeepCopy(sourceProfile.settings and sourceProfile.settings.rollOptions or {})
    EnsureLootProfileDefaults(targetProfile)
    if type(TouchLootProfileSettings) == "function" then
      TouchLootProfileSettings(targetProfile)
    else
      TouchLootProfile(targetProfile)
    end
    return true
  end

  local function ExportLootPointSettings(profileName)
    local profile = select(1, GetLootProfile(profileName))
    if type(profile) ~= "table" then
      return nil
    end
    local payload = {
      pointMode = NormalizePointMode(profile.settings and profile.settings.pointMode),
      pointRules = DeepCopy(profile.settings and profile.settings.pointRules or {}),
      lidTable = DeepCopy(profile.settings and profile.settings.lidTable or { rows = {} }),
    }
    return POINT_SETTINGS_EXPORT_PREFIX .. json_encode(payload)
  end

  local function ImportLootPointSettings(profileName, dataStr)
    local access = GetLootProfileAccessInfo(profileName)
    if not access or not access.canManageProfile then
      return false, "Only the Master or a Council Member can edit this profile."
    end
    if type(dataStr) ~= "string" or dataStr:sub(1, #POINT_SETTINGS_EXPORT_PREFIX) ~= POINT_SETTINGS_EXPORT_PREFIX then
      return false, "Import failed: string not recognized for point settings."
    end
    local payload = dataStr:sub(#POINT_SETTINGS_EXPORT_PREFIX + 1)
    local data = json_decode(payload)
    if type(data) ~= "table" then
      return false, "Import failed: invalid point settings data."
    end

    local profile = select(1, GetLootProfile(profileName))
    EnsureLootProfileDefaults(profile)
    profile.settings.pointMode = NormalizePointMode(data.pointMode)
    profile.settings.pointRules = DeepCopy(type(data.pointRules) == "table" and data.pointRules or {})
    profile.settings.lidTable = DeepCopy(type(data.lidTable) == "table" and data.lidTable or { rows = {} })
    EnsureLidTableRows(profile.settings)
    EnsureLootProfileDefaults(profile)
    if type(TouchLootProfileSettings) == "function" then
      TouchLootProfileSettings(profile)
    else
      TouchLootProfile(profile)
    end
    return true
  end

  local function CopyLootPointSettings(sourceProfileName, targetProfileName)
    local access = GetLootProfileAccessInfo(targetProfileName)
    if not access or not access.canManageProfile then
      return false, "Only the Master or a Council Member can edit this profile."
    end
    local sourceProfile = select(1, GetLootProfile(sourceProfileName))
    local targetProfile = select(1, GetLootProfile(targetProfileName))
    if type(sourceProfile) ~= "table" or type(targetProfile) ~= "table" then
      return false, "Profile not found."
    end
    EnsureLootProfileDefaults(sourceProfile)
    EnsureLootProfileDefaults(targetProfile)
    targetProfile.settings.pointMode = NormalizePointMode(sourceProfile.settings and sourceProfile.settings.pointMode)
    targetProfile.settings.pointRules = DeepCopy(sourceProfile.settings and sourceProfile.settings.pointRules or {})
    targetProfile.settings.lidTable = DeepCopy(sourceProfile.settings and sourceProfile.settings.lidTable or { rows = {} })
    EnsureLidTableRows(targetProfile.settings)
    EnsureLootProfileDefaults(targetProfile)
    if type(TouchLootProfileSettings) == "function" then
      TouchLootProfileSettings(targetProfile)
    else
      TouchLootProfile(targetProfile)
    end
    return true
  end

  local function GetSpecKey()
    if not GetSpecialization or not GetSpecializationInfo then return "nospec" end
    local idx = GetSpecialization()
    if not idx then return "nospec" end
    local specID = GetSpecializationInfo(idx)
    return tostring(specID or idx or "nospec")
  end

  local function GetCurrentSpecID()
    if not GetSpecialization or not GetSpecializationInfo then return nil end
    local idx = GetSpecialization()
    if not idx then return nil end
    local specID = GetSpecializationInfo(idx)
    return specID
  end

  local function GetCharacterKey()
    if not UnitName then return nil end
    local name = UnitName("player")
    if not name then return nil end
    local realm = nil
    if GetNormalizedRealmName then
      realm = GetNormalizedRealmName()
    elseif GetRealmName then
      realm = GetRealmName()
    end
    if realm and realm ~= "" then
      return name .. "-" .. realm
    end
    return name
  end

  local characterListSnapshotSource
  local characterListSnapshot

  local function EnsureCharacterList()
    local root = RootDB()
    root.characters = root.characters or {}
    return root.characters
  end

  local function AddCharacterToList(key)
    if not key or key == "" then return end
    local list = EnsureCharacterList()
    for _, v in ipairs(list) do
      if v == key then return end
    end
    list[#list + 1] = key
    table.sort(list)
    characterListSnapshotSource = nil
    characterListSnapshot = nil
  end

  local function GetCharacterList()
    local list = EnsureCharacterList()
    if characterListSnapshotSource ~= list or type(characterListSnapshot) ~= "table" then
      local snapshot = {}
      for i, v in ipairs(list) do snapshot[i] = v end
      table.sort(snapshot)
      characterListSnapshotSource = list
      characterListSnapshot = snapshot
    end
    local out = {}
    for i, v in ipairs(characterListSnapshot) do out[i] = v end
    return out
  end

  local function LoadLayoutFromSpec(specKey)
    local db = DB()
    local lay = db.spec.layouts[specKey]
    if not lay then
      Print("No saved layout for this spec yet.")
      return false
    end
    db.panels = DeepCopy(lay.panels or {})
    db.positions = DeepCopy(lay.positions or {})
    Print("Loaded layout for spec: " .. specKey)
    return true
  end

  local function EnsureDefaults()
    local db = DB()
    local root = RootDB()
    RunRootMigrations(root)

    EnsureProfileRecord(root, "Default")
    local currentCharacterKey = type(GetCharacterKey) == "function" and TrimText(GetCharacterKey() or "") or ""
    for _, profile in pairs(root.profiles or {}) do
      EnsureLootProfilePermissionState(profile, currentCharacterKey)
      EnsureLootProfileSyncState(profile)
      EnsureLootProfileRevisionState(profile)
    end
    if type(RepairSimulationProfileOwnership) == "function" then
      RepairSimulationProfileOwnership(root)
    end
    local _, activeProfileName = NormalizeActiveLootSessions(root)
    NormalizeLootProfileEnabledState(root, activeProfileName)

    root.ui = root.ui or {}
    if TrimText(root.currentProfile) == "Simulation" then
      local fallbackProfile = TrimText(root.ui.lastNonSimulationProfile)
      if fallbackProfile == "" or fallbackProfile == "Simulation" or not root.profiles[fallbackProfile] then
        if TrimText(activeProfileName) ~= "" and TrimText(activeProfileName) ~= "Simulation" and root.profiles[activeProfileName] then
          fallbackProfile = activeProfileName
        else
          for profileName in pairs(root.profiles or {}) do
            local resolvedName = TrimText(profileName)
            if resolvedName ~= "" and resolvedName ~= "Simulation" and resolvedName ~= "Default" then
              fallbackProfile = resolvedName
              break
            end
          end
          if fallbackProfile == "" and root.profiles.Default then
            fallbackProfile = "Default"
          end
        end
      end
      if fallbackProfile ~= "" and fallbackProfile ~= "Simulation" and root.profiles[fallbackProfile] then
        root.currentProfile = fallbackProfile
      end
    elseif TrimText(root.currentProfile) ~= "" and TrimText(root.currentProfile) ~= "Default" and TrimText(root.currentProfile) ~= "Simulation" then
      root.ui.lastNonSimulationProfile = root.currentProfile
    end

    if db.__seeded then return end
    db.__seeded = true
  end

  return {
    DeepCopy = DeepCopy,
    ExportProfile = ExportProfile,
    ImportProfile = ImportProfile,
    ExportLootProfileSnapshot = ExportLootProfileSnapshot,
    ExportLootProfileDomainSnapshot = ExportLootProfileDomainSnapshot,
    ExportLootProfileSubdomainSnapshot = ExportLootProfileSubdomainSnapshot,
    ExportLootProfileSubdomainPatch = ExportLootProfileSubdomainPatch,
    ExportLootProfileConflictRowPatch = ExportLootProfileConflictRowPatch,
    ExportLootProfileSubdomainPatchManifest = ExportLootProfileSubdomainPatchManifest,
    ImportLootProfileSnapshot = ImportLootProfileSnapshot,
    ImportLootProfileDomainSnapshot = ImportLootProfileDomainSnapshot,
    ImportLootProfileSubdomainSnapshot = ImportLootProfileSubdomainSnapshot,
    ImportLootProfileSubdomainPatch = ImportLootProfileSubdomainPatch,
    ImportLootProfileConflictRowPatch = ImportLootProfileConflictRowPatch,
    PreviewLootProfileSnapshot = PreviewLootProfileSnapshot,
    PreviewLootProfileDomainSnapshot = PreviewLootProfileDomainSnapshot,
    PreviewLootProfileSubdomainSnapshot = PreviewLootProfileSubdomainSnapshot,
    PreviewLootProfileSubdomainPatch = PreviewLootProfileSubdomainPatch,
    PreviewLootProfileConflictRowPatch = PreviewLootProfileConflictRowPatch,
    PreviewLootProfileSubdomainPatchManifest = PreviewLootProfileSubdomainPatchManifest,
    GetLootProfileRevisionSummary = GetLootProfileRevisionSummary,
    ExportLootRollSettings = ExportLootRollSettings,
    ImportLootRollSettings = ImportLootRollSettings,
    CopyLootRollSettings = CopyLootRollSettings,
    ExportLootPointSettings = ExportLootPointSettings,
    ImportLootPointSettings = ImportLootPointSettings,
    CopyLootPointSettings = CopyLootPointSettings,
    GetSpecKey = GetSpecKey,
    GetCurrentSpecID = GetCurrentSpecID,
    GetCharacterKey = GetCharacterKey,
    AddCharacterToList = AddCharacterToList,
    GetCharacterList = GetCharacterList,
    LoadLayoutFromSpec = LoadLayoutFromSpec,
    EnsureDefaults = EnsureDefaults,
    RunRootMigrations = RunRootMigrations,
    EnsureLootProfileIdentity = EnsureLootProfileIdentity,
    AssignNewLootProfileIdentity = AssignNewLootProfileIdentity,
    EnsureLootProfileSyncState = EnsureLootProfileSyncState,
    MarkLootProfileAsIndependentClone = MarkLootProfileAsIndependentClone,
    MarkLootProfileAsSharedReplica = MarkLootProfileAsSharedReplica,
    EnsureLootProfileRevisionState = EnsureLootProfileRevisionState,
    BuildLootProfileSnapshotDiff = BuildLootProfileSnapshotDiff,
    BuildLootProfileDomainSnapshotDiff = BuildLootProfileDomainSnapshotDiff,
    BuildLootProfileSubdomainSnapshotDiff = BuildLootProfileSubdomainSnapshotDiff,
    BuildLootProfileSubdomainPatchDiff = BuildLootProfileSubdomainPatchDiff,
    BuildLootProfileConflictRowPatchDiff = BuildLootProfileConflictRowPatchDiff,
    BuildLootProfileTransferConflictPreview = BuildLootProfileTransferConflictPreview,
    ApplyLootProfileTransferConflictResolution = ApplyLootProfileTransferConflictResolution,
    BuildLootProfileRevisionSummary = BuildLootProfileRevisionSummary,
    GetLootProfileRevisionSummary = GetLootProfileRevisionSummary,
    GetLootProfileDomainRevision = GetLootProfileDomainRevision,
    NormalizeLootProfileSubdomainList = NormalizeLootProfileSubdomainList,
    CloneLootProfileSubdomainList = CloneLootProfileSubdomainList,
    FilterLootProfilePatchCapableSubdomains = FilterLootProfilePatchCapableSubdomains,
    GetLootProfileSubdomainKeysForDomain = GetLootProfileSubdomainKeysForDomain,
    GetLootProfileSubdomainLabel = GetLootProfileSubdomainLabel,
    GetLootProfileSubdomainParentDomain = GetLootProfileSubdomainParentDomain,
    ResolveLootProfileDomainsForSubdomains = ResolveLootProfileDomainsForSubdomains,
    GetLootProfileSubchecksumManifest = GetLootProfileSubchecksumManifest,
    TouchLootProfileDomain = TouchLootProfileDomain,
  }
end
