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

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

  local RootDB = deps.RootDB
  local Print = deps.Print
  local TrimText = deps.TrimText
  local DeepCopy = deps.DeepCopy
  local GetCharacterKey = deps.GetCharacterKey
  local GetLocalAutoPassEnabled = deps.GetLocalAutoPassEnabled
  local GetActiveLootSession = deps.GetActiveLootSession
  local GetLootProfile = deps.GetLootProfile
  local GetLootProfileId = deps.GetLootProfileId
  local GetLootProfileRevisionSummary = deps.GetLootProfileRevisionSummary
  local ExportLootProfileSnapshot = deps.ExportLootProfileSnapshot
  local ExportLootProfileDomainSnapshot = deps.ExportLootProfileDomainSnapshot
  local ExportLootProfileSubdomainSnapshot = deps.ExportLootProfileSubdomainSnapshot
  local ImportLootProfileSnapshot = deps.ImportLootProfileSnapshot
  local ImportLootProfileDomainSnapshot = deps.ImportLootProfileDomainSnapshot
  local ImportLootProfileSubdomainSnapshot = deps.ImportLootProfileSubdomainSnapshot
  local PreviewLootProfileSnapshot = deps.PreviewLootProfileSnapshot
  local PreviewLootProfileDomainSnapshot = deps.PreviewLootProfileDomainSnapshot
  local PreviewLootProfileSubdomainSnapshot = deps.PreviewLootProfileSubdomainSnapshot
  local BuildLootProfileSnapshotDiff = deps.BuildLootProfileSnapshotDiff
  local BuildLootProfileDomainSnapshotDiff = deps.BuildLootProfileDomainSnapshotDiff
  local BuildLootProfileSubdomainSnapshotDiff = deps.BuildLootProfileSubdomainSnapshotDiff
  local BuildLootProfileLiveBoardSnapshotChecksumSource = deps.BuildLootProfileLiveBoardSnapshotChecksumSource
  local BuildLootProfileLiveBoardChecksumSource = deps.BuildLootProfileLiveBoardChecksumSource
  local BuildLootProfileTransferConflictPreview = deps.BuildLootProfileTransferConflictPreview
  local ApplyLootProfileTransferConflictResolution = deps.ApplyLootProfileTransferConflictResolution
  local GetLootProfileSubchecksumManifest = deps.GetLootProfileSubchecksumManifest
  local FilterLootProfilePatchCapableSubdomains = deps.FilterLootProfilePatchCapableSubdomains
  local GetLootProfileSubdomainLabel = deps.GetLootProfileSubdomainLabel
  local GetLootProfileSubdomainParentDomain = deps.GetLootProfileSubdomainParentDomain
  local ResolveLootProfileDomainsForSubdomains = deps.ResolveLootProfileDomainsForSubdomains
  local TouchLootProfileDomain = deps.TouchLootProfileDomain
  local GetProfileSyncEstimate = deps.GetProfileSyncEstimate
  local GetProfileSyncTuning = deps.GetProfileSyncTuning
  local RunCommOutboundTransportValidation = deps.RunCommOutboundTransportValidation
  local ClearIncomingProfileSyncsForSession = deps.ClearIncomingProfileSyncsForSession
  local GetIncomingProfileSyncHealth = deps.GetIncomingProfileSyncHealth
  local RecordRepairHistory = deps.RecordRepairHistory
  local PushUndoSnapshot = deps.PushUndoSnapshot
  local PROFILE_BOOTSTRAP_DOMAINS = type(deps.PROFILE_BOOTSTRAP_DOMAINS) == "table" and deps.PROFILE_BOOTSTRAP_DOMAINS or { "settings", "permissions" }
  local PROFILE_BACKGROUND_SYNC_DOMAINS = type(deps.PROFILE_BACKGROUND_SYNC_DOMAINS) == "table" and deps.PROFILE_BACKGROUND_SYNC_DOMAINS or { "loot", "session" }

  local DEFAULT_PROFILE_MODE = "SIMULATION"
  local DEFAULT_SCENARIO = "FRESH"
  local DEFAULT_MEMBER_COUNT = 5
  local HIDDEN_PROFILE_PREFIX = "__LCSIM__"
  local DEFAULT_CLIENT_VERSION = "12.1.0 (Build 69299)"
  local DEFAULT_ADDON_VERSION = "1.0.0 [BETA]"
  local PROFILE_REVISION_DOMAINS = { "settings", "permissions", "loot", "session" }
  local PROFILE_REVISION_DOMAIN_LABELS = {
    settings = "Settings",
    permissions = "Permissions",
    loot = "Loot Data",
    session = "Session Data",
  }
  local DEV_HARNESS_HOST_FUN_AWARD_EVENT = "DEVSYNC_HOST_FUN_AWARD"
  local DEV_HARNESS_HOST_NOTE_CHARACTER = "SyntheticHost"
  local DEV_HARNESS_HOST_NOTE_ENTRY = "ledger-devsync-host-note"
  local DEV_HARNESS_HOST_SESSION_ID = "DEVSYNC_HOST_SESSION"
  local DEV_HARNESS_SETTING_KEY = "__devsyncHarnessSetting"
  local DEV_HARNESS_PERMISSION_KEY = "__devsyncHarnessPermission"
  local PSEUDO_CLASS_SPECS = {
    { className = "Warrior", classFile = "WARRIOR", specName = "Arms", specIcon = "132355" },
    { className = "Paladin", classFile = "PALADIN", specName = "Retribution", specIcon = "135873" },
    { className = "Hunter", classFile = "HUNTER", specName = "Marksmanship", specIcon = "236179" },
    { className = "Rogue", classFile = "ROGUE", specName = "Outlaw", specIcon = "236270" },
    { className = "Priest", classFile = "PRIEST", specName = "Shadow", specIcon = "136207" },
    { className = "Shaman", classFile = "SHAMAN", specName = "Enhancement", specIcon = "237581" },
    { className = "Mage", classFile = "MAGE", specName = "Fire", specIcon = "135810" },
    { className = "Warlock", classFile = "WARLOCK", specName = "Destruction", specIcon = "136186" },
    { className = "Monk", classFile = "MONK", specName = "Windwalker", specIcon = "608953" },
    { className = "Druid", classFile = "DRUID", specName = "Balance", specIcon = "136096" },
    { className = "Demon Hunter", classFile = "DEMONHUNTER", specName = "Havoc", specIcon = "1247264" },
    { className = "Death Knight", classFile = "DEATHKNIGHT", specName = "Unholy", specIcon = "135775" },
    { className = "Evoker", classFile = "EVOKER", specName = "Augmentation", specIcon = "5198700" },
  }

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

  local function copy(value, useLocalClone)
    if not useLocalClone and type(DeepCopy) == "function" then
      return DeepCopy(value)
    end
    if type(value) ~= "table" then
      return value
    end
    local clone = {}
    for key, entry in pairs(value) do
      clone[key] = copy(entry, true)
    end
    return clone
  end

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

  local function nowMsToken()
    local base = now()
    return tostring(base) .. "-" .. tostring(math.random(1000, 9999))
  end

  local function lowerKey(value)
    return string.lower(trim(value))
  end

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

  local function cloneDomainList(domains)
    local clone = {}
    for _, domain in ipairs(resolveDomains(domains)) do
      clone[#clone + 1] = domain
    end
    return clone
  end

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

  local function resolveProfileMode(value)
    local mode = string.upper(trim(value))
    if mode ~= "SIMULATION" and mode ~= "CURRENT" then
      mode = DEFAULT_PROFILE_MODE
    end
    return mode
  end

  local function resolveScenario(value)
    local scenario = string.upper(trim(value))
    if scenario ~= "FRESH" and scenario ~= "RETURNING" and scenario ~= "MIXED" then
      scenario = DEFAULT_SCENARIO
    end
    return scenario
  end

  local function resolveMemberCount(value)
    local count = math.floor((tonumber(value) or DEFAULT_MEMBER_COUNT) + 0.5)
    if count < 1 then
      count = DEFAULT_MEMBER_COUNT
    elseif count > 40 then
      count = 40
    end
    return count
  end

  local function ensureStore()
    local root = type(RootDB) == "function" and RootDB() or nil
    if type(root) ~= "table" then
      return {
        profileMode = DEFAULT_PROFILE_MODE,
        scenario = DEFAULT_SCENARIO,
        memberCount = DEFAULT_MEMBER_COUNT,
      }
    end
    root.ui = type(root.ui) == "table" and root.ui or {}
    root.ui.developerSyncHarness = type(root.ui.developerSyncHarness) == "table" and root.ui.developerSyncHarness or {}
    local store = root.ui.developerSyncHarness
    if trim(store.profileMode) == "" then
      store.profileMode = DEFAULT_PROFILE_MODE
    end
    if trim(store.scenario) == "" then
      store.scenario = DEFAULT_SCENARIO
    end
    if math.max(0, tonumber(store.memberCount) or 0) <= 0 then
      store.memberCount = DEFAULT_MEMBER_COUNT
    end
    store.syntheticSession = type(store.syntheticSession) == "table" and store.syntheticSession or nil
    return store
  end

  local function getRoot()
    return type(RootDB) == "function" and RootDB() or nil
  end

  local function resolveCurrentProfileName()
    local root = getRoot()
    if type(root) ~= "table" then
      return "Default"
    end
    local currentProfile = trim(root.currentProfile)
    if currentProfile ~= "" and type(root.profiles) == "table" and type(root.profiles[currentProfile]) == "table" then
      return currentProfile
    end
    if type(root.profiles) == "table" and type(root.profiles.Default) == "table" then
      return "Default"
    end
    for profileName, profile in pairs(root.profiles or {}) do
      if trim(profileName) ~= "" and type(profile) == "table" then
        return tostring(profileName)
      end
    end
    return "Default"
  end

  local function resolveProfileName(profileMode)
    profileMode = resolveProfileMode(profileMode)
    local root = getRoot()
    if profileMode == "SIMULATION" and type(root) == "table" and type(root.profiles) == "table" and type(root.profiles.Simulation) == "table" then
      return "Simulation", "SIMULATION", ""
    end
    local fallbackName = resolveCurrentProfileName()
    if profileMode == "SIMULATION" then
      return fallbackName, "CURRENT", "Simulation profile not found. Used the current profile instead."
    end
    return fallbackName, "CURRENT", ""
  end

  local function cloneEstimate(estimate)
    estimate = type(estimate) == "table" and estimate or {}
    return {
      bytes = math.max(0, tonumber(estimate.bytes) or 0),
      chunkSize = math.max(1, tonumber(estimate.chunkSize) or 1),
      chunks = math.max(0, tonumber(estimate.chunks) or 0),
      messages = math.max(0, tonumber(estimate.messages) or 0),
      intervalSeconds = math.max(0, tonumber(estimate.intervalSeconds) or 0),
      seconds = math.max(0, tonumber(estimate.seconds) or 0),
    }
  end

  local function buildEstimate(byteCount)
    local bytes = math.max(0, tonumber(byteCount) or 0)
    if bytes <= 0 then
      local tuning = type(GetProfileSyncTuning) == "function" and GetProfileSyncTuning() or {}
      return {
        bytes = 0,
        chunkSize = math.max(1, tonumber(tuning.chunkSize) or 120),
        chunks = 0,
        messages = 0,
        intervalSeconds = math.max(0, tonumber(tuning.intervalSeconds) or 0.12),
        seconds = 0,
      }
    end
    if type(GetProfileSyncEstimate) == "function" then
      return cloneEstimate(GetProfileSyncEstimate(bytes))
    end
    local tuning = type(GetProfileSyncTuning) == "function" and GetProfileSyncTuning() or {}
    local chunkSize = math.max(1, tonumber(tuning.chunkSize) or 120)
    local intervalSeconds = math.max(0, tonumber(tuning.intervalSeconds) or 0.12)
    local chunks = math.max(1, math.ceil(bytes / chunkSize))
    local messages = chunks + 2
    return {
      bytes = bytes,
      chunkSize = chunkSize,
      chunks = chunks,
      messages = messages,
      intervalSeconds = intervalSeconds,
      seconds = messages * intervalSeconds,
    }
  end

  local function getProfileSnapshotText(profileName, domains)
    local resolvedProfileName = trim(profileName)
    if resolvedProfileName == "" then
      return ""
    end
    if type(domains) == "table" and #domains > 0 and type(ExportLootProfileDomainSnapshot) == "function" then
      return tostring(ExportLootProfileDomainSnapshot(resolvedProfileName, domains) or "")
    end
    if type(ExportLootProfileSnapshot) == "function" then
      return tostring(ExportLootProfileSnapshot(resolvedProfileName) or "")
    end
    return ""
  end

  local function buildScenarioCounts(scenario, memberCount)
    scenario = resolveScenario(scenario)
    memberCount = resolveMemberCount(memberCount)
    local freshCount = memberCount
    if scenario == "RETURNING" then
      freshCount = 0
    elseif scenario == "MIXED" then
      freshCount = math.max(1, math.floor((memberCount * 0.25) + 0.5))
    end
    if freshCount > memberCount then
      freshCount = memberCount
    end
    local alignedCount = math.max(0, memberCount - freshCount)
    return freshCount, alignedCount
  end

  local function buildScenarioLabel(scenario)
    scenario = resolveScenario(scenario)
    if scenario == "RETURNING" then
      return "Returning / mostly aligned"
    end
    if scenario == "MIXED" then
      return "Mixed drift raid"
    end
    return "Fresh joiners"
  end

  local function buildMemberName(index)
    return string.format("SimRaider%02d-PreviewRealm", math.max(1, tonumber(index) or 1))
  end

  local function buildMemberLabel(index)
    return string.format("SimRaider%02d", math.max(1, tonumber(index) or 1))
  end

  local function buildMemberTimeline(memberCount, scenario, bootstrapEstimate, backgroundEstimate, controlSeconds)
    memberCount = resolveMemberCount(memberCount)
    scenario = resolveScenario(scenario)
    local freshCount, alignedCount = buildScenarioCounts(scenario, memberCount)
    local members = {}
    local bootstrapCursor = 0
    local bootstrapPhaseSeconds = freshCount * math.max(0, tonumber(bootstrapEstimate.seconds) or 0)
    local alignedSeen = 0
    local freshSeen = 0
    for index = 1, memberCount do
      local isFresh = index <= freshCount
      local entry = {
        name = buildMemberName(index),
      }
      if isFresh then
        freshSeen = freshSeen + 1
        bootstrapCursor = bootstrapCursor + math.max(0, tonumber(bootstrapEstimate.seconds) or 0)
        entry.mode = "fresh"
        entry.readyAt = bootstrapCursor
        entry.fullAt = bootstrapPhaseSeconds + (freshSeen * math.max(0, tonumber(backgroundEstimate.seconds) or 0))
        entry.status = "Bootstrap + background sync"
      else
        alignedSeen = alignedSeen + 1
        entry.mode = alignedCount > 0 and "aligned" or "fresh"
        entry.readyAt = alignedSeen * controlSeconds
        entry.fullAt = entry.readyAt
        entry.status = "Checksum-only / no snapshot"
      end
      members[#members + 1] = entry
    end
    return members
  end

  local function buildHarnessReport(opts)
    opts = type(opts) == "table" and opts or {}
    local requestedProfileMode = resolveProfileMode(opts.profileMode or ensureStore().profileMode)
    local scenario = resolveScenario(opts.scenario or ensureStore().scenario)
    local memberCount = resolveMemberCount(opts.memberCount or ensureStore().memberCount)
    local profileName, resolvedProfileMode, fallbackMessage = resolveProfileName(requestedProfileMode)
    local profile = type(GetLootProfile) == "function" and select(1, GetLootProfile(profileName)) or nil
    if type(profile) ~= "table" then
      return nil, "Profile not found for sync harness."
    end

    local tuning = type(GetProfileSyncTuning) == "function" and GetProfileSyncTuning() or {}
    local bootstrapText = getProfileSnapshotText(profileName, PROFILE_BOOTSTRAP_DOMAINS)
    local backgroundText = getProfileSnapshotText(profileName, PROFILE_BACKGROUND_SYNC_DOMAINS)
    local fullText = getProfileSnapshotText(profileName)
    local bootstrapEstimate = buildEstimate(#bootstrapText)
    local backgroundEstimate = buildEstimate(#backgroundText)
    local fullEstimate = buildEstimate(#fullText)
    local freshCount, alignedCount = buildScenarioCounts(scenario, memberCount)
    local controlSeconds = math.max(0.18, 3 * math.max(0, tonumber(tuning.intervalSeconds) or 0.12))
    local members = buildMemberTimeline(memberCount, scenario, bootstrapEstimate, backgroundEstimate, controlSeconds)
    local lastReadyAt = 0
    local lastFullAt = 0
    local totalReadyAt = 0
    local totalFullAt = 0
    for _, member in ipairs(members) do
      lastReadyAt = math.max(lastReadyAt, tonumber(member.readyAt) or 0)
      lastFullAt = math.max(lastFullAt, tonumber(member.fullAt) or 0)
      totalReadyAt = totalReadyAt + (tonumber(member.readyAt) or 0)
      totalFullAt = totalFullAt + (tonumber(member.fullAt) or 0)
    end

    local report = {
      generatedAt = now(),
      profileName = profileName,
      profileMode = resolvedProfileMode,
      requestedProfileMode = requestedProfileMode,
      fallbackMessage = fallbackMessage,
      scenario = scenario,
      scenarioLabel = buildScenarioLabel(scenario),
      memberCount = memberCount,
      freshMemberCount = freshCount,
      alignedMemberCount = alignedCount,
      tuning = {
        chunkSize = math.max(1, tonumber(tuning.chunkSize) or 120),
        intervalSeconds = math.max(0, tonumber(tuning.intervalSeconds) or 0.12),
        safePayloadLimit = math.max(0, tonumber(tuning.safePayloadLimit) or 0),
      },
      domains = {
        bootstrap = cloneDomainList(PROFILE_BOOTSTRAP_DOMAINS),
        background = cloneDomainList(PROFILE_BACKGROUND_SYNC_DOMAINS),
      },
      estimates = {
        bootstrap = bootstrapEstimate,
        background = backgroundEstimate,
        full = fullEstimate,
      },
      totals = {
        snapshotBytes = (freshCount * ((tonumber(bootstrapEstimate.bytes) or 0) + (tonumber(backgroundEstimate.bytes) or 0))),
        snapshotMessages = (freshCount * ((tonumber(bootstrapEstimate.messages) or 0) + (tonumber(backgroundEstimate.messages) or 0))),
        rollReadyLastAt = lastReadyAt,
        fullSyncLastAt = lastFullAt,
        rollReadyAverageAt = memberCount > 0 and (totalReadyAt / memberCount) or 0,
        fullSyncAverageAt = memberCount > 0 and (totalFullAt / memberCount) or 0,
        controlOnlySecondsPerAlignedMember = controlSeconds,
      },
      notes = {
        "This developer tool now also creates a synthetic session overlay in Current Session and Sync Management.",
        "The synthetic members use hidden scratch profiles, so pull/push/preview rehearsal does not touch your real source profile.",
      },
      faultScenarios = {
        {
          title = "Duplicate member update",
          action = "Repeat a synthetic pull or push for the same member before reopening Sync Management.",
          expected = "One member row remains and the latest revision state wins without a duplicate repair entry.",
        },
        {
          title = "Late acknowledgement",
          action = "In a real two-client test, delay the receiver acknowledgement beyond the host timeout after a targeted snapshot.",
          expected = "The host revalidates the changed domains first and accepts a late acknowledgement without queuing duplicate repair.",
        },
        {
          title = "Combat-deferred UI",
          action = "Open Current Session, enter combat, and trigger a synthetic repair or member-state change.",
          expected = "Communication state is retained and the visible session UI refreshes once combat ends.",
        },
        {
          title = "Session stop during recovery",
          action = "Stop the synthetic session while a preview or repair workflow is open.",
          expected = "Pending UI review state is cleared and no repair is applied after the session is stopped.",
        },
        {
          title = "Inbound admission limits",
          action = "In a controlled two-client test, repeat precise-state and snapshot requests faster than the configured window allows.",
          expected = "The first valid requests are coalesced; excess requests are rejected, counted in Sync Management, and do not grow pending work.",
        },
        {
          title = "Stale acknowledgement",
          action = "Send an acknowledgement for an older transfer generation after a newer targeted transfer has been queued.",
          expected = "The stale ACK is rejected and cannot mark the newer transfer or revision state as complete.",
        },
        {
          title = "Stale precise response",
          action = "Request the same member subcheck or patch-manifest scope twice, then delay the first response until after the second request.",
          expected = "The response carrying the older request token is ignored; Sync Management records the stale drop and retains the latest scope state.",
        },
        {
          title = "Tokenless precise peer",
          action = "Use a second client that omits the optional request-token field in a subcheck or patch-manifest response.",
          expected = "The response remains accepted for mixed-version compatibility while tokened newer responses still reject stale replacements.",
        },
        {
          title = "Delayed multipart precise response",
          action = "Delay the final chunk of a multipart subcheck or patch-manifest response until a newer request has been sent.",
          expected = "The delayed multipart response is discarded by its older request token and cannot replace the newest manifest state.",
        },
        {
          title = "Stale delta response",
          action = "After the host sends a newer delta, deliver an ACK or NACK for an earlier change ID or sequence.",
          expected = "The host rejects the stale response; it neither marks the new delta acknowledged nor queues recovery work.",
        },
        {
          title = "Inbound field-count limit",
          action = "Send a controlled LidCouncil message with more than the supported protocol field count.",
          expected = "The common receiver gate rejects it before a feature handler runs and increments inbound rejection telemetry.",
        },
      },
      members = members,
    }

    if scenario == "FRESH" then
      report.notes[#report.notes + 1] = "Fresh joiners start with no local shared profile and become roll-ready only after the host bootstrap is pushed."
    elseif scenario == "RETURNING" then
      report.notes[#report.notes + 1] = "Returning members are generated as mostly aligned with a smaller set of host-newer and member-newer drift cases."
    elseif scenario == "MIXED" then
      report.notes[#report.notes + 1] = "Mixed drift creates fresh joiners plus host-newer, member-newer, conflict, and aligned members for manual repair rehearsal."
    end

    return report
  end

  local function isHiddenSyntheticProfile(name)
    return trim(name):match("^" .. HIDDEN_PROFILE_PREFIX) ~= nil
  end

  local function clearHiddenSyntheticProfiles()
    local root = getRoot()
    if type(root) ~= "table" or type(root.profiles) ~= "table" then
      return
    end
    local removals = {}
    for profileName in pairs(root.profiles) do
      if isHiddenSyntheticProfile(profileName) then
        removals[#removals + 1] = profileName
      end
    end
    for _, profileName in ipairs(removals) do
      root.profiles[profileName] = nil
    end
  end

  local function clearSyntheticSessionState(store)
    store = store or ensureStore()
    clearHiddenSyntheticProfiles()
    store.syntheticSession = nil
  end

  local function invalidateSyntheticSessionForProfileSwitch(store, synthetic)
    store = store or ensureStore()
    synthetic = type(synthetic) == "table" and synthetic or nil
    if not synthetic then
      return false
    end
    local sourceProfileName = trim(synthetic.sourceProfileName)
    local currentProfileName = trim(resolveCurrentProfileName())
    if sourceProfileName == "" or currentProfileName == "" then
      return false
    end
    if lowerKey(sourceProfileName) == lowerKey(currentProfileName) then
      return false
    end
    clearSyntheticSessionState(store)
    if type(Print) == "function" then
      Print("Developer sync harness cleared because the active profile changed.")
    end
    return true
  end

  local function buildHiddenProfileName(runId, kind, index)
    return string.format("%s%s-%s-%02d", HIDDEN_PROFILE_PREFIX, tostring(runId), tostring(kind), math.max(0, tonumber(index) or 0))
  end

  local function getProfileTable(profileName)
    return type(GetLootProfile) == "function" and select(1, GetLootProfile(profileName)) or nil
  end

  local function cloneProfile(sourceProfileName, targetProfileName)
    if trim(sourceProfileName) == "" or trim(targetProfileName) == "" then
      return false, "Source and target profile names are required."
    end
    if type(ExportLootProfileSnapshot) ~= "function" or type(ImportLootProfileSnapshot) ~= "function" then
      return false, "Profile clone APIs unavailable."
    end
    local snapshot = ExportLootProfileSnapshot(sourceProfileName)
    if type(snapshot) ~= "string" or snapshot == "" then
      return false, "Could not export the source profile."
    end
    local ok, err = ImportLootProfileSnapshot(targetProfileName, snapshot)
    if not ok then
      return false, err or "Could not import the synthetic profile copy."
    end
    return true
  end

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

    local function buildSessionArchiveManifestSignature(manifest)
      local parts = {}
      for subdomain, checksum in pairs(type(manifest) == "table" and type(manifest.checksums) == "table" and manifest.checksums or {}) do
        if string.sub(string.lower(trim(subdomain)), 1, 4) == "ssr:" then
          parts[#parts + 1] = tostring(subdomain) .. "=" .. tostring(checksum or "")
        end
      end
      table.sort(parts)
      return table.concat(parts, "\31")
    end

    local function buildFunAwardsArchiveManifestSignature(manifest)
      local parts = {}
      for subdomain, checksum in pairs(type(manifest) == "table" and type(manifest.checksums) == "table" and manifest.checksums or {}) do
        local prefix = string.sub(string.lower(trim(subdomain)), 1, 4)
        if prefix == "lre:" or prefix == "lve:" then
          parts[#parts + 1] = tostring(subdomain) .. "=" .. tostring(checksum or "")
        end
      end
      table.sort(parts)
      return table.concat(parts, "\31")
    end

    local function findAwardRankingRow(report, rankingKey, characterKey)
      local ranking = type(report) == "table"
        and type(report.rankings) == "table"
        and type(report.rankings[rankingKey]) == "table"
        and report.rankings[rankingKey].rows or {}
      for _, row in ipairs(type(ranking) == "table" and ranking or {}) do
        if trim(type(row) == "table" and row.character or "") == characterKey then
          return row
        end
      end
      return nil
    end

    local root = getRoot()
    local sourceProfileName = resolveCurrentProfileName()
    local currentProfile = type(root) == "table" and type(root.profiles) == "table" and root.profiles[sourceProfileName] or nil
    local sourceName = HIDDEN_PROFILE_PREFIX .. "W3-ARCHIVE-HOST"
    local targetName = HIDDEN_PROFILE_PREFIX .. "W3-ARCHIVE-MEMBER"
    local originalSessionCount = type(currentProfile) == "table" and #(type(currentProfile.sessions) == "table" and currentProfile.sessions or {}) or 0
    local function cleanup()
      if type(root) == "table" and type(root.profiles) == "table" then
        root.profiles[sourceName] = nil
        root.profiles[targetName] = nil
      end
    end

    cleanup()
    local executed, executionError = pcall(function()
      local apisReady = type(currentProfile) == "table"
        and type(ExportLootProfileSubdomainSnapshot) == "function"
        and type(ImportLootProfileSubdomainSnapshot) == "function"
        and type(GetLootProfileSubchecksumManifest) == "function"
        and type(TouchLootProfileDomain) == "function"
      addCheck("70-session archive validation APIs available", true, apisReady)
      if not apisReady then
        return
      end

      root.profiles[sourceName] = copy(currentProfile)
      root.profiles[targetName] = copy(currentProfile)
      local sourceProfile = root.profiles[sourceName]
      local targetProfile = root.profiles[targetName]
      local derivedFixture = {
        character = "ValidationMeta-Realm",
        eventId = "W3-COMPACT-FIRST",
        metaLeaf = "lmr:ValidationMeta-Realm",
        eventLeaf = "lre:W3-COMPACT-FIRST",
      }
      sourceProfile.lootLedgerMeta = type(sourceProfile.lootLedgerMeta) == "table" and sourceProfile.lootLedgerMeta or {}
      sourceProfile.lootLedgerMeta[derivedFixture.character] = {
        penaltyPoints = 0,
        classFile = "MAGE",
        className = "Mage",
        specName = "Fire",
        specID = 63,
        specIcon = "135810",
        note = "",
        mainAltRole = "MAIN",
        mainCharacter = "",
      }
      sourceProfile.lootRollStats = type(sourceProfile.lootRollStats) == "table" and sourceProfile.lootRollStats or {}
      sourceProfile.lootRollStats.events = type(sourceProfile.lootRollStats.events) == "table" and sourceProfile.lootRollStats.events or {}
      sourceProfile.lootRollStats.events[derivedFixture.eventId] = {
        c = derivedFixture.character,
        o = "bis",
        l = "BiS",
        r = 97,
        f = 1,
        selectedAt = 200000,
      }
      targetProfile.lootLedgerMeta = type(targetProfile.lootLedgerMeta) == "table" and targetProfile.lootLedgerMeta or {}
      targetProfile.lootLedgerMeta[derivedFixture.character] = nil
      targetProfile.lootRollStats = type(targetProfile.lootRollStats) == "table" and targetProfile.lootRollStats or {}
      targetProfile.lootRollStats.events = type(targetProfile.lootRollStats.events) == "table" and targetProfile.lootRollStats.events or {}
      targetProfile.lootRollStats.events[derivedFixture.eventId] = nil
      TouchLootProfileDomain(sourceProfile, "loot")
      TouchLootProfileDomain(targetProfile, "loot")

      sourceProfile.sessions = {}
      for index = 1, 70 do
        sourceProfile.sessions[index] = {
          id = string.format("W3-SESSION-%03d", index),
          profileName = "Workflow 3 Archive Validation",
          host = "ValidationHost-Realm",
          status = "FINISHED",
          startedAt = 100000 + (index * 3600),
          endedAt = 100300 + (index * 3600),
          members = {
            ["ValidationHost-Realm"] = {
              name = "ValidationHost-Realm",
              status = "JOINED",
              localAutoPassEnabled = false,
            },
            [string.format("Member%02d-Realm", ((index - 1) % 20) + 1)] = {
              name = string.format("Member%02d-Realm", ((index - 1) % 20) + 1),
              status = "JOINED",
              localAutoPassEnabled = true,
            },
          },
          rollOptions = {
            { optionKey = "bis", label = "BiS" },
            { optionKey = "pass", label = "Pass" },
          },
        }
      end
      targetProfile.sessions = {
        copy(sourceProfile.sessions[1]),
        {
          id = "W3-MEMBER-ONLY",
          profileName = "Member-only stale session",
          host = "Member01-Realm",
          status = "FINISHED",
          startedAt = 1,
          endedAt = 2,
          members = {},
          rollOptions = {},
        },
      }
      targetProfile.sessions[1].endedAt = 1
      TouchLootProfileDomain(sourceProfile, "session")
      TouchLootProfileDomain(targetProfile, "session")

      local sourceManifest = GetLootProfileSubchecksumManifest(sourceName, { "session" })
      local targetManifestBefore = GetLootProfileSubchecksumManifest(targetName, { "session" })
      local sourceArchiveSignature = buildSessionArchiveManifestSignature(sourceManifest)
      local targetArchiveSignatureBefore = buildSessionArchiveManifestSignature(targetManifestBefore)
      local sessionLeafCount = 0
      for subdomain in pairs(type(sourceManifest) == "table" and type(sourceManifest.checksums) == "table" and sourceManifest.checksums or {}) do
        if string.sub(string.lower(trim(subdomain)), 1, 4) == "ssr:" then
          sessionLeafCount = sessionLeafCount + 1
        end
      end
      addCheck("70-session source exposes one leaf per record", 70, sessionLeafCount)
      addCheck("divergent member archive differs before repair", true,
        sourceArchiveSignature ~= ""
          and targetArchiveSignatureBefore ~= ""
          and sourceArchiveSignature ~= targetArchiveSignatureBefore)

      local snapshot = ExportLootProfileSubdomainSnapshot(sourceName, nil, {
        authoritativeArchiveScope = "SESSION_HISTORY",
      })
      addCheck("70-session authoritative snapshot exports", true, type(snapshot) == "string" and snapshot ~= "")
      addCheck("70-session snapshot requires chunk transport", true, type(snapshot) == "string" and #snapshot > 240)
      if type(snapshot) ~= "string" or snapshot == "" then
        return
      end

      local profileId = trim(type(sourceProfile.meta) == "table" and sourceProfile.meta.profileId or "")
      local imported = ImportLootProfileSubdomainSnapshot(targetName, snapshot, {
        expectedProfileId = profileId,
        sourceCharacter = "ValidationHost-Realm",
        allowAuthoritativeArchiveReplace = true,
      })
      addCheck("authoritative 70-session replacement is accepted", true, imported == true)
      if imported ~= true then
        return
      end

      local targetById = {}
      for _, session in ipairs(type(targetProfile.sessions) == "table" and targetProfile.sessions or {}) do
        targetById[trim(type(session) == "table" and session.id or "")] = session
      end
      local exactRecords = true
      for _, sourceSession in ipairs(sourceProfile.sessions) do
        local targetSession = targetById[trim(sourceSession.id)]
        if type(targetSession) ~= "table"
          or trim(targetSession.status) ~= trim(sourceSession.status)
          or tonumber(targetSession.startedAt) ~= tonumber(sourceSession.startedAt)
          or tonumber(targetSession.endedAt) ~= tonumber(sourceSession.endedAt)
        then
          exactRecords = false
          break
        end
      end
      local targetManifestAfter = GetLootProfileSubchecksumManifest(targetName, { "session" })
      local targetArchiveSignatureAfter = buildSessionArchiveManifestSignature(targetManifestAfter)
      addCheck("member archive contains exactly 70 host records", 70, #(targetProfile.sessions or {}))
      addCheck("member-only stale session is removed", nil, targetById["W3-MEMBER-ONLY"])
      addCheck("all 70 session records retain authoritative values", true, exactRecords)
      addCheck("70-session archive checksum converges", sourceArchiveSignature, targetArchiveSignatureAfter)

      local sourceLootManifest = GetLootProfileSubchecksumManifest(sourceName, { "loot" })
      local sourceLootChecksums = type(sourceLootManifest) == "table" and type(sourceLootManifest.checksums) == "table"
        and sourceLootManifest.checksums or {}
      addCheck("class/spec-only Loot List metadata exposes a P3 leaf", true,
        trim(sourceLootChecksums[derivedFixture.metaLeaf]) ~= "")
      addCheck("compact first-option award event exposes a P3 leaf", true,
        trim(sourceLootChecksums[derivedFixture.eventLeaf]) ~= "")

      local derivedSnapshot = ExportLootProfileSubdomainSnapshot(sourceName, {
        derivedFixture.metaLeaf,
        derivedFixture.eventLeaf,
      })
      addCheck("derived P3 metadata snapshot exports", true,
        type(derivedSnapshot) == "string" and derivedSnapshot ~= "")
      local derivedImported = type(derivedSnapshot) == "string" and derivedSnapshot ~= ""
        and ImportLootProfileSubdomainSnapshot(targetName, derivedSnapshot, {
          expectedProfileId = profileId,
          sourceCharacter = "ValidationHost-Realm",
        })
        or false
      addCheck("derived P3 metadata snapshot imports", true, derivedImported == true)

      local targetMeta = type(targetProfile.lootLedgerMeta) == "table"
        and targetProfile.lootLedgerMeta[derivedFixture.character] or nil
      addCheck("Loot List class/spec identity converges", "MAGE/Mage/Fire/63/135810",
        table.concat({
          trim(type(targetMeta) == "table" and targetMeta.classFile or ""),
          trim(type(targetMeta) == "table" and targetMeta.className or ""),
          trim(type(targetMeta) == "table" and targetMeta.specName or ""),
          tostring(type(targetMeta) == "table" and tonumber(targetMeta.specID) or ""),
          trim(type(targetMeta) == "table" and targetMeta.specIcon or ""),
        }, "/"))
      local targetEvent = type(targetProfile.lootRollStats) == "table"
        and type(targetProfile.lootRollStats.events) == "table"
        and targetProfile.lootRollStats.events[derivedFixture.eventId] or nil
      addCheck("compact Everything Is BiS marker survives P3 apply", "ValidationMeta-Realm/bis/1",
        table.concat({
          trim(type(targetEvent) == "table" and (targetEvent.character or targetEvent.c) or ""),
          trim(type(targetEvent) == "table" and (targetEvent.optionKey or targetEvent.o) or ""),
          tostring(type(targetEvent) == "table" and (targetEvent.isFirstOption or targetEvent.f) or ""),
        }, "/"))
      local getLootRollAwards = type(API) == "table" and API.LIDCOUNCIL_GetLootRollAwards or nil
      addCheck("Fun Awards reader available for derived P3 validation", true, type(getLootRollAwards) == "function")
      local derivedAwardMetric = ""
      if type(getLootRollAwards) == "function" then
        local awardReport = getLootRollAwards(targetName)
        local ranking = type(awardReport) == "table"
          and type(awardReport.rankings) == "table"
          and type(awardReport.rankings.bis_everything) == "table"
          and awardReport.rankings.bis_everything.rows or {}
        for _, row in ipairs(type(ranking) == "table" and ranking or {}) do
          if trim(type(row) == "table" and row.character or "") == derivedFixture.character then
            derivedAwardMetric = trim(row.metric)
            break
          end
        end
      end
      addCheck("Everything Is BiS ranking rebuilds from repaired compact event", "1", derivedAwardMetric)
      local targetLootManifest = GetLootProfileSubchecksumManifest(targetName, { "loot" })
      local targetLootChecksums = type(targetLootManifest) == "table" and type(targetLootManifest.checksums) == "table"
        and targetLootManifest.checksums or {}
      addCheck("derived P3 leaf checksums converge",
        tostring(sourceLootChecksums[derivedFixture.metaLeaf]) .. "/" .. tostring(sourceLootChecksums[derivedFixture.eventLeaf]),
        tostring(targetLootChecksums[derivedFixture.metaLeaf]) .. "/" .. tostring(targetLootChecksums[derivedFixture.eventLeaf]))

      sourceProfile.lootLedger = {}
      targetProfile.lootLedger = {}
      sourceProfile.lootLedgerMeta = {}
      targetProfile.lootLedgerMeta = {}
      sourceProfile.lootRollStats = {
        schemaVersion = 4,
        events = {
          ["W4-LIVE-1:ITEM-1:Alpha-Realm"] = {
            itemKey = "ITEM-1", character = "Alpha-Realm", optionKey = "bis", optionLabel = "BiS",
            pointBehavior = "BIS", popupSection = "NEED", rollValue = 20, isFirstOption = true,
          },
          ["W4-LIVE-1:ITEM-2:Alpha-Realm"] = {
            itemKey = "ITEM-2", character = "Alpha-Realm", optionKey = "upgrade", optionLabel = "Upgrade",
            pointBehavior = "ITEMLEVEL", popupSection = "NEED", rollValue = 40, isFirstOption = false,
          },
          ["W4-LIVE-1:ITEM-3:Beta-Realm"] = {
            itemKey = "ITEM-3", character = "Beta-Realm", optionKey = "bis", optionLabel = "BiS",
            pointBehavior = "BIS", popupSection = "NEED", rollValue = 90, isFirstOption = true,
          },
          ["W4-LIVE-1:ITEM-4:Beta-Realm"] = {
            itemKey = "ITEM-4", character = "Beta-Realm", optionKey = "bis", optionLabel = "BiS",
            pointBehavior = "BIS", popupSection = "NEED", rollValue = 70, isFirstOption = true,
          },
          ["W4-SIM:TESTSIM-ROLL:Gamma-Realm"] = {
            itemKey = "TESTSIM-ROLL", character = "Gamma-Realm", optionKey = "bis", optionLabel = "BiS",
            pointBehavior = "BIS", popupSection = "NEED", rollValue = 100, isFirstOption = true,
            isSimulation = true,
          },
        },
        voteEvents = {
          ["W4-LIVE-1:ITEM-1:Alpha-Realm"] = {
            itemKey = "ITEM-1", voter = "Alpha-Realm", target = "Beta-Realm",
          },
          ["W4-SIM:TESTSIM-VOTE:Beta-Realm"] = {
            itemKey = "TESTSIM-VOTE", voter = "Beta-Realm", target = "Alpha-Realm", isSimulation = true,
          },
        },
      }
      targetProfile.lootRollStats = {
        schemaVersion = 4,
        events = {
          ["W4-LIVE-1:ITEM-1:Alpha-Realm"] = {
            itemKey = "ITEM-1", character = "Alpha-Realm", optionKey = "bis", optionLabel = "BiS",
            pointBehavior = "BIS", popupSection = "NEED", rollValue = 99, isFirstOption = true,
          },
          ["W4-MEMBER-ONLY:STALE:Stale-Realm"] = {
            itemKey = "STALE", character = "Stale-Realm", optionKey = "bis", optionLabel = "BiS",
            pointBehavior = "BIS", popupSection = "NEED", rollValue = 100, isFirstOption = true,
          },
        },
        voteEvents = {
          ["W4-MEMBER-ONLY:STALE:Stale-Realm"] = {
            itemKey = "STALE", voter = "Stale-Realm", target = "Alpha-Realm",
          },
        },
      }
      TouchLootProfileDomain(sourceProfile, "loot")
      TouchLootProfileDomain(targetProfile, "loot")

      local sourceAwardsManifest = GetLootProfileSubchecksumManifest(sourceName, { "loot" })
      local targetAwardsManifestBefore = GetLootProfileSubchecksumManifest(targetName, { "loot" })
      local sourceAwardsSignature = buildFunAwardsArchiveManifestSignature(sourceAwardsManifest)
      addCheck("divergent Fun Awards event set differs before repair", true,
        sourceAwardsSignature ~= ""
          and sourceAwardsSignature ~= buildFunAwardsArchiveManifestSignature(targetAwardsManifestBefore))

      local awardsSnapshot = ExportLootProfileSubdomainSnapshot(sourceName, nil, {
        authoritativeArchiveScope = "FUN_AWARDS",
      })
      addCheck("authoritative Fun Awards snapshot exports", true,
        type(awardsSnapshot) == "string" and awardsSnapshot ~= "")
      local awardsImported = type(awardsSnapshot) == "string" and awardsSnapshot ~= ""
        and ImportLootProfileSubdomainSnapshot(targetName, awardsSnapshot, {
          expectedProfileId = profileId,
          sourceCharacter = "ValidationHost-Realm",
          allowAuthoritativeArchiveReplace = true,
        })
        or false
      addCheck("authoritative Fun Awards replacement imports", true, awardsImported == true)

      local targetStats = type(targetProfile.lootRollStats) == "table" and targetProfile.lootRollStats or {}
      local targetEvents = type(targetStats.events) == "table" and targetStats.events or {}
      local targetVoteEvents = type(targetStats.voteEvents) == "table" and targetStats.voteEvents or {}
      local targetEventCount = 0
      local targetVoteCount = 0
      for _ in pairs(targetEvents) do targetEventCount = targetEventCount + 1 end
      for _ in pairs(targetVoteEvents) do targetVoteCount = targetVoteCount + 1 end
      addCheck("member contains every canonical roll event", 5, targetEventCount)
      addCheck("member contains every canonical vote event", 2, targetVoteCount)
      addCheck("member-only stale roll event is removed", nil, targetEvents["W4-MEMBER-ONLY:STALE:Stale-Realm"])
      addCheck("member-only stale vote event is removed", nil, targetVoteEvents["W4-MEMBER-ONLY:STALE:Stale-Realm"])

      local targetAwardsManifestAfter = GetLootProfileSubchecksumManifest(targetName, { "loot" })
      addCheck("Fun Awards event manifest converges exactly", sourceAwardsSignature,
        buildFunAwardsArchiveManifestSignature(targetAwardsManifestAfter))

      local awardsReport = type(getLootRollAwards) == "function" and getLootRollAwards(targetName) or nil
      local luckiestRow = findAwardRankingRow(awardsReport, "luckiest", "Beta-Realm")
      local worstRow = findAwardRankingRow(awardsReport, "worst", "Alpha-Realm")
      local bisRow = findAwardRankingRow(awardsReport, "bis_everything", "Beta-Realm")
      local forgottenRow = findAwardRankingRow(awardsReport, "forgotten", "Alpha-Realm")
      local realVoteRow = findAwardRankingRow(awardsReport, "boss_voter", "Alpha-Realm")
      local simulationVoteRow = findAwardRankingRow(awardsReport, "boss_voter", "Beta-Realm")
      local simulationRollRow = findAwardRankingRow(awardsReport, "luckiest", "Gamma-Realm")
      addCheck("Luckiest average rebuilds from all repaired events", "80.0",
        trim(type(luckiestRow) == "table" and luckiestRow.metric or ""))
      addCheck("Worst average rebuilds from all repaired events", "30.0",
        trim(type(worstRow) == "table" and worstRow.metric or ""))
      addCheck("Everything Is BiS count rebuilds from repaired events", "2",
        trim(type(bisRow) == "table" and bisRow.metric or ""))
      addCheck("Forgotten need count rebuilds from repaired events", "2",
        trim(type(forgottenRow) == "table" and forgottenRow.metric or ""))
      addCheck("real council vote remains in repaired awards", "1",
        trim(type(realVoteRow) == "table" and realVoteRow.metric or ""))
      addCheck("simulation council vote remains excluded after repair", nil, simulationVoteRow)
      addCheck("simulation roll remains excluded after repair", nil, simulationRollRow)

      sourceProfile.lootRollStats = {
        schemaVersion = 4,
        events = {},
        voteEvents = {},
      }
      TouchLootProfileDomain(sourceProfile, "loot")
      local emptyAwardsSnapshot = ExportLootProfileSubdomainSnapshot(sourceName, nil, {
        authoritativeArchiveScope = "FUN_AWARDS",
      })
      local emptyAwardsPreview = type(emptyAwardsSnapshot) == "string" and emptyAwardsSnapshot ~= ""
        and PreviewLootProfileSubdomainSnapshot(emptyAwardsSnapshot)
        or nil
      addCheck("empty authoritative Fun Awards snapshot preserves its scope", "FUN_AWARDS",
        string.upper(trim(type(emptyAwardsPreview) == "table" and emptyAwardsPreview.authoritativeArchiveScope or "")))
      local emptyAwardsImported = type(emptyAwardsSnapshot) == "string" and emptyAwardsSnapshot ~= ""
        and ImportLootProfileSubdomainSnapshot(targetName, emptyAwardsSnapshot, {
          expectedProfileId = profileId,
          sourceCharacter = "ValidationHost-Realm",
          allowAuthoritativeArchiveReplace = true,
        })
        or false
      addCheck("empty authoritative Fun Awards replacement imports", true, emptyAwardsImported == true)
      local emptiedStats = type(targetProfile.lootRollStats) == "table" and targetProfile.lootRollStats or {}
      local emptiedEventCount = 0
      for _ in pairs(type(emptiedStats.events) == "table" and emptiedStats.events or {}) do
        emptiedEventCount = emptiedEventCount + 1
      end
      for _ in pairs(type(emptiedStats.voteEvents) == "table" and emptiedStats.voteEvents or {}) do
        emptiedEventCount = emptiedEventCount + 1
      end
      addCheck("empty authoritative Fun Awards replacement removes stale events", 0, emptiedEventCount)
    end)

    cleanup()
    if not executed then
      addCheck("70-session archive validation executes", true, false)
    end
    local currentSessionCountAfter = type(currentProfile) == "table"
      and #(type(currentProfile.sessions) == "table" and currentProfile.sessions or {}) or 0
    addCheck("70-session validation leaves the active profile untouched", originalSessionCount, currentSessionCountAfter)
    addCheck("70-session validation removes temporary profiles", true,
      type(root) ~= "table" or type(root.profiles) ~= "table"
        or (root.profiles[sourceName] == nil and root.profiles[targetName] == nil))

    return passedCount == #checks, {
      suite = "archive_70_session_convergence",
      version = 4,
      total = #checks,
      passed = passedCount,
      failed = #checks - passedCount,
      error = executed and "" or tostring(executionError or "validation_error"),
      checks = checks,
    }
  end

  local function ensureRevisionEntry(profile, domain)
    if type(profile) ~= "table" then
      return nil
    end
    profile.meta = type(profile.meta) == "table" and profile.meta or {}
    profile.meta.domainRevisions = type(profile.meta.domainRevisions) == "table" and profile.meta.domainRevisions or {}
    local revisions = profile.meta.domainRevisions
    revisions[domain] = type(revisions[domain]) == "table" and revisions[domain] or {}
    return revisions[domain], revisions
  end

  local function forceDomainRevision(profile, hostSummary, domain, relation)
    if type(profile) ~= "table" then
      return
    end
    local updatedAt = now()
    local entry, revisions = ensureRevisionEntry(profile, domain)
    if not entry then
      return
    end
    local hostRevision = math.max(0, tonumber(type(hostSummary) == "table" and hostSummary[domain]) or 0)
    local targetRevision = hostRevision
    if relation == "newer" then
      targetRevision = hostRevision + 1
    elseif relation == "older" then
      targetRevision = math.max(0, hostRevision - 1)
    end
    entry.revision = targetRevision
    entry.updatedAt = updatedAt

    if domain == "loot" or domain == "session" then
      local lootEntry = ensureRevisionEntry(profile, "loot")
      local sessionEntry = ensureRevisionEntry(profile, "session")
      lootEntry = type(lootEntry) == "table" and lootEntry or { revision = 0, updatedAt = updatedAt }
      sessionEntry = type(sessionEntry) == "table" and sessionEntry or { revision = 0, updatedAt = updatedAt }
      if domain == "loot" then
        lootEntry.revision = targetRevision
        lootEntry.updatedAt = updatedAt
      else
        sessionEntry.revision = targetRevision
        sessionEntry.updatedAt = updatedAt
      end
      local operationalEntry = ensureRevisionEntry(profile, "operational")
      if type(operationalEntry) == "table" then
        operationalEntry.revision = math.max(
          math.max(0, tonumber(lootEntry.revision) or 0),
          math.max(0, tonumber(sessionEntry.revision) or 0)
        )
        operationalEntry.updatedAt = updatedAt
      end
    end

    profile.meta = type(profile.meta) == "table" and profile.meta or {}
    profile.meta.revision = math.max(0, tonumber(profile.meta.revision) or 0, targetRevision)
    profile.meta.updatedAt = updatedAt
  end

  local function ensureBaseSyntheticSeed(profileName, runId)
    local profile = getProfileTable(profileName)
    if type(profile) ~= "table" then
      return false
    end
    profile.settings = type(profile.settings) == "table" and profile.settings or {}
    profile.settings[DEV_HARNESS_SETTING_KEY] = {
      label = "Developer Sync Seed",
      mode = "authoritative",
      updatedAt = now(),
    }
    if type(TouchLootProfileDomain) == "function" then
      TouchLootProfileDomain(profile, "settings")
    end

    profile.meta = type(profile.meta) == "table" and profile.meta or {}
    profile.meta.permissionPolicy = type(profile.meta.permissionPolicy) == "table" and profile.meta.permissionPolicy or {}
    profile.meta.permissionPolicy[DEV_HARNESS_PERMISSION_KEY] = {
      label = "Developer Permission Seed",
      role = "COUNCIL",
      updatedAt = now(),
    }
    if type(TouchLootProfileDomain) == "function" then
      TouchLootProfileDomain(profile, "permissions")
    end

    profile.lootRollStats = type(profile.lootRollStats) == "table" and profile.lootRollStats or {}
    profile.lootRollStats.events = type(profile.lootRollStats.events) == "table" and profile.lootRollStats.events or {}
    profile.lootRollStats.events[DEV_HARNESS_HOST_FUN_AWARD_EVENT] = {
      itemLink = "Fun Award - Luckiest Roller",
      optionKey = "luckiest_roller",
      optionLabel = "Luckiest Roller",
      character = "SyntheticHost",
      rollValue = 99,
      updatedAt = now(),
      winner = "SyntheticHost",
      note = "Host recorded SyntheticHost as Luckiest Roller",
    }
    if type(TouchLootProfileDomain) == "function" then
      TouchLootProfileDomain(profile, "loot")
    end

    profile.lootLedger = type(profile.lootLedger) == "table" and profile.lootLedger or {}
    profile.lootLedger[DEV_HARNESS_HOST_NOTE_CHARACTER] = profile.lootLedger[DEV_HARNESS_HOST_NOTE_CHARACTER] or {
      character = DEV_HARNESS_HOST_NOTE_CHARACTER,
      totalPoints = 0,
      items = {},
    }
    profile.lootLedger[DEV_HARNESS_HOST_NOTE_CHARACTER].items = {
      {
        entryId = DEV_HARNESS_HOST_NOTE_ENTRY,
        itemName = "Manual Note",
        points = 10,
        note = "Came late to raid",
        awardedAt = now(),
        isManual = true,
        grantedBy = "SyntheticHost",
      },
    }
    profile.lootLedger[DEV_HARNESS_HOST_NOTE_CHARACTER].totalPoints = 10
    if type(TouchLootProfileDomain) == "function" then
      TouchLootProfileDomain(profile, "loot")
    end

    profile.liveBoardHistory = type(profile.liveBoardHistory) == "table" and profile.liveBoardHistory or {}
    profile.liveBoardHistory[#profile.liveBoardHistory + 1] = {
      boardId = "devsync-host-" .. tostring(runId),
      sessionId = "devsync-host-" .. tostring(runId),
      label = "Sample host live board seed",
      itemOrder = {},
      items = {},
      createdAt = now(),
      updatedAt = now(),
      selectedItemKey = "",
    }
    if type(TouchLootProfileDomain) == "function" then
      TouchLootProfileDomain(profile, "session")
    end

    profile.sessions = type(profile.sessions) == "table" and profile.sessions or {}
    profile.sessions[#profile.sessions + 1] = {
      id = DEV_HARNESS_HOST_SESSION_ID,
      profileName = "Developer Sync Seed Session",
      host = "SyntheticHost",
      status = "FINISHED",
      startedAt = now() - 600,
      endedAt = now() - 120,
      members = {
        SyntheticHost = {
          name = "SyntheticHost",
          status = "JOINED",
          localAutoPassEnabled = false,
        },
      },
      rollOptions = {
        {
          optionKey = "need",
          label = "Need",
        },
      },
    }
    if type(TouchLootProfileDomain) == "function" then
      TouchLootProfileDomain(profile, "session")
    end
    return true
  end

  local function mutateSyntheticMemberProfile(profileName, hostSummary, index, relation)
    local profile = getProfileTable(profileName)
    if type(profile) ~= "table" then
      return nil
    end
    local token = tostring(index) .. "-" .. tostring(now())
    local variant = (math.max(1, tonumber(index) or 1) % 5)
    local domain = (variant == 3 and "session") or (variant == 4 and "settings") or (variant == 0 and "permissions") or "loot"
    if variant == 1 then
      local winnerName = buildMemberLabel(((math.max(1, tonumber(index) or 1) + 4) % 20) + 1)
      local characterName = buildMemberLabel(index)
      profile.lootRollStats = type(profile.lootRollStats) == "table" and profile.lootRollStats or {}
      profile.lootRollStats.events = type(profile.lootRollStats.events) == "table" and profile.lootRollStats.events or {}
      if relation == "older" then
        profile.lootRollStats.events[DEV_HARNESS_HOST_FUN_AWARD_EVENT] = nil
      elseif relation == "same" then
        profile.lootRollStats.events[DEV_HARNESS_HOST_FUN_AWARD_EVENT] = {
          itemLink = "Fun Award - Luckiest Roller",
          optionKey = "luckiest_roller",
          optionLabel = "Luckiest Roller",
          character = characterName,
          rollValue = math.max(1, 100 - math.max(1, tonumber(index) or 1)),
          updatedAt = now(),
          winner = winnerName,
          note = "Member recorded " .. winnerName .. " as Luckiest Roller",
        }
      else
        profile.lootRollStats.events["DEVSYNC_MEMBER_" .. token] = {
          itemLink = "Fun Award - Luckiest Roller",
          optionKey = "luckiest_roller",
          optionLabel = "Luckiest Roller",
          character = characterName,
          rollValue = math.max(1, 100 - math.max(1, tonumber(index) or 1)),
          updatedAt = now(),
          winner = winnerName,
          note = "Member recorded " .. winnerName .. " as Luckiest Roller",
        }
      end
    elseif variant == 2 then
      local memberLabel = buildMemberLabel(index)
      local characterKey = buildMemberName(index)
      profile.lootLedger = type(profile.lootLedger) == "table" and profile.lootLedger or {}
      if relation == "older" then
        local row = profile.lootLedger[DEV_HARNESS_HOST_NOTE_CHARACTER]
        if type(row) == "table" and type(row.items) == "table" then
          for itemIndex = #row.items, 1, -1 do
            if trim(type(row.items[itemIndex]) == "table" and row.items[itemIndex].entryId or "") == DEV_HARNESS_HOST_NOTE_ENTRY then
              table.remove(row.items, itemIndex)
            end
          end
          row.totalPoints = 0
          for _, item in ipairs(row.items) do
            row.totalPoints = row.totalPoints + (tonumber(type(item) == "table" and item.points) or 0)
          end
        end
      else
        profile.lootLedger[characterKey] = profile.lootLedger[characterKey] or {
          character = characterKey,
          totalPoints = 0,
          items = {},
        }
        local row = profile.lootLedger[characterKey]
        row.items = type(row.items) == "table" and row.items or {}
        row.items[#row.items + 1] = {
          entryId = "ledger-devsync-member-note-" .. token,
          itemName = "Manual Note",
          points = 10,
          note = "Came late to raid - " .. memberLabel,
          awardedAt = now(),
          isManual = true,
          grantedBy = "SyntheticHost",
        }
        row.totalPoints = 0
        for _, item in ipairs(row.items) do
          row.totalPoints = row.totalPoints + (tonumber(type(item) == "table" and item.points) or 0)
        end
      end
    elseif variant == 3 then
      local memberLabel = buildMemberLabel(index)
      profile.sessions = type(profile.sessions) == "table" and profile.sessions or {}
      if relation == "older" then
        for sessionIndex = #profile.sessions, 1, -1 do
          if trim(type(profile.sessions[sessionIndex]) == "table" and profile.sessions[sessionIndex].id or "") == DEV_HARNESS_HOST_SESSION_ID then
            table.remove(profile.sessions, sessionIndex)
          end
        end
      else
        profile.sessions[#profile.sessions + 1] = {
          id = "DEVSYNC_MEMBER_SESSION_" .. token,
          profileName = "Session History - " .. memberLabel,
          host = memberLabel,
          status = relation == "same" and "FINISHED" or "PREPARING",
          startedAt = now() - 300,
          endedAt = relation == "same" and (now() - 60) or nil,
          members = {
            [memberLabel] = {
              name = memberLabel,
              status = "JOINED",
              localAutoPassEnabled = (index % 2) == 0,
            },
          },
          rollOptions = {
            {
              optionKey = "bis",
              label = "BiS",
            },
          },
        }
      end
    elseif variant == 4 then
      profile.settings = type(profile.settings) == "table" and profile.settings or {}
      if relation == "older" then
        profile.settings[DEV_HARNESS_SETTING_KEY] = {
          label = "Developer Sync Seed",
          mode = "legacy",
          updatedAt = now() - 300,
        }
      else
        profile.settings[DEV_HARNESS_SETTING_KEY] = {
          label = "Raid Prep Override " .. buildMemberLabel(index),
          mode = relation == "same" and "conflict" or "member_newer",
          updatedAt = now(),
        }
      end
    else
      profile.meta = type(profile.meta) == "table" and profile.meta or {}
      profile.meta.permissionPolicy = type(profile.meta.permissionPolicy) == "table" and profile.meta.permissionPolicy or {}
      if relation == "older" then
        profile.meta.permissionPolicy[DEV_HARNESS_PERMISSION_KEY] = {
          label = "Developer Permission Seed",
          role = "RAIDER",
          updatedAt = now() - 300,
        }
      else
        profile.meta.permissionPolicy[DEV_HARNESS_PERMISSION_KEY] = {
          label = "Permission Override " .. buildMemberLabel(index),
          role = relation == "same" and "ASSIST" or "COUNCIL",
          updatedAt = now(),
        }
      end
    end
    if type(TouchLootProfileDomain) == "function" then
      TouchLootProfileDomain(profile, domain)
    end
    forceDomainRevision(profile, hostSummary, domain, relation)
    return domain
  end

  local function buildPseudoMemberMeta(index)
    local entry = PSEUDO_CLASS_SPECS[((math.max(1, tonumber(index) or 1) - 1) % #PSEUDO_CLASS_SPECS) + 1]
    return copy(entry)
  end

  local function buildSummary(profileName)
    local summary = type(GetLootProfileRevisionSummary) == "function" and GetLootProfileRevisionSummary(profileName) or nil
    summary = type(summary) == "table" and summary or {}
    local profileId = trim(summary.profileId)
    if profileId == "" and type(GetLootProfileId) == "function" then
      profileId = trim(select(1, GetLootProfileId(profileName)) or "")
      summary.profileId = profileId
    end
    return {
      profileName = trim(summary.profileName or profileName),
      profileId = profileId,
      settings = math.max(0, tonumber(summary.settings) or 0),
      permissions = math.max(0, tonumber(summary.permissions) or 0),
      operational = math.max(0, tonumber(summary.operational) or 0),
      loot = math.max(0, tonumber(summary.loot or summary.operational) or 0),
      session = math.max(0, tonumber(summary.session or summary.operational) or 0),
      settingsChecksum = trim(summary.settingsChecksum),
      permissionsChecksum = trim(summary.permissionsChecksum),
      operationalChecksum = trim(summary.operationalChecksum),
      lootChecksum = trim(summary.lootChecksum ~= "" and summary.lootChecksum or summary.operationalChecksum),
      sessionChecksum = trim(summary.sessionChecksum ~= "" and summary.sessionChecksum or summary.operationalChecksum),
      updatedAt = math.max(0, tonumber(summary.updatedAt) or 0),
    }
  end

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

  local function buildScenarioKinds(scenario, memberCount)
    memberCount = resolveMemberCount(memberCount)
    scenario = resolveScenario(scenario)
    local kinds = {}
    if scenario == "FRESH" then
      for index = 1, memberCount do
        kinds[index] = "fresh"
      end
      return kinds
    end

    if scenario == "RETURNING" then
      local cycle = { "aligned", "host_newer", "member_newer", "aligned", "aligned", "host_newer" }
      for index = 1, memberCount do
        kinds[index] = cycle[((index - 1) % #cycle) + 1]
      end
      if memberCount >= 3 then
        kinds[1] = "aligned"
        kinds[2] = "host_newer"
        kinds[3] = "member_newer"
      end
      return kinds
    end

    local freshCount = select(1, buildScenarioCounts("MIXED", memberCount))
    local freshByIndex = {}
    for freshIndex = 0, freshCount - 1 do
      freshByIndex[math.floor((freshIndex * memberCount) / freshCount) + 1] = true
    end
    local cycle = { "host_newer", "member_newer", "diverged", "aligned" }
    local nonFreshIndex = 0
    for index = 1, memberCount do
      if freshByIndex[index] then
        kinds[index] = "fresh"
      else
        nonFreshIndex = nonFreshIndex + 1
        kinds[index] = cycle[((nonFreshIndex - 1) % #cycle) + 1]
      end
    end
    return kinds
  end

  local function buildStatefulRevisionState()
    local state = {}
    for index, domain in ipairs(PROFILE_REVISION_DOMAINS) do
      state[domain] = index * 100
    end
    return state
  end

  local function cloneStatefulRevisionState(state)
    local clone = {}
    for _, domain in ipairs(PROFILE_REVISION_DOMAINS) do
      clone[domain] = math.max(0, tonumber(type(state) == "table" and state[domain]) or 0)
    end
    return clone
  end

  local function statesHaveSameRevisions(left, right)
    for _, domain in ipairs(PROFILE_REVISION_DOMAINS) do
      if math.max(0, tonumber(type(left) == "table" and left[domain]) or 0)
        ~= math.max(0, tonumber(type(right) == "table" and right[domain]) or 0)
      then
        return false
      end
    end
    return true
  end

  local function copyStatefulDomains(target, source, domains)
    local copied = 0
    for _, domain in ipairs(type(domains) == "table" and domains or {}) do
      if target[domain] ~= nil and source[domain] ~= nil and target[domain] ~= source[domain] then
        target[domain] = source[domain]
        copied = copied + 1
      end
    end
    return copied
  end

  local function statefulDomainForMember(index)
    return PROFILE_REVISION_DOMAINS[((math.max(1, tonumber(index) or 1) - 1) % #PROFILE_REVISION_DOMAINS) + 1]
  end

  local function simulateFreshJoinTransfer()
    local host = buildStatefulRevisionState()
    local member = {}
    for _, domain in ipairs(PROFILE_REVISION_DOMAINS) do
      member[domain] = 0
    end
    local copiedDomains = copyStatefulDomains(member, host, PROFILE_REVISION_DOMAINS)
    return {
      mode = "snapshot",
      scheduledDomainTransfers = #PROFILE_REVISION_DOMAINS,
      copiedDomains = copiedDomains,
      acknowledgements = 1,
      converged = statesHaveSameRevisions(member, host),
    }
  end

  local function simulateReturningJoinDelta(index)
    local host = buildStatefulRevisionState()
    local member = cloneStatefulRevisionState(host)
    local domain = statefulDomainForMember(index)
    member[domain] = math.max(0, member[domain] - 1)
    local copiedDomains = copyStatefulDomains(member, host, { domain })
    return {
      mode = "delta",
      domain = domain,
      scheduledDomainTransfers = 1,
      copiedDomains = copiedDomains,
      acknowledgements = 1,
      converged = statesHaveSameRevisions(member, host),
    }
  end

  local function simulateHostDomainFanout(memberCount, domain)
    local host = buildStatefulRevisionState()
    local members = {}
    memberCount = resolveMemberCount(memberCount)
    domain = trim(domain)
    if domain == "" or host[domain] == nil then
      domain = statefulDomainForMember(1)
    end
    for index = 1, memberCount do
      members[index] = cloneStatefulRevisionState(host)
    end
    host[domain] = host[domain] + 1

    local scheduledDomainTransfers = 0
    local acknowledgements = 0
    local allConverged = true
    for index = 1, memberCount do
      scheduledDomainTransfers = scheduledDomainTransfers + copyStatefulDomains(members[index], host, { domain })
      acknowledgements = acknowledgements + 1
      allConverged = allConverged and statesHaveSameRevisions(members[index], host)
    end
    return {
      domain = domain,
      scheduledDomainTransfers = scheduledDomainTransfers,
      acknowledgements = acknowledgements,
      converged = allConverged,
    }
  end

  local function simulateMemberDomainFanout(memberCount, sourceIndex, domain)
    local host = buildStatefulRevisionState()
    local members = {}
    memberCount = resolveMemberCount(memberCount)
    sourceIndex = math.max(1, math.min(memberCount, math.floor(tonumber(sourceIndex) or 1)))
    domain = trim(domain)
    if domain == "" or host[domain] == nil then
      domain = statefulDomainForMember(sourceIndex)
    end
    for index = 1, memberCount do
      members[index] = cloneStatefulRevisionState(host)
    end
    members[sourceIndex][domain] = members[sourceIndex][domain] + 1
    host[domain] = members[sourceIndex][domain]

    local relayDomainTransfers = 0
    local acknowledgements = 1 -- The host acknowledges the member-to-host delta.
    local allConverged = true
    for index = 1, memberCount do
      if index ~= sourceIndex then
        relayDomainTransfers = relayDomainTransfers + copyStatefulDomains(members[index], host, { domain })
        acknowledgements = acknowledgements + 1
      end
      allConverged = allConverged and statesHaveSameRevisions(members[index], host)
    end
    return {
      domain = domain,
      uploadDomainTransfers = 1,
      relayDomainTransfers = relayDomainTransfers,
      scheduledDomainTransfers = 1 + relayDomainTransfers,
      acknowledgements = acknowledgements,
      converged = allConverged,
    }
  end

  local function buildStatefulJoinPlan(scenario, memberCount)
    local host = buildStatefulRevisionState()
    local kinds = buildScenarioKinds(scenario, memberCount)
    local summary = {
      freshSnapshots = 0,
      hostDeltas = 0,
      memberUploads = 0,
      conflicts = 0,
      aligned = 0,
      scheduledDomainTransfers = 0,
      acknowledgements = 0,
      unchangedDomainTransfers = 0,
    }
    local members = {}
    for index, kind in ipairs(kinds) do
      local domain = statefulDomainForMember(index)
      local entry = {
        index = index,
        kind = kind,
        domain = domain,
        transferMode = "none",
        scheduledDomainTransfers = 0,
        acknowledgements = 0,
      }
      if kind == "fresh" then
        entry.transferMode = "snapshot"
        entry.scheduledDomainTransfers = #PROFILE_REVISION_DOMAINS
        entry.acknowledgements = 1
        summary.freshSnapshots = summary.freshSnapshots + 1
      elseif kind == "host_newer" then
        entry.transferMode = "host_delta"
        entry.scheduledDomainTransfers = 1
        entry.acknowledgements = 1
        summary.hostDeltas = summary.hostDeltas + 1
      elseif kind == "member_newer" then
        entry.transferMode = "member_delta"
        entry.scheduledDomainTransfers = 1
        entry.acknowledgements = 1
        summary.memberUploads = summary.memberUploads + 1
      elseif kind == "diverged" then
        entry.transferMode = "conflict"
        summary.conflicts = summary.conflicts + 1
      else
        summary.aligned = summary.aligned + 1
      end
      summary.scheduledDomainTransfers = summary.scheduledDomainTransfers + entry.scheduledDomainTransfers
      summary.acknowledgements = summary.acknowledgements + entry.acknowledgements
      members[#members + 1] = entry
    end
    return {
      host = host,
      members = members,
      summary = summary,
    }
  end

  local function buildStatefulTransferMatrix()
    local matrix = {
      freshJoin = simulateFreshJoinTransfer(),
      returningJoin = simulateReturningJoinDelta(2),
      mixedJoin = buildStatefulJoinPlan("MIXED", 20),
      hostFanout = {},
      memberFanout = {},
    }
    for _, memberCount in ipairs({ 5, 10, 20 }) do
      matrix.hostFanout[memberCount] = simulateHostDomainFanout(memberCount, "loot")
      matrix.memberFanout[memberCount] = simulateMemberDomainFanout(memberCount, 2, "loot")
    end
    return matrix
  end

  local function buildMemberEntry(memberKey, summary, meta, role, isHost, kind)
    summary = type(summary) == "table" and summary or buildEmptySummary()
    meta = type(meta) == "table" and meta or {}
    local isFresh = trim(kind) == "fresh"
    return {
      name = memberKey,
      role = trim(role) ~= "" and trim(role) or "RAIDER",
      status = "JOINED",
      joinedAt = now(),
      addonVersion = DEFAULT_ADDON_VERSION,
      clientVersion = DEFAULT_CLIENT_VERSION,
      className = trim(meta.className),
      classFile = trim(meta.classFile),
      specName = trim(meta.specName),
      specIcon = trim(meta.specIcon),
      localAutoPassEnabled = not isFresh,
      sharedProfileId = trim(summary.profileId),
      settingsRevision = summary.settings,
      permissionsRevision = summary.permissions,
      operationalRevision = summary.operational,
      lootRevision = summary.loot,
      sessionRevision = summary.session,
      settingsChecksum = trim(summary.settingsChecksum),
      permissionsChecksum = trim(summary.permissionsChecksum),
      operationalChecksum = trim(summary.operationalChecksum),
      lootChecksum = trim(summary.lootChecksum),
      sessionChecksum = trim(summary.sessionChecksum),
      profileUpdatedAt = summary.updatedAt,
      lastSyncAt = now(),
      profileMaster = isHost and memberKey or "",
      harnessKind = trim(kind),
      sharedProfileReady = not isFresh,
    }
  end

  local function refreshSyntheticSessionMembers(synthetic)
    synthetic = type(synthetic) == "table" and synthetic or nil
    if not synthetic or type(synthetic.activeSession) ~= "table" then
      return
    end
    local members = synthetic.activeSession.members or {}
    local hostSummary = buildSummary(synthetic.hostProfileName)
    local hostMember = members[synthetic.selfKey]
    if type(hostMember) == "table" then
      local updatedHost = buildMemberEntry(synthetic.selfKey, hostSummary, synthetic.memberMetaByKey[synthetic.selfKey], "MASTER", true, "host")
      if type(GetLocalAutoPassEnabled) == "function" then
        updatedHost.localAutoPassEnabled = GetLocalAutoPassEnabled() and true or false
      end
      updatedHost.joinedAt = tonumber(hostMember.joinedAt) or updatedHost.joinedAt
      for key, value in pairs(updatedHost) do
        hostMember[key] = value
      end
    end
    for memberKey, kind in pairs(synthetic.memberKindsByKey or {}) do
      if lowerKey(memberKey) ~= lowerKey(synthetic.selfKey) then
        local summary = buildEmptySummary()
        local memberProfileName = trim(type(synthetic.memberProfilesByKey) == "table" and synthetic.memberProfilesByKey[memberKey] or "")
        if memberProfileName ~= "" then
          summary = buildSummary(memberProfileName)
        end
        local updatedMember = buildMemberEntry(memberKey, summary, synthetic.memberMetaByKey[memberKey], "RAIDER", false, kind)
        local target = members[memberKey]
        if type(target) ~= "table" then
          members[memberKey] = updatedMember
        else
          updatedMember.joinedAt = tonumber(target.joinedAt) or updatedMember.joinedAt
          for key, value in pairs(updatedMember) do
            target[key] = value
          end
        end
      end
    end
    synthetic.activeSession.members = members
    synthetic.updatedAt = now()
  end

  local function setSyntheticRuntimeState(store, severity, message)
    store = store or ensureStore()
    local synthetic = type(store.syntheticSession) == "table" and store.syntheticSession or nil
    if not synthetic then
      return
    end
    synthetic.severity = trim(severity)
    synthetic.message = trim(message)
    synthetic.updatedAt = now()
  end

  local function clearSyntheticReviewState(synthetic)
    synthetic = type(synthetic) == "table" and synthetic or nil
    if not synthetic then
      return
    end
    synthetic.detailDiff = nil
    synthetic.detailConflict = nil
    synthetic.detailSnapshotData = nil
    synthetic.detailPreviewSummary = nil
    synthetic.detailBaseSummary = nil
    synthetic.reviewMemberKey = nil
  end

  local function buildSyntheticSession(report)
    local store = ensureStore()
    clearSyntheticSessionState(store)
    local root = getRoot()
    if type(root) ~= "table" or type(root.profiles) ~= "table" then
      return false, "Developer sync harness could not access the profile database."
    end
    if type(GetActiveLootSession) == "function" and type(GetActiveLootSession()) == "table" then
      return false, "Stop the real active loot session before starting the synthetic sync harness."
    end

    local runId = nowMsToken()
    local sourceProfileName = trim(type(report) == "table" and report.profileName or "")
    local hostProfileName = buildHiddenProfileName(runId, "HOST", 0)
    local cloned, cloneErr = cloneProfile(sourceProfileName, hostProfileName)
    if not cloned then
      return false, cloneErr or "Could not create the synthetic host profile."
    end
    ensureBaseSyntheticSeed(hostProfileName, runId)
    local hostSummary = buildSummary(hostProfileName)
    local selfKey = trim(type(GetCharacterKey) == "function" and GetCharacterKey() or "HarnessHost-PreviewRealm")
    local synthetic = {
      active = true,
      runId = runId,
      sourceProfileName = sourceProfileName,
      sourceProfileMode = trim(type(report) == "table" and report.profileMode or DEFAULT_PROFILE_MODE),
      hostProfileName = hostProfileName,
      selfKey = selfKey,
      memberKindsByKey = {},
      memberProfilesByKey = {},
      memberMetaByKey = {},
      preciseLoadedByMember = {},
      activeSession = {
        id = "DEVSYNC-" .. tostring(runId),
        profileName = hostProfileName,
        displayProfileName = sourceProfileName,
        host = selfKey,
        status = "PREPARING",
        startedAt = now(),
        acceptedBySelf = true,
        members = {},
        isSynthetic = true,
      },
    }

    synthetic.memberMetaByKey[selfKey] = {
      className = "Evoker",
      classFile = "EVOKER",
      specName = "Developer Host",
      specIcon = "5198700",
    }
    synthetic.memberKindsByKey[selfKey] = "host"
    synthetic.activeSession.members[selfKey] = buildMemberEntry(selfKey, hostSummary, synthetic.memberMetaByKey[selfKey], "MASTER", true, "host")

    local memberKinds = buildScenarioKinds(trim(report.scenario), math.max(1, tonumber(report.memberCount) or 0))
    for index = 1, math.max(1, tonumber(report.memberCount) or 0) do
      local memberKey = buildMemberName(index)
      local kind = trim(memberKinds[index])
      synthetic.memberKindsByKey[memberKey] = kind
      synthetic.memberMetaByKey[memberKey] = buildPseudoMemberMeta(index)
      if kind ~= "fresh" then
        local memberProfileName = buildHiddenProfileName(runId, "MEMBER", index)
        local ok, err = cloneProfile(hostProfileName, memberProfileName)
        if not ok then
          return false, err or ("Could not create the synthetic member profile for " .. memberKey)
        end
        synthetic.memberProfilesByKey[memberKey] = memberProfileName
        if kind == "host_newer" then
          mutateSyntheticMemberProfile(memberProfileName, hostSummary, index, "older")
        elseif kind == "member_newer" then
          mutateSyntheticMemberProfile(memberProfileName, hostSummary, index, "newer")
        elseif kind == "diverged" then
          mutateSyntheticMemberProfile(memberProfileName, hostSummary, index, "same")
        end
      end
      synthetic.activeSession.members[memberKey] = buildMemberEntry(
        memberKey,
        trim(synthetic.memberProfilesByKey[memberKey]) ~= "" and buildSummary(synthetic.memberProfilesByKey[memberKey]) or buildEmptySummary(),
        synthetic.memberMetaByKey[memberKey],
        "RAIDER",
        false,
        kind
      )
    end

    store.syntheticSession = synthetic
    refreshSyntheticSessionMembers(store.syntheticSession)
    setSyntheticRuntimeState(store, "success", "Developer synthetic session created for Sync Management rehearsal.")
    return true, copy(store.syntheticSession)
  end

  local function getSyntheticSession()
    local store = ensureStore()
    local synthetic = type(store.syntheticSession) == "table" and store.syntheticSession or nil
    if type(synthetic) ~= "table" or synthetic.active ~= true then
      return nil
    end
    if invalidateSyntheticSessionForProfileSwitch(store, synthetic) then
      return nil
    end
    return synthetic
  end

  local function getSyntheticSessionContext()
    local synthetic = getSyntheticSession()
    if not synthetic then
      return nil
    end
    return {
      active = true,
      activeSession = synthetic.activeSession,
      activeProfileName = synthetic.hostProfileName,
      displayProfileName = synthetic.sourceProfileName,
      sourceProfileMode = synthetic.sourceProfileMode,
    }
  end

  local function compareRevisionSummaries(localSummary, remoteSummary, domains)
    local remoteNewer = {}
    local localNewer = {}
    local left = type(localSummary) == "table" and localSummary or buildEmptySummary()
    local right = type(remoteSummary) == "table" and remoteSummary or buildEmptySummary()
    for _, domain in ipairs(resolveDomains(domains)) do
      local localRevision = math.max(0, tonumber(left[domain]) or 0)
      local remoteRevision = math.max(0, tonumber(right[domain]) or 0)
      local checksumKey = domain .. "Checksum"
      local localChecksum = trim(left[checksumKey])
      local remoteChecksum = trim(right[checksumKey])
      local haveChecksums = localChecksum ~= "" and remoteChecksum ~= ""
      if haveChecksums and localChecksum == remoteChecksum then
      elseif haveChecksums and localChecksum ~= remoteChecksum then
        if remoteRevision > localRevision then
          remoteNewer[#remoteNewer + 1] = domain
        elseif localRevision > remoteRevision then
          localNewer[#localNewer + 1] = domain
        else
          remoteNewer[#remoteNewer + 1] = domain
          localNewer[#localNewer + 1] = domain
        end
      elseif remoteRevision > localRevision then
        remoteNewer[#remoteNewer + 1] = domain
      elseif localRevision > remoteRevision then
        localNewer[#localNewer + 1] = domain
      end
    end
    return remoteNewer, localNewer
  end

  local function resolveComparison(localSummary, remoteSummary)
    local remoteNewerDomains, localNewerDomains = compareRevisionSummaries(localSummary, remoteSummary)
    local comparison = "same"
    local localProfileId = trim(type(localSummary) == "table" and localSummary.profileId or "")
    local remoteProfileId = trim(type(remoteSummary) == "table" and remoteSummary.profileId or "")
    if remoteProfileId == "" then
      if #remoteNewerDomains > 0 and #localNewerDomains > 0 then
        comparison = "diverged"
      elseif #remoteNewerDomains > 0 then
        comparison = "remote_newer"
      elseif #localNewerDomains > 0 then
        comparison = "local_newer"
      else
        comparison = "unknown"
      end
    elseif localProfileId ~= "" and lowerKey(localProfileId) ~= lowerKey(remoteProfileId) then
      comparison = "different_lineage"
    elseif #remoteNewerDomains > 0 and #localNewerDomains > 0 then
      comparison = "diverged"
    elseif #remoteNewerDomains > 0 then
      comparison = "remote_newer"
    elseif #localNewerDomains > 0 then
      comparison = "local_newer"
    end
    return comparison, remoteNewerDomains, localNewerDomains
  end

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

  local function resolveBootstrapState(candidate)
    candidate = type(candidate) == "table" and candidate or {}
    local comparison = lowerKey(candidate.comparison)
    if comparison == "different_lineage" then
      return "lineage"
    end
    if comparison == "unknown" or trim(candidate.profileId) == "" then
      return "pending"
    end
    local settingsRemote = hasDomain(candidate.remoteNewerDomains, "settings")
    local settingsLocal = hasDomain(candidate.localNewerDomains, "settings")
    local permissionsRemote = hasDomain(candidate.remoteNewerDomains, "permissions")
    local permissionsLocal = hasDomain(candidate.localNewerDomains, "permissions")
    if not settingsRemote and not settingsLocal and not permissionsRemote and not permissionsLocal then
      return "ready"
    end
    if settingsRemote or permissionsRemote then
      return "review"
    end
    if settingsLocal or permissionsLocal then
      return "pending"
    end
    return "unknown"
  end

  local function buildPreciseDiffInfo(synthetic, candidate)
    candidate = type(candidate) == "table" and candidate or {}
    local memberKey = trim(candidate.memberKey)
    local memberProfileName = trim(type(synthetic.memberProfilesByKey) == "table" and synthetic.memberProfilesByKey[memberKey] or "")
    if memberKey == "" or memberProfileName == "" or not synthetic.preciseLoadedByMember[memberKey] then
      return {
        scopeDomains = {},
        differentSubdomains = {},
        differentSubdomainsByDomain = {},
      }
    end
    local hostManifest = type(GetLootProfileSubchecksumManifest) == "function" and GetLootProfileSubchecksumManifest(synthetic.hostProfileName) or nil
    local memberManifest = type(GetLootProfileSubchecksumManifest) == "function" and GetLootProfileSubchecksumManifest(memberProfileName) or nil
    if type(hostManifest) ~= "table" or type(memberManifest) ~= "table" then
      return {
        scopeDomains = {},
        differentSubdomains = {},
        differentSubdomainsByDomain = {},
      }
    end

    local mergedSubdomains = {}
    local seen = {}
    local function addSubdomain(subdomain)
      local value = trim(subdomain)
      local key = lowerKey(value)
      if value ~= "" and not seen[key] then
        seen[key] = true
        mergedSubdomains[#mergedSubdomains + 1] = value
      end
    end
    for _, subdomain in ipairs(type(hostManifest.subdomains) == "table" and hostManifest.subdomains or {}) do
      addSubdomain(subdomain)
    end
    for _, subdomain in ipairs(type(memberManifest.subdomains) == "table" and memberManifest.subdomains or {}) do
      addSubdomain(subdomain)
    end

    local byDomain = {}
    local differentSubdomains = {}
    for _, subdomain in ipairs(mergedSubdomains) do
      local leftChecksum = trim(type(hostManifest.checksums) == "table" and hostManifest.checksums[subdomain] or "")
      local rightChecksum = trim(type(memberManifest.checksums) == "table" and memberManifest.checksums[subdomain] or "")
      if leftChecksum ~= rightChecksum then
        local domain = trim(type(GetLootProfileSubdomainParentDomain) == "function" and GetLootProfileSubdomainParentDomain(subdomain) or "")
        if domain ~= "" then
          byDomain[domain] = type(byDomain[domain]) == "table" and byDomain[domain] or {}
          byDomain[domain][#byDomain[domain] + 1] = subdomain
          differentSubdomains[#differentSubdomains + 1] = subdomain
        end
      end
    end

    local scopeDomains = {}
    for _, domain in ipairs(resolveDomains()) do
      if type(byDomain[domain]) == "table" and #byDomain[domain] > 0 then
        scopeDomains[#scopeDomains + 1] = domain
      end
    end
    return {
      scopeDomains = scopeDomains,
      differentSubdomains = differentSubdomains,
      differentSubdomainsByDomain = byDomain,
    }
  end

  local function buildSafeRecommendation(candidate)
    candidate = type(candidate) == "table" and candidate or {}
    local comparison = lowerKey(candidate.comparison)
    if comparison == "same" then
      return {
        action = "none",
        label = "Already Aligned",
      }
    end
    if comparison == "unknown" then
      return {
        action = "push",
        label = "Run Recommended Repair: Push Bootstrap",
        domains = cloneDomainList(PROFILE_BOOTSTRAP_DOMAINS),
      }
    end
    if comparison == "local_newer" then
      if candidate.precisePushReady and type(candidate.precisePushSubdomains) == "table" and #candidate.precisePushSubdomains > 0 then
        return {
          action = "push",
          label = "Run Recommended Repair: Push Selected",
          domains = cloneDomainList(candidate.hostRepairDomains),
          subdomains = copy(candidate.precisePushSubdomains),
        }
      end
      if type(candidate.hostRepairDomains) == "table" and #candidate.hostRepairDomains > 0 then
        return {
          action = "push",
          label = "Run Recommended Repair: Push Host Repair",
          domains = cloneDomainList(candidate.hostRepairDomains),
        }
      end
      return {
        action = "check",
        label = "Run Recommended Repair: Check Differences",
      }
    end
    if comparison == "remote_newer" then
      if candidate.precisePullReady and type(candidate.precisePullSubdomains) == "table" and #candidate.precisePullSubdomains > 0 then
        return {
          action = "pull",
          label = "Run Recommended Repair: Pull Selected",
          domains = cloneDomainList(candidate.memberRepairDomains),
          subdomains = copy(candidate.precisePullSubdomains),
        }
      end
      if type(candidate.memberRepairDomains) == "table" and #candidate.memberRepairDomains > 0 then
        return {
          action = "pull",
          label = "Run Recommended Repair: Pull Member Repair",
          domains = cloneDomainList(candidate.memberRepairDomains),
        }
      end
      return {
        action = "check",
        label = "Run Recommended Repair: Check Differences",
      }
    end
    if comparison == "diverged" then
      if candidate.precisePreviewReady then
        return {
          action = "preview",
          label = "Run Recommended Repair: Preview Repair",
          domains = cloneDomainList(resolveDomains()),
          subdomains = copy(candidate.precisePreviewSubdomains or {}),
        }
      end
      return {
        action = "check",
        label = "Run Recommended Repair: Check Differences",
      }
    end
    if comparison == "different_lineage" then
      return {
        action = "push",
        label = "Run Recommended Repair: Replace With Host Copy",
      }
    end
    return {
      action = "check",
      label = "Run Recommended Repair: Check Differences",
    }
  end

  local function buildSyntheticCandidates()
    local synthetic = getSyntheticSession()
    if not synthetic then
      return {}
    end
    refreshSyntheticSessionMembers(synthetic)
    local hostSummary = buildSummary(synthetic.hostProfileName)
    local candidates = {}
    for memberKey, member in pairs(synthetic.activeSession.members or {}) do
      if lowerKey(memberKey) ~= lowerKey(synthetic.selfKey) and trim(type(member) == "table" and member.status or "JOINED") == "JOINED" then
        local memberProfileName = trim(type(synthetic.memberProfilesByKey) == "table" and synthetic.memberProfilesByKey[memberKey] or "")
        local remoteSummary = memberProfileName ~= "" and buildSummary(memberProfileName) or buildEmptySummary()
        local comparison, remoteNewerDomains, localNewerDomains = resolveComparison(hostSummary, remoteSummary)
        local candidate = {
          memberKey = memberKey,
          isSessionHost = false,
          role = trim(type(member) == "table" and member.role or "RAIDER"),
          addonVersion = trim(type(member) == "table" and member.addonVersion or DEFAULT_ADDON_VERSION),
          className = trim(type(member) == "table" and member.className or ""),
          classFile = trim(type(member) == "table" and member.classFile or ""),
          specName = trim(type(member) == "table" and member.specName or ""),
          specIcon = trim(type(member) == "table" and member.specIcon or ""),
          profileId = trim(remoteSummary.profileId),
          settings = remoteSummary.settings,
          permissions = remoteSummary.permissions,
          operational = remoteSummary.operational,
          loot = remoteSummary.loot,
          session = remoteSummary.session,
          settingsChecksum = trim(remoteSummary.settingsChecksum),
          permissionsChecksum = trim(remoteSummary.permissionsChecksum),
          operationalChecksum = trim(remoteSummary.operationalChecksum),
          lootChecksum = trim(remoteSummary.lootChecksum),
          sessionChecksum = trim(remoteSummary.sessionChecksum),
          updatedAt = remoteSummary.updatedAt,
          comparison = comparison,
          remoteNewerDomains = remoteNewerDomains,
          localNewerDomains = localNewerDomains,
          remoteDomainText = formatDomains(remoteNewerDomains),
          localDomainText = formatDomains(localNewerDomains),
          hostRepairDomains = cloneDomainList(localNewerDomains),
          memberRepairDomains = cloneDomainList(remoteNewerDomains),
        }
        candidate.bootstrapState = resolveBootstrapState(candidate)
        local preciseDiff = buildPreciseDiffInfo(synthetic, candidate)
        candidate.preciseScopeDomains = preciseDiff.scopeDomains
        candidate.preciseDifferentSubdomains = preciseDiff.differentSubdomains
        candidate.preciseDifferentSubdomainsByDomain = preciseDiff.differentSubdomainsByDomain
        candidate.precisePushSubdomains = {}
        candidate.precisePullSubdomains = {}
        candidate.precisePreviewSubdomains = copy(preciseDiff.differentSubdomains)
        for _, domain in ipairs(candidate.hostRepairDomains) do
          for _, subdomain in ipairs(type(preciseDiff.differentSubdomainsByDomain[domain]) == "table" and preciseDiff.differentSubdomainsByDomain[domain] or {}) do
            candidate.precisePushSubdomains[#candidate.precisePushSubdomains + 1] = subdomain
          end
        end
        for _, domain in ipairs(candidate.memberRepairDomains) do
          for _, subdomain in ipairs(type(preciseDiff.differentSubdomainsByDomain[domain]) == "table" and preciseDiff.differentSubdomainsByDomain[domain] or {}) do
            candidate.precisePullSubdomains[#candidate.precisePullSubdomains + 1] = subdomain
          end
        end
        candidate.preciseDetailLoaded = synthetic.preciseLoadedByMember[memberKey] == true
        candidate.precisePushReady = #candidate.precisePushSubdomains > 0
        candidate.precisePullReady = #candidate.precisePullSubdomains > 0
        candidate.precisePreviewReady = #candidate.precisePreviewSubdomains > 0
        local function buildSubdomainText(subdomains)
          local labels = {}
          for _, subdomain in ipairs(type(subdomains) == "table" and subdomains or {}) do
            labels[#labels + 1] = type(GetLootProfileSubdomainLabel) == "function" and GetLootProfileSubdomainLabel(subdomain) or subdomain
          end
          return table.concat(labels, ", ")
        end
        candidate.precisePushText = buildSubdomainText(candidate.precisePushSubdomains)
        candidate.precisePullText = buildSubdomainText(candidate.precisePullSubdomains)
        candidate.precisePreviewText = buildSubdomainText(candidate.precisePreviewSubdomains)
        candidate.patchPushSubdomains = {}
        candidate.patchPullSubdomains = {}
        candidate.patchPreviewSubdomains = {}
        candidate.patchPushReady = false
        candidate.patchDetailLoaded = false
        if type(FilterLootProfilePatchCapableSubdomains) == "function" then
          candidate.patchPushSubdomains = FilterLootProfilePatchCapableSubdomains(candidate.precisePushSubdomains)
          candidate.patchPullSubdomains = FilterLootProfilePatchCapableSubdomains(candidate.precisePullSubdomains)
          candidate.patchPreviewSubdomains = FilterLootProfilePatchCapableSubdomains(candidate.precisePreviewSubdomains)
        end
        candidate.patchPushText = ""
        candidate.patchPullText = ""
        candidate.patchPreviewText = ""
        candidate.safeRecommendation = buildSafeRecommendation(candidate)
        candidates[#candidates + 1] = candidate
      end
    end
    table.sort(candidates, function(left, right)
      local priority = {
        remote_newer = 1,
        diverged = 2,
        unknown = 3,
        different_lineage = 4,
        local_newer = 5,
        same = 6,
      }
      local leftPriority = priority[trim(left.comparison)] or 99
      local rightPriority = priority[trim(right.comparison)] or 99
      if leftPriority ~= rightPriority then
        return leftPriority < rightPriority
      end
      return lowerKey(left.memberKey) < lowerKey(right.memberKey)
    end)
    return candidates
  end

  local function buildSyntheticStatus(precomputedCandidates)
    local synthetic = getSyntheticSession()
    if not synthetic then
      return {
        activeSession = false,
        isHost = false,
      }
    end
    local counts = {
      remote_newer = 0,
      diverged = 0,
      local_newer = 0,
      same = 0,
      unknown = 0,
      different_lineage = 0,
    }
    local bootstrapCounts = {
      ready = 0,
      pending = 0,
      review = 0,
      lineage = 0,
      unknown = 0,
    }
    local candidates = type(precomputedCandidates) == "table" and precomputedCandidates or buildSyntheticCandidates()
    for _, candidate in ipairs(candidates) do
      local comparison = trim(candidate.comparison)
      if counts[comparison] ~= nil then
        counts[comparison] = counts[comparison] + 1
      end
      local bootstrapState = trim(candidate.bootstrapState)
      if bootstrapCounts[bootstrapState] ~= nil then
        bootstrapCounts[bootstrapState] = bootstrapCounts[bootstrapState] + 1
      else
        bootstrapCounts.unknown = bootstrapCounts.unknown + 1
      end
    end
    return {
      activeSession = true,
      sessionId = trim(synthetic.activeSession.id),
      profileName = trim(synthetic.hostProfileName),
      displayProfileName = trim(synthetic.sourceProfileName),
      isHost = true,
      candidateCounts = counts,
      bootstrapCounts = bootstrapCounts,
      mode = "developer_harness",
      severity = trim(synthetic.severity),
      message = trim(synthetic.message),
      sender = trim(synthetic.selfKey),
      updatedAt = math.max(0, tonumber(synthetic.updatedAt) or 0),
      remoteDomains = {},
      localDomains = {},
      detailDiff = type(synthetic.detailDiff) == "table" and synthetic.detailDiff or nil,
      detailConflict = type(synthetic.detailConflict) == "table" and synthetic.detailConflict or nil,
    }
  end

  local function buildTransferData(profileName, options)
    profileName = trim(profileName)
    options = type(options) == "table" and options or {}
    local subdomains = type(options.subdomains) == "table" and options.subdomains or nil
    local domains = type(options.domains) == "table" and options.domains or nil
    if type(subdomains) == "table" and #subdomains > 0 and type(ExportLootProfileSubdomainSnapshot) == "function" then
      local data = ExportLootProfileSubdomainSnapshot(profileName, subdomains)
      return data and "SUBDOMAINS" or nil, data
    end
    if type(domains) == "table" and #domains > 0 and type(ExportLootProfileDomainSnapshot) == "function" then
      local data = ExportLootProfileDomainSnapshot(profileName, domains)
      return data and "DOMAINS" or nil, data
    end
    if type(ExportLootProfileSnapshot) == "function" then
      local data = ExportLootProfileSnapshot(profileName)
      return data and "FULL" or nil, data
    end
    return nil, nil
  end

  local function buildPreviewSummary(hostProfileName, transferKind, dataStr)
    if transferKind == "SUBDOMAINS" then
      local summary = type(PreviewLootProfileSubdomainSnapshot) == "function" and PreviewLootProfileSubdomainSnapshot(dataStr) or nil
      local diff = type(BuildLootProfileSubdomainSnapshotDiff) == "function" and BuildLootProfileSubdomainSnapshotDiff(hostProfileName, dataStr) or nil
      return summary, diff
    elseif transferKind == "DOMAINS" then
      local summary = type(PreviewLootProfileDomainSnapshot) == "function" and PreviewLootProfileDomainSnapshot(dataStr) or nil
      local diff = type(BuildLootProfileDomainSnapshotDiff) == "function" and BuildLootProfileDomainSnapshotDiff(hostProfileName, dataStr) or nil
      return summary, diff
    end
    local summary = type(PreviewLootProfileSnapshot) == "function" and PreviewLootProfileSnapshot(dataStr) or nil
    local diff = type(BuildLootProfileSnapshotDiff) == "function" and BuildLootProfileSnapshotDiff(hostProfileName, dataStr) or nil
    return summary, diff
  end

  local function requestSyntheticSubchecks(memberKey)
    local store = ensureStore()
    local synthetic = getSyntheticSession()
    if not synthetic then
      setSyntheticRuntimeState(store, "error", "No developer synthetic session is active.")
      return false, "No developer synthetic session is active."
    end
    local requestedKey = trim(memberKey)
    local loadedCount = 0
    if requestedKey ~= "" then
      if trim(type(synthetic.memberProfilesByKey) == "table" and synthetic.memberProfilesByKey[requestedKey] or "") == "" then
        setSyntheticRuntimeState(store, "warn", "That synthetic member has no local shared profile copy yet.")
        return false, "That synthetic member has no local shared profile copy yet."
      end
      synthetic.preciseLoadedByMember[requestedKey] = true
      loadedCount = 1
    else
      for candidateKey, memberProfileName in pairs(synthetic.memberProfilesByKey or {}) do
        if trim(memberProfileName) ~= "" then
          synthetic.preciseLoadedByMember[candidateKey] = true
          loadedCount = loadedCount + 1
        end
      end
    end
    clearSyntheticReviewState(synthetic)
    setSyntheticRuntimeState(store, "success", string.format("Loaded precise synthetic diff scopes for %d member(s).", math.max(0, loadedCount)))
    return true
  end

  local function requestSyntheticSnapshot(memberKey, options)
    local store = ensureStore()
    local synthetic = getSyntheticSession()
    if not synthetic then
      setSyntheticRuntimeState(store, "error", "No developer synthetic session is active.")
      return false, "No developer synthetic session is active."
    end
    local resolvedMemberKey = trim(memberKey)
    if resolvedMemberKey == "" then
      setSyntheticRuntimeState(store, "warn", "Select a synthetic member first.")
      return false, "Select a synthetic member first."
    end
    local memberProfileName = trim(type(synthetic.memberProfilesByKey) == "table" and synthetic.memberProfilesByKey[resolvedMemberKey] or "")
    if memberProfileName == "" then
      setSyntheticRuntimeState(store, "warn", "That synthetic member does not have a local shared profile copy yet.")
      return false, "That synthetic member does not have a local shared profile copy yet."
    end
    options = type(options) == "table" and options or {}
    local transferKind, dataStr = buildTransferData(memberProfileName, options)
    if trim(transferKind) == "" or type(dataStr) ~= "string" then
      setSyntheticRuntimeState(store, "error", "Could not export synthetic member repair data.")
      return false, "Could not export synthetic member repair data."
    end

    local previewSummary, detailDiff = buildPreviewSummary(synthetic.hostProfileName, transferKind, dataStr)
    local detailConflict = type(BuildLootProfileTransferConflictPreview) == "function" and BuildLootProfileTransferConflictPreview(synthetic.hostProfileName, dataStr) or nil
    synthetic.detailSnapshotData = dataStr
    synthetic.detailPreviewSummary = type(previewSummary) == "table" and previewSummary or nil
    synthetic.detailBaseSummary = buildSummary(synthetic.hostProfileName)
    synthetic.detailDiff = type(detailDiff) == "table" and detailDiff or nil
    if type(synthetic.detailDiff) == "table" then
      synthetic.detailDiff.memberKey = resolvedMemberKey
    end
    synthetic.detailConflict = type(detailConflict) == "table" and detailConflict.totalRows and detailConflict.totalRows > 0 and detailConflict or nil
    if type(synthetic.detailConflict) == "table" then
      synthetic.detailConflict.memberKey = resolvedMemberKey
    end
    synthetic.reviewMemberKey = resolvedMemberKey
    setSyntheticRuntimeState(store, "success", "Previewed synthetic member repair data.")
    return true
  end

  local function importTransferIntoProfile(profileName, transferKind, dataStr, expectedProfileId, sourceCharacter)
    if transferKind == "SUBDOMAINS" and type(ImportLootProfileSubdomainSnapshot) == "function" then
      return ImportLootProfileSubdomainSnapshot(profileName, dataStr, {
        expectedProfileId = expectedProfileId,
        sourceCharacter = sourceCharacter,
      })
    elseif transferKind == "DOMAINS" and type(ImportLootProfileDomainSnapshot) == "function" then
      return ImportLootProfileDomainSnapshot(profileName, dataStr, {
        expectedProfileId = expectedProfileId,
        sourceCharacter = sourceCharacter,
      })
    elseif type(ImportLootProfileSnapshot) == "function" then
      return ImportLootProfileSnapshot(profileName, dataStr, {
        expectedProfileId = expectedProfileId,
        sourceCharacter = sourceCharacter,
      })
    end
    return false, "No suitable import API was available."
  end

  local function pullSyntheticRepair(memberKey, options)
    local store = ensureStore()
    local synthetic = getSyntheticSession()
    if not synthetic then
      setSyntheticRuntimeState(store, "error", "No developer synthetic session is active.")
      return false, "No developer synthetic session is active."
    end
    local resolvedMemberKey = trim(memberKey)
    local memberProfileName = trim(type(synthetic.memberProfilesByKey) == "table" and synthetic.memberProfilesByKey[resolvedMemberKey] or "")
    if resolvedMemberKey == "" or memberProfileName == "" then
      setSyntheticRuntimeState(store, "warn", "Select a synthetic member with a local shared profile copy.")
      return false, "Select a synthetic member with a local shared profile copy."
    end
    local hostSummary = buildSummary(synthetic.hostProfileName)
    local transferKind, dataStr = buildTransferData(memberProfileName, options)
    if trim(transferKind) == "" or type(dataStr) ~= "string" then
      setSyntheticRuntimeState(store, "error", "Could not export the synthetic member repair data.")
      return false, "Could not export the synthetic member repair data."
    end
    if type(PushUndoSnapshot) == "function" then
      PushUndoSnapshot(synthetic.hostProfileName, {
        memberKey = resolvedMemberKey,
        profileId = hostSummary.profileId,
        summary = "Synthetic member pull repair",
        kind = "synthetic_pull",
      })
    end
    local ok, err = importTransferIntoProfile(synthetic.hostProfileName, transferKind, dataStr, hostSummary.profileId, resolvedMemberKey)
    if not ok then
      setSyntheticRuntimeState(store, "error", tostring(err or "Could not apply the synthetic member repair."))
      return false, err or "Could not apply the synthetic member repair."
    end
    refreshSyntheticSessionMembers(synthetic)
    clearSyntheticReviewState(synthetic)
    if type(RecordRepairHistory) == "function" then
      RecordRepairHistory({
        profileName = synthetic.hostProfileName,
        sessionId = synthetic.activeSession.id,
        memberKey = resolvedMemberKey,
        kind = "synthetic_pull",
        summary = "Pulled synthetic member changes into the scratch host profile.",
        createdAt = now(),
      })
    end
    setSyntheticRuntimeState(store, "success", "Pulled synthetic member repair into the scratch host profile.")
    return true
  end

  local function pushSyntheticRepair(targetMemberKey, options)
    local store = ensureStore()
    local synthetic = getSyntheticSession()
    if not synthetic then
      setSyntheticRuntimeState(store, "error", "No developer synthetic session is active.")
      return false, "No developer synthetic session is active."
    end

    local hostSummary = buildSummary(synthetic.hostProfileName)
    local candidates = buildSyntheticCandidates()
    local candidateByKey = {}
    for _, candidate in ipairs(candidates) do
      candidateByKey[candidate.memberKey] = candidate
    end

    local targets = {}
    local requestedTarget = trim(targetMemberKey)
    if requestedTarget ~= "" then
      targets[1] = requestedTarget
    else
      for _, candidate in ipairs(candidates) do
        if trim(candidate.comparison) ~= "same" then
          targets[#targets + 1] = candidate.memberKey
        end
      end
    end
    if #targets == 0 then
      setSyntheticRuntimeState(store, "warn", "No synthetic members currently require a host repair.")
      return false, "No synthetic members require a host repair."
    end

    local pushedCount = 0
    for _, memberKey in ipairs(targets) do
      local memberProfileName = trim(type(synthetic.memberProfilesByKey) == "table" and synthetic.memberProfilesByKey[memberKey] or "")
      local candidate = candidateByKey[memberKey]
      if memberProfileName == "" or trim(type(candidate) == "table" and candidate.comparison or "") == "different_lineage" then
        local freshProfileName = memberProfileName ~= "" and memberProfileName or buildHiddenProfileName(synthetic.runId, "MEMBER", #targets + pushedCount + 100)
        local ok, err = cloneProfile(synthetic.hostProfileName, freshProfileName)
        if ok then
          synthetic.memberProfilesByKey[memberKey] = freshProfileName
          synthetic.memberKindsByKey[memberKey] = "aligned"
          pushedCount = pushedCount + 1
          if type(RecordRepairHistory) == "function" then
            RecordRepairHistory({
              profileName = synthetic.hostProfileName,
              sessionId = synthetic.activeSession.id,
              memberKey = memberKey,
              kind = "synthetic_push",
              summary = "Pushed scratch host repair to a synthetic member.",
              createdAt = now(),
            })
          end
        elseif type(Print) == "function" then
          Print(tostring(err or ("Could not refresh " .. memberKey)))
        end
      else
        local scopedOptions = type(options) == "table" and options or nil
        if type(scopedOptions) ~= "table" and type(candidate) == "table" then
          if candidate.precisePushReady and type(candidate.precisePushSubdomains) == "table" and #candidate.precisePushSubdomains > 0 then
            scopedOptions = { subdomains = candidate.precisePushSubdomains }
          elseif type(candidate.hostRepairDomains) == "table" and #candidate.hostRepairDomains > 0 then
            scopedOptions = { domains = candidate.hostRepairDomains }
          end
        end
        local transferKind, dataStr = buildTransferData(synthetic.hostProfileName, scopedOptions)
        if trim(transferKind) ~= "" and type(dataStr) == "string" then
          local ok = importTransferIntoProfile(memberProfileName, transferKind, dataStr, hostSummary.profileId, synthetic.selfKey)
          if ok then
            synthetic.memberKindsByKey[memberKey] = "aligned"
            pushedCount = pushedCount + 1
            if type(RecordRepairHistory) == "function" then
              RecordRepairHistory({
                profileName = synthetic.hostProfileName,
                sessionId = synthetic.activeSession.id,
                memberKey = memberKey,
                kind = "synthetic_push",
                summary = "Pushed scratch host repair to a synthetic member.",
                createdAt = now(),
              })
            end
          end
        end
      end
    end

    refreshSyntheticSessionMembers(synthetic)
    clearSyntheticReviewState(synthetic)
    setSyntheticRuntimeState(store, "success", string.format("Pushed scratch host repair to %d synthetic member(s).", math.max(0, pushedCount)))
    return pushedCount > 0, pushedCount > 0 and pushedCount or "No synthetic member repair was applied."
  end

  local function prepareSyntheticSession()
    local store = ensureStore()
    local synthetic = getSyntheticSession()
    if not synthetic then
      return false, "No developer synthetic session is active."
    end
    synthetic.activeSession.status = "PREPARING"
    synthetic.activeSession.endedAt = nil
    synthetic.updatedAt = now()
    clearSyntheticReviewState(synthetic)
    refreshSyntheticSessionMembers(synthetic)
    setSyntheticRuntimeState(store, "info", "Developer synthetic session prepared. Start Session will make the scratch host copy authoritative.")
    return true
  end

  local function activateSyntheticSession()
    local store = ensureStore()
    local synthetic = getSyntheticSession()
    if not synthetic then
      return false, "No developer synthetic session is active."
    end
    synthetic.activeSession.status = "ACTIVE"
    synthetic.activeSession.startedAt = math.max(1, tonumber(synthetic.activeSession.startedAt) or now())
    synthetic.activeSession.endedAt = nil
    synthetic.updatedAt = now()

    local repairedCount = 0
    for _, candidate in ipairs(buildSyntheticCandidates()) do
      if trim(candidate.comparison) ~= "same" then
        local ok, result = pushSyntheticRepair(nil)
        if ok then
          repairedCount = math.max(0, tonumber(result) or 0)
        end
        break
      end
    end
    refreshSyntheticSessionMembers(synthetic)
    clearSyntheticReviewState(synthetic)
    if repairedCount > 0 then
      setSyntheticRuntimeState(store, "success", string.format(
        "Developer synthetic session started. The scratch host copy is now authoritative and aligned %d synthetic member(s).",
        repairedCount
      ))
    else
      setSyntheticRuntimeState(store, "success", "Developer synthetic session started. The scratch host copy is now authoritative and all synthetic members are already aligned.")
    end
    return true
  end

  local function stopSyntheticSession()
    local store = ensureStore()
    local synthetic = getSyntheticSession()
    if not synthetic then
      return false, "No developer synthetic session is active."
    end
    synthetic.activeSession.status = "FINISHED"
    synthetic.activeSession.endedAt = now()
    synthetic.updatedAt = synthetic.activeSession.endedAt
    clearSyntheticReviewState(synthetic)
    refreshSyntheticSessionMembers(synthetic)
    setSyntheticRuntimeState(store, "info", "Developer synthetic session stopped. Prepare it again or clear the harness to remove the scratch session.")
    return true
  end

  local function getConflictPreview(memberKey)
    local synthetic = getSyntheticSession()
    if not synthetic then
      return nil
    end
    if type(synthetic.detailConflict) ~= "table" then
      return nil
    end
    if trim(memberKey) ~= "" and lowerKey(memberKey) ~= lowerKey(synthetic.detailConflict.memberKey) then
      return nil
    end
    return synthetic.detailConflict
  end

  local function applyConflictResolution(memberKey, resolution)
    local store = ensureStore()
    local synthetic = getSyntheticSession()
    if not synthetic then
      setSyntheticRuntimeState(store, "error", "No developer synthetic session is active.")
      return false, "No developer synthetic session is active."
    end
    if type(synthetic.detailConflict) ~= "table" or type(synthetic.detailSnapshotData) ~= "string" then
      setSyntheticRuntimeState(store, "warn", "No synthetic preview conflict is loaded.")
      return false, "No synthetic preview conflict is loaded."
    end
    local resolvedMemberKey = trim(memberKey)
    if resolvedMemberKey == "" or lowerKey(resolvedMemberKey) ~= lowerKey(synthetic.detailConflict.memberKey) then
      setSyntheticRuntimeState(store, "warn", "That synthetic preview no longer matches the selected member.")
      return false, "That synthetic preview no longer matches the selected member."
    end
    local hostSummary = buildSummary(synthetic.hostProfileName)
    if type(PushUndoSnapshot) == "function" then
      PushUndoSnapshot(synthetic.hostProfileName, {
        memberKey = resolvedMemberKey,
        profileId = hostSummary.profileId,
        summary = "Synthetic preview conflict resolution",
        kind = "synthetic_preview_apply",
      })
    end
    local ok, result
    if type(ApplyLootProfileTransferConflictResolution) == "function" then
      ok, result = ApplyLootProfileTransferConflictResolution(synthetic.hostProfileName, synthetic.detailSnapshotData, resolution, {
        expectedProfileId = hostSummary.profileId,
        sourceCharacter = resolvedMemberKey,
      })
    else
      ok, result = false, "Synthetic conflict resolution API unavailable."
    end
    if not ok then
      setSyntheticRuntimeState(store, "error", tostring(result or "Could not apply the synthetic preview conflict resolution."))
      return false, result or "Could not apply the synthetic preview conflict resolution."
    end
    refreshSyntheticSessionMembers(synthetic)
    clearSyntheticReviewState(synthetic)
    if type(RecordRepairHistory) == "function" then
      RecordRepairHistory({
        profileName = synthetic.hostProfileName,
        sessionId = synthetic.activeSession.id,
        memberKey = resolvedMemberKey,
        kind = "synthetic_preview_apply",
        summary = "Applied selected synthetic preview rows to the scratch host profile.",
        createdAt = now(),
      })
    end
    if type(result) == "table" and ((type(result.subdomains) == "table" and #result.subdomains > 0) or (type(result.domains) == "table" and #result.domains > 0)) then
      pushSyntheticRepair(nil, {
        domains = result.domains,
        subdomains = result.subdomains,
      })
    else
      setSyntheticRuntimeState(store, "success", "Applied selected synthetic preview rows to the scratch host profile.")
    end
    return true, result
  end

  local function runHarness(opts)
    local store = ensureStore()
    local report, err = buildHarnessReport(opts)
    if not report then
      return false, err
    end
    local ok, syntheticErr = buildSyntheticSession(report)
    if not ok then
      return false, syntheticErr or "Could not create the synthetic developer session."
    end
    store.profileMode = report.requestedProfileMode
    store.scenario = report.scenario
    store.memberCount = report.memberCount
    store.lastRunAt = report.generatedAt
    store.lastReport = report
    return true, report
  end

  local function clearHarness()
    local store = ensureStore()
    clearSyntheticSessionState(store)
    store.lastRunAt = nil
    store.lastReport = nil
    store.lastAutomatedValidation = nil
    store.automatedValidationHistory = nil
    return true
  end

  local function getHarnessState()
    local store = ensureStore()
    local synthetic = getSyntheticSession()
    return {
      profileMode = resolveProfileMode(store.profileMode),
      scenario = resolveScenario(store.scenario),
      memberCount = resolveMemberCount(store.memberCount),
      lastRunAt = math.max(0, tonumber(store.lastRunAt) or 0),
      lastReport = type(store.lastReport) == "table" and store.lastReport or nil,
      lastAutomatedValidation = type(store.lastAutomatedValidation) == "table" and store.lastAutomatedValidation or nil,
      automatedValidationHistory = type(store.automatedValidationHistory) == "table" and copy(store.automatedValidationHistory) or {},
      syntheticActive = type(synthetic) == "table" and synthetic.active == true or false,
      syntheticProfileName = trim(type(synthetic) == "table" and synthetic.sourceProfileName or ""),
      syntheticScenario = trim(type(synthetic) == "table" and store.scenario or ""),
      syntheticMemberCount = type(synthetic) == "table" and math.max(0, tonumber(store.memberCount) or 0) or 0,
    }
  end

  return {
    RunHarness = runHarness,
    RunAutomatedValidation = function(options)
      options = type(options) == "table" and options or {}
      local includeCommunicationSuites = options.includeCommunicationSuites ~= false
      local persistReport = options.persistReport ~= false
      local workflow6FaultMatrixEvidence = {}
      local checks = {}
      local passedCount = 0
      local function addCheck(name, expected, actual)
        local passed = expected == actual
        checks[#checks + 1] = {
          name = name,
          passed = passed,
          expected = tostring(expected),
          actual = tostring(actual),
        }
        if passed then
          passedCount = passedCount + 1
        end
      end

      local checkRegistry = {
        { name = "profile mode normalization", expected = "CURRENT", run = function() return resolveProfileMode("current") end },
        { name = "profile mode fallback", expected = DEFAULT_PROFILE_MODE, run = function() return resolveProfileMode("invalid") end },
        { name = "scenario normalization", expected = "MIXED", run = function() return resolveScenario("mixed") end },
        { name = "scenario fallback", expected = DEFAULT_SCENARIO, run = function() return resolveScenario("invalid") end },
        { name = "member count lower bound", expected = DEFAULT_MEMBER_COUNT, run = function() return resolveMemberCount(0) end },
        { name = "member count upper bound", expected = 40, run = function() return resolveMemberCount(99) end },
        {
          name = "fresh scenario counts",
          expected = "20/0",
          run = function()
            local freshCount, alignedCount = buildScenarioCounts("FRESH", 20)
            return tostring(freshCount) .. "/" .. tostring(alignedCount)
          end,
        },
        {
          name = "returning scenario counts",
          expected = "0/20",
          run = function()
            local freshCount, alignedCount = buildScenarioCounts("RETURNING", 20)
            return tostring(freshCount) .. "/" .. tostring(alignedCount)
          end,
        },
        {
          name = "mixed scenario counts",
          expected = "5/15",
          run = function()
            local freshCount, alignedCount = buildScenarioCounts("MIXED", 20)
            return tostring(freshCount) .. "/" .. tostring(alignedCount)
          end,
        },
        {
          name = "mixed scenario member count",
          expected = 20,
          run = function()
            return #buildScenarioKinds("MIXED", 20)
          end,
        },
        {
          name = "mixed scenario coverage",
          expected = "fresh/host_newer/member_newer/diverged",
          run = function()
            local kinds = buildScenarioKinds("MIXED", 20)
            return table.concat({ kinds[1], kinds[2], kinds[3], kinds[4] }, "/")
          end,
        },
        {
          name = "mixed timeline member count",
          expected = 20,
          run = function()
            return #buildMemberTimeline(20, "MIXED", { seconds = 1 }, { seconds = 0.5 }, 0.2)
          end,
        },
        {
          name = "mixed timeline fresh member",
          expected = "fresh",
          run = function()
            local timeline = buildMemberTimeline(20, "MIXED", { seconds = 1 }, { seconds = 0.5 }, 0.2)
            return trim(type(timeline[1]) == "table" and timeline[1].mode or "")
          end,
        },
        {
          name = "mixed timeline aligned member",
          expected = "aligned",
          run = function()
            local timeline = buildMemberTimeline(20, "MIXED", { seconds = 1 }, { seconds = 0.5 }, 0.2)
            return trim(type(timeline[6]) == "table" and timeline[6].mode or "")
          end,
        },
        {
          name = "mixed timeline order",
          expected = true,
          run = function()
            local timeline = buildMemberTimeline(20, "MIXED", { seconds = 1 }, { seconds = 0.5 }, 0.2)
            return (tonumber(type(timeline[5]) == "table" and timeline[5].readyAt or 0) or 0)
              >= (tonumber(type(timeline[1]) == "table" and timeline[1].readyAt or 0) or 0)
          end,
        },
        {
          name = "mixed scenario fresh member parity",
          expected = 5,
          run = function()
            local freshCount = 0
            for _, kind in ipairs(buildScenarioKinds("MIXED", 20)) do
              if kind == "fresh" then
                freshCount = freshCount + 1
              end
            end
            return freshCount
          end,
        },
        {
          name = "current session checksum ignores presentation and timing metadata",
          expected = true,
          run = function()
            local buildSource = deps.BuildLootProfileCurrentSessionChecksumSource
            local checksum = deps.CalculateStableChecksum
            if type(buildSource) ~= "function" or type(checksum) ~= "function" then
              return false
            end
            local base = {
              id = "SESSION-CANONICAL",
              profileName = "Canonical",
              remoteProfileName = "Canonical",
              profileId = "profile-canonical",
              host = "Host-Realm",
              status = "ACTIVE",
              startedAt = 100,
              activatedAt = 110,
              rollOptions = { { id = "need", label = "Need" } },
              members = {
                ["Host-Realm"] = {
                  name = "Host-Realm",
                  status = "JOINED",
                  joinedAt = 100,
                  className = "Mage",
                  specName = "Fire",
                  addonVersion = "old",
                  clientVersion = "old",
                },
              },
            }
            local presentationVariant = copy(base, true)
            presentationVariant.profileName = "Local Replica Alias"
            presentationVariant.startedAt = 999
            presentationVariant.activatedAt = 1000
            presentationVariant.members["Host-Realm"].joinedAt = 777
            presentationVariant.members["Host-Realm"].className = "Warrior"
            presentationVariant.members["Host-Realm"].specName = "Arms"
            presentationVariant.members["Host-Realm"].addonVersion = "new"
            presentationVariant.members["Host-Realm"].clientVersion = "new"
            presentationVariant.members["Host-Realm"].lastSyncAt = 2000
            local localNameBase = copy(base, true)
            localNameBase.remoteProfileName = ""
            local localNameVariant = copy(localNameBase, true)
            localNameVariant.remoteProfileName = nil
            return checksum(buildSource(base)) == checksum(buildSource(presentationVariant))
              and checksum(buildSource(localNameBase)) == checksum(buildSource(localNameVariant))
          end,
        },
        {
          name = "current session checksum detects authoritative state changes",
          expected = true,
          run = function()
            local buildSource = deps.BuildLootProfileCurrentSessionChecksumSource
            local checksum = deps.CalculateStableChecksum
            if type(buildSource) ~= "function" or type(checksum) ~= "function" then
              return false
            end
            local base = {
              id = "SESSION-CANONICAL",
              remoteProfileName = "Canonical",
              profileId = "profile-canonical",
              host = "Host-Realm",
              status = "ACTIVE",
              rollOptions = { { id = "need", label = "Need" } },
              members = {
                ["Host-Realm"] = { status = "JOINED" },
                ["Member-Realm"] = { status = "JOINED" },
              },
            }
            local baseChecksum = checksum(buildSource(base))
            local statusVariant = copy(base, true)
            statusVariant.status = "PREPARING"
            local rosterVariant = copy(base, true)
            rosterVariant.members["Member-Realm"].status = "LEFT"
            local rollVariant = copy(base, true)
            rollVariant.rollOptions[1].label = "Main Need"
            return baseChecksum ~= checksum(buildSource(statusVariant))
              and baseChecksum ~= checksum(buildSource(rosterVariant))
              and baseChecksum ~= checksum(buildSource(rollVariant))
          end,
        },
        {
          name = "saved board checksum ignores transport perspective and presentation state",
          expected = true,
          run = function()
            local buildSource = BuildLootProfileLiveBoardSnapshotChecksumSource
            local checksum = deps.CalculateStableChecksum
            if type(buildSource) ~= "function" or type(checksum) ~= "function" then
              return false
            end
            local base = {
              boardId = "live-SESSION-CANONICAL",
              sessionId = "SESSION-CANONICAL",
              profileName = "Canonical Host Profile",
              historyProfileName = "Canonical Host Profile",
              createdAt = 100,
              updatedAt = 110,
              selectedItemKey = "ITEM-A",
              itemOrder = { "ITEM-A" },
              items = {
                ["ITEM-A"] = {
                  key = "ITEM-A",
                  itemID = 12345,
                  link = "item:12345",
                  icon = 7702759,
                  votesByVoter = { ["Host-Realm"] = "Member-Realm" },
                  hostVoteFor = "Member-Realm",
                  selections = {
                    ["Host-Realm"] = {
                      optionKey = "bis",
                      label = "BiS",
                      selectedAt = 105,
                      selectedSeq = 1,
                      source = "LOCAL",
                    },
                    ["Member-Realm"] = {
                      optionKey = "almost_bis",
                      label = "Almost BiS",
                      selectedAt = 106,
                      selectedSeq = 2,
                      source = "REMOTE",
                    },
                  },
                },
              },
            }
            local mirror = copy(base, true)
            mirror.profileName = "Local Replica Alias"
            mirror.historyProfileName = "Local Replica Alias"
            mirror.updatedAt = 111
            mirror.selectedItemKey = nil
            mirror.items["ITEM-A"].icon = "7702759"
            mirror.items["ITEM-A"].hostVoteFor = "Host-Realm"
            mirror.items["ITEM-A"].selections["Host-Realm"].source = "MIRROR"
            mirror.items["ITEM-A"].selections["Member-Realm"].source = "MIRROR"
            return checksum(buildSource(base)) == checksum(buildSource(mirror))
          end,
        },
        {
          name = "saved board checksum retains gameplay item and choice differences",
          expected = true,
          run = function()
            local buildSource = BuildLootProfileLiveBoardSnapshotChecksumSource
            local checksum = deps.CalculateStableChecksum
            if type(buildSource) ~= "function" or type(checksum) ~= "function" then
              return false
            end
            local base = {
              boardId = "live-SESSION-CONTENT",
              sessionId = "SESSION-CONTENT",
              itemOrder = { "ITEM-A" },
              items = {
                ["ITEM-A"] = {
                  key = "ITEM-A",
                  itemID = 12345,
                  link = "item:12345",
                  selections = {
                    ["Host-Realm"] = { optionKey = "bis", selectedAt = 105, selectedSeq = 1 },
                  },
                },
              },
            }
            local itemVariant = copy(base, true)
            itemVariant.items["ITEM-A"].itemID = 54321
            local choiceVariant = copy(base, true)
            choiceVariant.items["ITEM-A"].selections["Host-Realm"].optionKey = "pass"
            local baseChecksum = checksum(buildSource(base))
            return baseChecksum ~= checksum(buildSource(itemVariant))
              and baseChecksum ~= checksum(buildSource(choiceVariant))
          end,
        },
        {
          name = "saved board checksum excludes Test Raid Items history",
          expected = true,
          run = function()
            local buildSource = BuildLootProfileLiveBoardChecksumSource
            if type(buildSource) ~= "function" then
              return false
            end
            local output = buildSource({
              {
                boardId = "live-SESSION-TEST-EXPLICIT",
                excludeFromHistory = true,
                itemOrder = { "TESTSIM-100-1" },
                items = { ["TESTSIM-100-1"] = { key = "TESTSIM-100-1", itemID = 1 } },
              },
              {
                boardId = "live-SESSION-TEST-KEYED",
                itemOrder = { "TESTSIM-100-2" },
                items = { ["TESTSIM-100-2"] = { key = "TESTSIM-100-2", itemID = 2 } },
              },
            })
            return type(output) == "table" and next(output) == nil
          end,
        },
        {
          name = "P2 current session ignores loot differences",
          expected = "SYNCED",
          run = function()
            if type(deps.CompareMemberPayloadSyncState) ~= "function" then
              return "missing"
            end
            return deps.CompareMemberPayloadSyncState(
              { sessionChecksum = "current-a", lootChecksum = "archive-host" },
              { sessionChecksum = "current-a", lootChecksum = "archive-member" },
              { currentSessionOnly = true }
            )
          end,
        },
        {
          name = "P2 current session detects session state differences",
          expected = "PARTIAL",
          run = function()
            if type(deps.CompareMemberPayloadSyncState) ~= "function" then
              return "missing"
            end
            return deps.CompareMemberPayloadSyncState(
              { sessionChecksum = "current-host", lootChecksum = "archive-same" },
              { sessionChecksum = "current-member", lootChecksum = "archive-same" },
              { currentSessionOnly = true }
            )
          end,
        },
        {
          name = "P2 current session requires exact session proof",
          expected = "PARTIAL",
          run = function()
            if type(deps.CompareMemberPayloadSyncState) ~= "function" then
              return "missing"
            end
            return deps.CompareMemberPayloadSyncState(
              { sessionChecksum = "current-host", lootChecksum = "archive-same" },
              { lootChecksum = "archive-same" },
              { currentSessionOnly = true }
            )
          end,
        },
        {
          name = "readiness matrix rejects stale generations",
          expected = true,
          run = function()
            local result = type(deps.ValidateReadinessProofLifecycle) == "function"
              and deps.ValidateReadinessProofLifecycle()
              or {}
            return result.staleGenerationRejected == true
          end,
        },
        {
          name = "readiness matrix rejects same-generation rewrites",
          expected = true,
          run = function()
            local result = type(deps.ValidateReadinessProofLifecycle) == "function"
              and deps.ValidateReadinessProofLifecycle()
              or {}
            return result.equalGenerationRewriteRejected == true
          end,
        },
        {
          name = "readiness matrix accepts newer generations",
          expected = true,
          run = function()
            local result = type(deps.ValidateReadinessProofLifecycle) == "function"
              and deps.ValidateReadinessProofLifecycle()
              or {}
            return result.newerGenerationAccepted == true
          end,
        },
        {
          name = "readiness matrix generation is monotonic",
          expected = true,
          run = function()
            local result = type(deps.ValidateReadinessProofLifecycle) == "function"
              and deps.ValidateReadinessProofLifecycle()
              or {}
            return result.generatedMatrixIsMonotonic == true
              and result.legacyMatrixCannotReplaceGeneratedState == true
          end,
        },
        {
          name = "accepted readiness proof is immutable",
          expected = true,
          run = function()
            local result = type(deps.ValidateReadinessProofLifecycle) == "function"
              and deps.ValidateReadinessProofLifecycle()
              or {}
            return result.acceptedProofIsImmutable == true
          end,
        },
        {
          name = "new lobby does not reuse readiness proof",
          expected = true,
          run = function()
            local result = type(deps.ValidateReadinessProofLifecycle) == "function"
              and deps.ValidateReadinessProofLifecycle()
              or {}
            return result.newLobbyDoesNotReuseProof == true
          end,
        },
        {
          name = "missing readiness proof displays validating",
          expected = "VALIDATING",
          run = function()
            local result = type(deps.ValidateReadinessProofLifecycle) == "function"
              and deps.ValidateReadinessProofLifecycle()
              or {}
            return result.missingProofState or "missing"
          end,
        },
        {
          name = "readiness matrix round-trips yellow stale archive state",
          expected = true,
          run = function()
            local result = type(deps.ValidateReadinessProofLifecycle) == "function"
              and deps.ValidateReadinessProofLifecycle()
              or {}
            return result.staleArchiveMatrixRoundTrips == true
          end,
        },
        {
          name = "duplicate local readiness proof is coalesced",
          expected = true,
          run = function()
            local shouldSuppress = deps.ShouldSuppressLocalProfileStateSend
            if type(shouldSuppress) ~= "function" then
              return "missing"
            end
            return shouldSuppress(
              { signature = "proof-a", sentAt = 99.5 },
              "proof-a",
              100,
              1,
              false
            ) == true
          end,
        },
        {
          name = "forced readiness proof bypasses duplicate coalescing",
          expected = true,
          run = function()
            local shouldSuppress = deps.ShouldSuppressLocalProfileStateSend
            if type(shouldSuppress) ~= "function" then
              return "missing"
            end
            return shouldSuppress(
              { signature = "proof-a", sentAt = 99.5 },
              "proof-a",
              100,
              1,
              true
            ) == false
          end,
        },
        {
          name = "expired readiness proof is sent again",
          expected = true,
          run = function()
            local shouldSuppress = deps.ShouldSuppressLocalProfileStateSend
            if type(shouldSuppress) ~= "function" then
              return "missing"
            end
            return shouldSuppress(
              { signature = "proof-a", sentAt = 98 },
              "proof-a",
              100,
              1,
              false
            ) == false
          end,
        },
        {
          name = "mixed scenario 5-10-20 fresh parity",
          expected = "1/1/3/3/5/5",
          run = function()
            local values = {}
            for _, memberCount in ipairs({ 5, 10, 20 }) do
              local actualFresh = 0
              for _, kind in ipairs(buildScenarioKinds("MIXED", memberCount)) do
                if kind == "fresh" then
                  actualFresh = actualFresh + 1
                end
              end
              local expectedFresh = select(1, buildScenarioCounts("MIXED", memberCount))
              values[#values + 1] = tostring(actualFresh)
              values[#values + 1] = tostring(expectedFresh)
            end
            return table.concat(values, "/")
          end,
        },
        {
          name = "stateful fresh join snapshot coverage",
          expected = "4/4/1/true",
          run = function()
            local fresh = buildStatefulTransferMatrix().freshJoin
            return table.concat({
              tostring(fresh.scheduledDomainTransfers),
              tostring(fresh.copiedDomains),
              tostring(fresh.acknowledgements),
              tostring(fresh.converged),
            }, "/")
          end,
        },
        {
          name = "stateful returning join one-domain delta",
          expected = "delta/1/1/1/true",
          run = function()
            local returning = buildStatefulTransferMatrix().returningJoin
            return table.concat({
              tostring(returning.mode),
              tostring(returning.scheduledDomainTransfers),
              tostring(returning.copiedDomains),
              tostring(returning.acknowledgements),
              tostring(returning.converged),
            }, "/")
          end,
        },
        {
          name = "stateful mixed join transfer plan",
          expected = "5/4/4/4/3",
          run = function()
            local summary = buildStatefulTransferMatrix().mixedJoin.summary
            return table.concat({
              tostring(summary.freshSnapshots),
              tostring(summary.hostDeltas),
              tostring(summary.memberUploads),
              tostring(summary.conflicts),
              tostring(summary.aligned),
            }, "/")
          end,
        },
        {
          name = "stateful mixed join changed-domain schedule",
          expected = "28/13/0",
          run = function()
            local summary = buildStatefulTransferMatrix().mixedJoin.summary
            return table.concat({
              tostring(summary.scheduledDomainTransfers),
              tostring(summary.acknowledgements),
              tostring(summary.unchangedDomainTransfers),
            }, "/")
          end,
        },
        {
          name = "stateful host fanout 5-10-20 domains",
          expected = "5/10/20",
          run = function()
            local matrix = buildStatefulTransferMatrix().hostFanout
            return table.concat({
              tostring(matrix[5].scheduledDomainTransfers),
              tostring(matrix[10].scheduledDomainTransfers),
              tostring(matrix[20].scheduledDomainTransfers),
            }, "/")
          end,
        },
        {
          name = "stateful host fanout 5-10-20 ACKs",
          expected = "5/10/20",
          run = function()
            local matrix = buildStatefulTransferMatrix().hostFanout
            return table.concat({
              tostring(matrix[5].acknowledgements),
              tostring(matrix[10].acknowledgements),
              tostring(matrix[20].acknowledgements),
            }, "/")
          end,
        },
        {
          name = "stateful host fanout convergence",
          expected = "true/true/true",
          run = function()
            local matrix = buildStatefulTransferMatrix().hostFanout
            return table.concat({
              tostring(matrix[5].converged),
              tostring(matrix[10].converged),
              tostring(matrix[20].converged),
            }, "/")
          end,
        },
        {
          name = "stateful member fanout 5-10-20 domains",
          expected = "5/10/20",
          run = function()
            local matrix = buildStatefulTransferMatrix().memberFanout
            return table.concat({
              tostring(matrix[5].scheduledDomainTransfers),
              tostring(matrix[10].scheduledDomainTransfers),
              tostring(matrix[20].scheduledDomainTransfers),
            }, "/")
          end,
        },
        {
          name = "stateful member fanout relay counts",
          expected = "4/9/19",
          run = function()
            local matrix = buildStatefulTransferMatrix().memberFanout
            return table.concat({
              tostring(matrix[5].relayDomainTransfers),
              tostring(matrix[10].relayDomainTransfers),
              tostring(matrix[20].relayDomainTransfers),
            }, "/")
          end,
        },
        {
          name = "stateful member fanout 5-10-20 ACKs",
          expected = "5/10/20",
          run = function()
            local matrix = buildStatefulTransferMatrix().memberFanout
            return table.concat({
              tostring(matrix[5].acknowledgements),
              tostring(matrix[10].acknowledgements),
              tostring(matrix[20].acknowledgements),
            }, "/")
          end,
        },
        {
          name = "stateful member fanout convergence",
          expected = "true/true/true",
          run = function()
            local matrix = buildStatefulTransferMatrix().memberFanout
            return table.concat({
              tostring(matrix[5].converged),
              tostring(matrix[10].converged),
              tostring(matrix[20].converged),
            }, "/")
          end,
        },
        {
          name = "stateful inbound snapshot lifecycle cleanup",
          expected = "1/0/1",
          run = function()
            local stagedTransfers = {
              previous = { sessionId = "previous-session", receivedChunkCount = 1 },
              current = { sessionId = "current-session", receivedChunkCount = 1 },
            }
            if type(ClearIncomingProfileSyncsForSession) ~= "function" then
              return "missing"
            end
            local removed = ClearIncomingProfileSyncsForSession(stagedTransfers, "previous-session", trim)
            return table.concat({
              tostring(removed),
              tostring(stagedTransfers.previous == nil and 0 or 1),
              tostring(stagedTransfers.current ~= nil and 1 or 0),
            }, "/")
          end,
        },
        {
          name = "stateful inbound snapshot cleanup ignores other sessions",
          expected = "0/1",
          run = function()
            local stagedTransfers = {
              current = { sessionId = "current-session", receivedChunkCount = 1 },
            }
            if type(ClearIncomingProfileSyncsForSession) ~= "function" then
              return "missing"
            end
            local removed = ClearIncomingProfileSyncsForSession(stagedTransfers, "previous-session", trim)
            return table.concat({
              tostring(removed),
              tostring(stagedTransfers.current ~= nil and 1 or 0),
            }, "/")
          end,
        },
        {
          name = "stateful inbound snapshot cleanup removes all ended-session transfers",
          expected = "2/0/1",
          run = function()
            local stagedTransfers = {
              previousOne = { sessionId = "previous-session", receivedChunkCount = 1 },
              previousTwo = { sessionId = "previous-session", receivedChunkCount = 2 },
              current = { sessionId = "current-session", receivedChunkCount = 1 },
            }
            if type(ClearIncomingProfileSyncsForSession) ~= "function" then
              return "missing"
            end
            local removed = ClearIncomingProfileSyncsForSession(stagedTransfers, "previous-session", trim)
            return table.concat({
              tostring(removed),
              tostring(stagedTransfers.previousOne == nil and stagedTransfers.previousTwo == nil and 0 or 1),
              tostring(stagedTransfers.current ~= nil and 1 or 0),
            }, "/")
          end,
        },
        {
          name = "stateful inbound snapshot finalizer bounds unique cleanup history",
          expected = "2/1/5/previous-session/2/8/1",
          run = function()
            local sessionState = {
              pendingProfileSyncs = {
                previousOne = { sessionId = "previous-session", receivedChunkCount = 1 },
                previousTwo = { sessionId = "previous-session", receivedChunkCount = 2 },
                current = { sessionId = "current-session", receivedChunkCount = 1 },
              },
              incomingSnapshotCleanupTotal = 3,
              incomingSnapshotCleanupHistory = {
                { sessionId = "previous-session", count = 1, at = 1 },
                { sessionId = "retained-one", count = 1, at = 2 },
                { sessionId = "retained-two", count = 1, at = 3 },
                { sessionId = "retained-three", count = 1, at = 4 },
                { sessionId = "retained-four", count = 1, at = 5 },
                { sessionId = "retained-five", count = 1, at = 6 },
                { sessionId = "retained-six", count = 1, at = 7 },
                { sessionId = "retained-seven", count = 1, at = 8 },
              },
              maxIncomingSnapshotCleanupHistory = 8,
            }
            local finalizer = deps.FinalizeIncomingProfileSyncSessionState
            if type(finalizer) ~= "function" then
              return "missing"
            end
            local removed = finalizer(sessionState, "previous-session", 200, trim)
            local latestCleanup = sessionState.incomingSnapshotCleanupHistory[1] or {}
            local matchingCleanupEntries = 0
            for _, cleanup in ipairs(sessionState.incomingSnapshotCleanupHistory) do
              if trim(type(cleanup) == "table" and cleanup.sessionId or "") == "previous-session" then
                matchingCleanupEntries = matchingCleanupEntries + 1
              end
            end
            return table.concat({
              tostring(removed),
              tostring(sessionState.pendingProfileSyncs.current ~= nil and 1 or 0),
              tostring(sessionState.incomingSnapshotCleanupTotal),
              trim(latestCleanup.sessionId),
              tostring(latestCleanup.count),
              tostring(#sessionState.incomingSnapshotCleanupHistory),
              tostring(matchingCleanupEntries),
            }, "/")
          end,
        },
        {
          name = "stateful inbound snapshot finalizer keeps state unchanged without matching transfer",
          expected = "0/1/3/current-session/1",
          run = function()
            local sessionState = {
              pendingProfileSyncs = {
                current = { sessionId = "current-session", receivedChunkCount = 1 },
              },
              incomingSnapshotCleanupTotal = 3,
              lastIncomingSnapshotCleanupCount = 1,
              lastIncomingSnapshotCleanupSessionId = "current-session",
              lastIncomingSnapshotCleanupAt = 100,
              incomingSnapshotCleanupHistory = {
                { sessionId = "current-session", count = 1, at = 100 },
              },
              maxIncomingSnapshotCleanupHistory = 8,
            }
            local finalizer = deps.FinalizeIncomingProfileSyncSessionState
            if type(finalizer) ~= "function" then
              return "missing"
            end
            local removed = finalizer(sessionState, "previous-session", 200, trim)
            return table.concat({
              tostring(removed),
              tostring(sessionState.pendingProfileSyncs.current ~= nil and 1 or 0),
              tostring(sessionState.incomingSnapshotCleanupTotal),
              trim(sessionState.lastIncomingSnapshotCleanupSessionId),
              tostring(#sessionState.incomingSnapshotCleanupHistory),
            }, "/")
          end,
        },
        {
          name = "stateful inbound snapshot transfer resolver rejects delayed and foreign packets",
          expected = "missing_transfer/sender_mismatch/matched",
          run = function()
            local resolver = deps.ResolveIncomingProfileSyncTransfer
            if type(resolver) ~= "function" then
              return "missing"
            end
            local pendingTransfers = {
              active = { sender = "Host-Realm", sessionId = "current-session" },
            }
            local _, missingReason = resolver(pendingTransfers, "cleared", "Host-Realm", trim)
            local _, foreignReason = resolver(pendingTransfers, "active", "Other-Realm", trim)
            local matchedState, matchedReason = resolver(pendingTransfers, "active", "Host-Realm", trim)
            return table.concat({
              missingReason,
              foreignReason,
              type(matchedState) == "table" and matchedReason or "missing",
            }, "/")
          end,
        },
        {
          name = "stateful inbound snapshot reject telemetry bounds reasons and deduplicates history",
          expected = "true/4/2/1/1/3/reason_c/1",
          run = function()
            local recorder = deps.RecordIncomingSnapshotReject
            if type(recorder) ~= "function" then
              return "missing"
            end
            local sessionState = {
              incomingSnapshotRejectHistory = {},
              maxIncomingSnapshotRejectHistory = 3,
              maxIncomingSnapshotRejectReasons = 2,
            }
            local accepted = recorder(sessionState, "PSYNC_CHUNK", "Host-Realm", { "PSYNC_CHUNK", "transfer-a" }, "reason_a", 100, trim)
            recorder(sessionState, "PSYNC_CHUNK", "Host-Realm", { "PSYNC_CHUNK", "transfer-a" }, "reason_a", 101, trim)
            recorder(sessionState, "PSYNC_CHUNK", "Host-Realm", { "PSYNC_CHUNK", "transfer-b" }, "reason_b", 102, trim)
            recorder(sessionState, "PSYNC_CHUNK", "Host-Realm", { "PSYNC_CHUNK", "transfer-c" }, "reason_c", 103, trim)
            local retainedReasonACount = 0
            for _, entry in ipairs(sessionState.incomingSnapshotRejectHistory) do
              if trim(type(entry) == "table" and entry.reason or "") == "reason_a" then
                retainedReasonACount = retainedReasonACount + 1
              end
            end
            return table.concat({
              tostring(accepted),
              tostring(math.max(0, tonumber(sessionState.incomingSnapshotRejectTotal) or 0)),
              tostring(math.max(0, tonumber(sessionState.incomingSnapshotRejectCounts.reason_a) or 0)),
              tostring(math.max(0, tonumber(sessionState.incomingSnapshotRejectCounts.reason_b) or 0)),
              tostring(math.max(0, tonumber(sessionState.incomingSnapshotRejectCounts.other) or 0)),
              tostring(#sessionState.incomingSnapshotRejectHistory),
              trim(type(sessionState.incomingSnapshotRejectHistory[1]) == "table" and sessionState.incomingSnapshotRejectHistory[1].reason or ""),
              tostring(retainedReasonACount),
            }, "/")
          end,
        },
        {
          name = "stateful inbound snapshot diagnostic rollover clears only the new session scope",
          expected = "true/false/true/session-b/200/0/0/0/4/1",
          run = function()
            local beginDiagnostics = deps.BeginIncomingSnapshotDiagnosticsForSession
            local recorder = deps.RecordIncomingSnapshotReject
            if type(beginDiagnostics) ~= "function" or type(recorder) ~= "function" then
              return "missing"
            end
            local sessionState = {
              incomingSnapshotCleanupTotal = 4,
              incomingSnapshotCleanupHistory = {
                { sessionId = "previous-session", count = 4, at = 50 },
              },
              maxIncomingSnapshotRejectHistory = 3,
              maxIncomingSnapshotRejectReasons = 2,
            }
            local beganFirst = beginDiagnostics(sessionState, "session-a", 100, trim)
            recorder(sessionState, "PSYNC_START", "Host-Realm", { "PSYNC_START", "transfer-a", "session-a" }, "reason_a", 101, trim)
            local beganSame = beginDiagnostics(sessionState, "session-a", 150, trim)
            local beganNext = beginDiagnostics(sessionState, "session-b", 200, trim)
            return table.concat({
              tostring(beganFirst),
              tostring(beganSame),
              tostring(beganNext),
              trim(sessionState.incomingSnapshotDiagnosticsSessionId),
              tostring(math.max(0, tonumber(sessionState.incomingSnapshotDiagnosticsStartedAt) or 0)),
              tostring(math.max(0, tonumber(sessionState.incomingSnapshotRejectTotal) or 0)),
              tostring(#sessionState.incomingSnapshotRejectHistory),
              tostring(next(sessionState.incomingSnapshotRejectCounts) == nil and 0 or 1),
              tostring(math.max(0, tonumber(sessionState.incomingSnapshotCleanupTotal) or 0)),
              tostring(#sessionState.incomingSnapshotCleanupHistory),
            }, "/")
          end,
        },
        {
          name = "inbound snapshot health helper available",
          expected = true,
          run = function()
            return type(GetIncomingProfileSyncHealth) == "function"
          end,
        },
        {
          name = "inbound snapshot health idle",
          expected = "idle",
          run = function()
            return type(GetIncomingProfileSyncHealth) == "function"
              and GetIncomingProfileSyncHealth(0, 0, 30)
              or "missing"
          end,
        },
        {
          name = "inbound snapshot health distinguishes receiving and stalled",
          expected = "receiving/stalled",
          run = function()
            if type(GetIncomingProfileSyncHealth) ~= "function" then
              return "missing"
            end
            return table.concat({
              GetIncomingProfileSyncHealth(1, 29, 30),
              GetIncomingProfileSyncHealth(1, 30, 30),
            }, "/")
          end,
        },
      }
      for _, definition in ipairs(checkRegistry) do
        local executed, actual = pcall(definition.run)
        local reportedActual = actual
        if not executed then
          reportedActual = "validation_error: " .. tostring(actual or "unknown error")
        end
        addCheck(
          definition.name,
          definition.expected,
          reportedActual
        )
      end

      (function()
        local simulationVoteValidation = deps.ValidateSimulationVoteExclusion
        addCheck("simulation vote exclusion validation API", true, type(simulationVoteValidation) == "function")
        if type(simulationVoteValidation) == "function" then
          local executed, validationOk, validationReport = pcall(simulationVoteValidation)
          addCheck("simulation vote exclusion validation completed", true, executed and validationOk == true)
          for _, validationCheck in ipairs(type(validationReport) == "table" and validationReport.checks or {}) do
            addCheck(
              "simulation vote exclusion: " .. tostring(type(validationCheck) == "table" and validationCheck.name or "unnamed check"),
              true,
              type(validationCheck) == "table" and validationCheck.passed == true
            )
          end
        end
      end)();

      (function()
        local executed, validationOk, validationReport = pcall(runSeventySessionArchiveConvergenceValidation)
        workflow6FaultMatrixEvidence.archiveConvergenceOk = executed and validationOk == true
        workflow6FaultMatrixEvidence.archiveConvergenceReport = validationReport
        addCheck("70-session archive convergence validation completed", true, executed and validationOk == true)
        for _, validationCheck in ipairs(type(validationReport) == "table" and validationReport.checks or {}) do
          addCheck(
            "archive stress: " .. tostring(type(validationCheck) == "table" and validationCheck.name or "unnamed check"),
            true,
            type(validationCheck) == "table" and validationCheck.passed == true
          )
        end
      end)();

      (function()
        local buildPlan = deps.BuildAlignedReplicaArchivePlan
        addCheck("character-switch archive planner API", true, type(buildPlan) == "function")
        if type(buildPlan) ~= "function" then
          return
        end
        local function scopes(lootListChecksum, itemHistoryChecksum, sessionHistoryChecksum, funAwardsChecksum, repairScope)
          return {
            { scope = "lootList", memberChecksum = lootListChecksum, needsRepair = repairScope == "lootList" },
            { scope = "itemHistory", memberChecksum = itemHistoryChecksum, needsRepair = repairScope == "itemHistory" },
            { scope = "sessionHistory", memberChecksum = sessionHistoryChecksum, needsRepair = repairScope == "sessionHistory" },
            { scope = "funAwards", memberChecksum = funAwardsChecksum, needsRepair = repairScope == "funAwards" },
          }
        end
        local aligned = buildPlan({
          existingReplica = true,
          localProfileId = "account-profile",
          memberProfileId = "account-profile",
          scopes = scopes("loot-list", "item-history", "session-history", "fun-awards"),
        })
        addCheck("character-switch aligned replica is reusable", true, aligned.canReuseExistingReplica == true)
        addCheck("character-switch aligned replica queues no archive scope", 0,
          #(type(aligned.broadArchiveScopes) == "table" and aligned.broadArchiveScopes or {}))
        addCheck("character-switch aligned replica queues no full snapshot", false, aligned.fullSnapshotAllowed == true)

        local newCharacter = buildPlan({
          existingReplica = true,
          localProfileId = "account-profile",
          memberProfileId = "account-profile",
          scopes = scopes("old-loot-list", "item-history", "session-history", "fun-awards", "lootList"),
          preciseProofReady = true,
          preciseSubdomains = {
            "llr:Newraider-Realm",
            "lmr:Newraider-Realm",
            "ssr:id%3aunrelated-session",
          },
        })
        addCheck("character-switch new character requests only loot proof", "loot",
          table.concat(type(newCharacter.preciseDomains) == "table" and newCharacter.preciseDomains or {}, ","))
        addCheck("character-switch new character selects only roster and Loot List leaves",
          "llr:Newraider-Realm,lmr:Newraider-Realm",
          table.concat(type(newCharacter.preciseSubdomains) == "table" and newCharacter.preciseSubdomains or {}, ","))
        addCheck("character-switch precise repair forbids broad archive fallback", false,
          newCharacter.broadArchiveFallbackAllowed == true)
        addCheck("character-switch precise repair forbids full snapshot", false,
          newCharacter.fullSnapshotAllowed == true)

        local missingProof = buildPlan({
          existingReplica = true,
          localProfileId = "account-profile",
          memberProfileId = "account-profile",
          scopes = scopes("old-loot-list", "item-history", "session-history", "fun-awards", "lootList"),
          preciseProofReady = false,
        })
        addCheck("character-switch missing proof remains pending", true, missingProof.awaitingPreciseProof == true)
        addCheck("character-switch missing proof queues no precise leaves", 0,
          #(type(missingProof.preciseSubdomains) == "table" and missingProof.preciseSubdomains or {}))
        addCheck("character-switch missing proof never enables broad archive fallback", false,
          missingProof.broadArchiveFallbackAllowed == true)
        addCheck("character-switch missing proof never enables full snapshot", false,
          missingProof.fullSnapshotAllowed == true)

        local resolveProofAction = deps.ResolveAlignedReplicaPreciseProofAction
        addCheck("character-switch precise-proof retry planner API", true, type(resolveProofAction) == "function")
        if type(resolveProofAction) == "function" then
          local retryDecision = resolveProofAction(false, 0, 4)
          addCheck("character-switch missing proof retries before its deadline", "retry_precise_proof/1/false",
            table.concat({
              tostring(retryDecision.action),
              tostring(retryDecision.attempts),
              tostring(retryDecision.terminal),
            }, "/"))
          local terminalDecision = resolveProofAction(false, 3, 4)
          addCheck("character-switch missing proof terminates fail-closed", "fail_closed/4/true",
            table.concat({
              tostring(terminalDecision.action),
              tostring(terminalDecision.attempts),
              tostring(terminalDecision.terminal),
            }, "/"))
          addCheck("character-switch proof timeout cannot queue broad recovery", false,
            terminalDecision.broadArchiveFallbackAllowed == true or terminalDecision.fullSnapshotAllowed == true)
        end

        local incompleteProof = buildPlan({
          existingReplica = true,
          localProfileId = "account-profile",
          memberProfileId = "account-profile",
          scopes = scopes("", "item-history", "session-history", "fun-awards", "lootList"),
        })
        addCheck("character-switch incomplete family proof uses legacy archive recovery", true,
          incompleteProof.broadArchiveFallbackAllowed == true and incompleteProof.canReuseExistingReplica ~= true)
      end)();

      (function()
        local buildIdentity = deps.BuildJoinManifestProofIdentity
        local resolveRequest = deps.ResolveJoinManifestProofRequest
        local resolveProofPoll = deps.ResolveJoinManifestProofPoll
        local projectRequestState = deps.ProjectPreciseRequestState
        local advanceProgress = deps.AdvancePreciseRequestProgress
        local recordMultipartPart = deps.RecordPreciseMultipartPart
        local isProofReady = deps.IsJoinManifestPreciseProofReady
        addCheck("join proof identity builder API", true, type(buildIdentity) == "function")
        addCheck("join proof lifecycle resolver API", true, type(resolveRequest) == "function")
        addCheck("join proof progress-aware poll API", true, type(resolveProofPoll) == "function")
        addCheck("join proof request-state projection API", true, type(projectRequestState) == "function")
        addCheck("join proof multipart progress API", true, type(advanceProgress) == "function")
        addCheck("join proof counted multipart receipt API", true, type(recordMultipartPart) == "function")
        addCheck("join proof response gate API", true, type(isProofReady) == "function")
        if type(buildIdentity) ~= "function"
          or type(resolveRequest) ~= "function"
          or type(resolveProofPoll) ~= "function"
          or type(projectRequestState) ~= "function"
          or type(advanceProgress) ~= "function"
          or type(recordMultipartPart) ~= "function"
          or type(isProofReady) ~= "function"
        then
          return
        end

        local proofIdentity = buildIdentity({
          sessionId = "SESSION-proof",
          memberKey = "Raider-Realm",
          profileRevision = "revision-a",
          domains = { "session", "loot", "loot" },
          subdomains = { "ssr:id%3aold", "llr:Raider-Realm" },
        })
        local reorderedIdentity = buildIdentity({
          sessionId = "session-PROOF",
          memberKey = "raider-realm",
          profileRevision = "revision-a",
          domains = { "loot", "session" },
          subdomains = { "llr:raider-realm", "ssr:id%3aold" },
        })
        addCheck("join proof identity is stable across scope ordering", true,
          proofIdentity ~= "" and proofIdentity == reorderedIdentity)

        local reused = resolveRequest({
          proofIdentity = proofIdentity,
          pendingState = {
            proofIdentity = proofIdentity,
            token = "JMR-stable-token",
          },
        })
        addCheck("join proof pending retries reuse one token", "reuse_pending/JMR-stable-token",
          tostring(reused.action) .. "/" .. tostring(reused.token))

        local exhausted = resolveRequest({
          proofIdentity = proofIdentity,
          terminalState = {
            proofIdentity = proofIdentity,
            attempts = 4,
            maxAttempts = 4,
          },
        })
        addCheck("join proof retry exhaustion is terminally suppressed", "suppress_terminal/true",
          tostring(exhausted.action) .. "/" .. tostring(exhausted.terminal))

        local changedRevisionIdentity = buildIdentity({
          sessionId = "SESSION-proof",
          memberKey = "Raider-Realm",
          profileRevision = "revision-b",
          domains = { "loot", "session" },
          subdomains = { "llr:Raider-Realm", "ssr:id%3aold" },
        })
        local changedScopeIdentity = buildIdentity({
          sessionId = "SESSION-proof",
          memberKey = "Raider-Realm",
          profileRevision = "revision-a",
          domains = { "loot" },
          subdomains = { "llr:Raider-Realm" },
        })
        local changedRevision = resolveRequest({
          proofIdentity = changedRevisionIdentity,
          terminalState = { proofIdentity = proofIdentity },
        })
        local changedScope = resolveRequest({
          proofIdentity = changedScopeIdentity,
          terminalState = { proofIdentity = proofIdentity },
        })
        addCheck("join proof changed revision or scopes rearms automatically", "start_new/start_new",
          tostring(changedRevision.action) .. "/" .. tostring(changedScope.action))

        local manualRearm = resolveRequest({
          proofIdentity = proofIdentity,
          terminalState = { proofIdentity = proofIdentity },
          manualRearm = true,
        })
        addCheck("join proof Refresh Readiness rearms terminal identity", "start_new/true",
          tostring(manualRearm.action) .. "/" .. tostring(manualRearm.manualRearm))

        local completeCandidate = projectRequestState({
          preciseDetailLoaded = true,
          preciseScopeDomains = { "session", "loot" },
        }, {
          status = "complete",
          requestToken = " JMR-stable-token ",
          requestedCount = 2,
          receivedCount = 2,
          complete = true,
        })
        addCheck("join proof matching response token and scopes completes", true,
          isProofReady(completeCandidate, "JMR-stable-token", { "loot", "session" }))
        addCheck("join proof missing response token is rejected", false,
          isProofReady({
            preciseDetailLoaded = true,
            preciseResponseComplete = true,
            preciseScopeDomains = { "loot", "session" },
          }, "JMR-stable-token", { "loot", "session" }))
        addCheck("join proof mismatched response token is rejected", false,
          isProofReady({
            preciseDetailLoaded = true,
            preciseResponseComplete = true,
            preciseRequestToken = "JMR-other-token",
            preciseScopeDomains = { "loot", "session" },
          }, "JMR-stable-token", { "loot", "session" }))
        addCheck("join proof incomplete scope coverage is rejected", false,
          isProofReady(completeCandidate, "JMR-stable-token", { "loot", "session", "permissions" }))

        local waitingDecision = resolveProofPoll({
          proofReady = false,
          requestState = "waiting",
          completedAttempts = 2,
          maxAttempts = 4,
        })
        addCheck("join proof waiting polls do not consume retry attempts", "wait_for_precise_proof/2/false",
          table.concat({
            tostring(waitingDecision.action),
            tostring(waitingDecision.attempts),
            tostring(waitingDecision.terminal),
          }, "/"))
        local failedDecision = resolveProofPoll({
          proofReady = false,
          requestState = "failed",
          completedAttempts = 2,
          maxAttempts = 4,
        })
        addCheck("join proof failed request consumes one bounded retry", "retry_precise_proof/3/false",
          table.concat({
            tostring(failedDecision.action),
            tostring(failedDecision.attempts),
            tostring(failedDecision.terminal),
          }, "/"))

        local progressState = {
          status = "failed",
          error = "response_timeout",
          requestToken = "JMR-stable-token",
          deadlineAt = 100,
        }
        local progressAccepted = advanceProgress(progressState, "JMR-stable-token", 120, 20)
        addCheck("join proof valid multipart progress rearms and extends its stall deadline", "true/waiting//140/120",
          table.concat({
            tostring(progressAccepted),
            tostring(progressState.status),
            tostring(progressState.error),
            tostring(progressState.deadlineAt),
            tostring(progressState.lastProgressAt),
          }, "/"))
        local staleDeadline = progressState.deadlineAt
        addCheck("join proof mismatched multipart progress cannot extend the deadline", "false/140",
          tostring(advanceProgress(progressState, "JMR-other-token", 130, 20))
            .. "/" .. tostring(progressState.deadlineAt == staleDeadline and staleDeadline or "changed"))

        local multipartBucket = {}
        local part2Complete, part2First = recordMultipartPart(multipartBucket, 2, 3, "two")
        local duplicateComplete, duplicateFirst = recordMultipartPart(multipartBucket, 2, 3, "two")
        local part1Complete, part1First = recordMultipartPart(multipartBucket, 1, 3, "one")
        local part3Complete, part3First = recordMultipartPart(multipartBucket, 3, 3, "three")
        addCheck("join proof multipart receipts count unique parts without full rescans",
          "false/true/false/false/false/true/true/true/3",
          table.concat({
            tostring(part2Complete), tostring(part2First),
            tostring(duplicateComplete), tostring(duplicateFirst),
            tostring(part1Complete), tostring(part1First),
            tostring(part3Complete), tostring(part3First),
            tostring(multipartBucket.receivedCount),
          }, "/"))

        local acceptedDecision = resolveProofPoll({
          proofReady = isProofReady(completeCandidate, "JMR-stable-token", { "loot", "session" }),
          requestState = "complete",
          completedAttempts = 2,
          maxAttempts = 4,
        })
        addCheck("join proof accepted completion exits retry path", "apply_precise/2/false",
          table.concat({
            tostring(acceptedDecision.action),
            tostring(acceptedDecision.attempts),
            tostring(acceptedDecision.terminal),
          }, "/"))
      end)();

      (function()
        local resolveP2Diagnostics = deps.ResolveHostMemberP2ProofDiagnostics
        addCheck("P2 proof diagnostic resolver API", true, type(resolveP2Diagnostics) == "function")
        if type(resolveP2Diagnostics) ~= "function" then
          return
        end

        local base = {
          matrixState = "VALIDATING",
          activeSessionId = "SESSION-current",
          statusSessionId = "SESSION-current",
          proofInspectable = true,
          proofAvailable = true,
          proofSessionId = "SESSION-current",
          expectedMemberKey = "Raider-Realm",
          proofMemberKey = "Raider-Realm",
          localProfileId = "profile-id",
          memberProfileId = "profile-id",
          localSessionChecksum = "session-sum",
          memberSessionChecksum = "session-sum",
          proofLastSyncAt = 100,
          proofAddonVersion = "1.0.0 [BETA]",
        }
        local function with(overrides)
          local input = {}
          for key, value in pairs(base) do
            input[key] = value
          end
          for key, value in pairs(type(overrides) == "table" and overrides or {}) do
            input[key] = value
          end
          return resolveP2Diagnostics(input)
        end

        addCheck("P2 diagnostics identify a missing current-lobby proof", "PROOF_MISSING",
          with({ proofAvailable = false }).code)
        addCheck("P2 diagnostics identify a proof from the previous lobby", "PROOF_SESSION_MISMATCH",
          with({ proofAvailable = false, previousProofSessionId = "SESSION-old" }).code)
        addCheck("P2 diagnostics identify a compact status from the previous lobby", "STATUS_SESSION_MISMATCH",
          with({ statusSessionId = "SESSION-old" }).code)
        addCheck("P2 diagnostics identify profile identity mismatch", "PROFILE_MISMATCH",
          with({ memberProfileId = "other-profile" }).code)
        addCheck("P2 diagnostics identify an incomplete current-lobby proof", "PROOF_INCOMPLETE",
          with({ proofLastSyncAt = 0 }).code)
        addCheck("P2 diagnostics identify a missing host current-session checksum", "LOCAL_CHECKSUM_MISSING",
          with({ localSessionChecksum = "" }).code)
        addCheck("P2 diagnostics identify a missing member current-session checksum", "MEMBER_CHECKSUM_MISSING",
          with({ memberSessionChecksum = "" }).code)
        addCheck("P2 diagnostics identify a current-session checksum mismatch", "CHECKSUM_MISMATCH",
          with({ memberSessionChecksum = "different-sum" }).code)
        addCheck("P2 diagnostics separate matching proof from pending status publication",
          "STATUS_PUBLICATION_PENDING", with().code)
        addCheck("P2 diagnostics describe the member-side host validation boundary", "HOST_VALIDATION_PENDING",
          with({ proofInspectable = false, proofAvailable = false }).code)
        addCheck("P2 diagnostics accept the host READY matrix", "ACCEPTED",
          with({ matrixState = "READY" }).code)
      end)();

      (function()
        local suppressStableMember = INTERNAL_API.LIDCOUNCIL_ShouldSuppressStableMemberPublication_Impl
        local buildReadinessPublicationOptions = INTERNAL_API.LIDCOUNCIL_BuildReadinessPublicationOptions_Impl
        local aggregateArchiveState = INTERNAL_API.LIDCOUNCIL_AggregateHostMemberArchiveState_Impl
        local selectLatestSession = INTERNAL_API.LIDCOUNCIL_SelectLatestCompletedSessionRecord_Impl
        local resolveHistoryAttempt = INTERNAL_API.LIDCOUNCIL_ResolveLatestSessionHistoryCatchupAttempt_Impl
        local shouldPrimeReplicaProof = INTERNAL_API.LIDCOUNCIL_ShouldPrimeReplicaProofWork_Impl
        addCheck("stable MEMBER publication gate API", true, type(suppressStableMember) == "function")
        addCheck("readiness publication policy API", true, type(buildReadinessPublicationOptions) == "function")
        addCheck("archive stale-state aggregator API", true, type(aggregateArchiveState) == "function")
        addCheck("latest completed-session selector API", true, type(selectLatestSession) == "function")
        addCheck("latest Session History catch-up budget API", true, type(resolveHistoryAttempt) == "function")
        addCheck("checksum-only PSTATE work gate API", true, type(shouldPrimeReplicaProof) == "function")
        if type(suppressStableMember) == "function" then
          addCheck("stable MEMBER publication suppresses forced identical proof but permits explicit repeat",
            "true/false/false",
            table.concat({
              tostring(suppressStableMember("same", "same", false)),
              tostring(suppressStableMember("same", "changed", false)),
              tostring(suppressStableMember("same", "same", true)),
            }, "/"))
          local published = 0
          local recentSignature = ""
          for _ = 1, 500 do
            if not suppressStableMember(recentSignature, "stable-proof", false) then
              published = published + 1
              recentSignature = "stable-proof"
            end
          end
          addCheck("500 identical automatic MEMBER callbacks publish once", 1, published)
          if type(buildReadinessPublicationOptions) == "function" then
            local automaticOptions = buildReadinessPublicationOptions()
            local manualOptions = buildReadinessPublicationOptions({ manualRefresh = true })
            addCheck("automatic readiness publication keeps identical-proof suppression", true,
              suppressStableMember("green-proof", "green-proof", automaticOptions.allowIdenticalRepeat))
            addCheck("manual Refresh Readiness resends an identical green proof", false,
              suppressStableMember("green-proof", "green-proof", manualOptions.allowIdenticalRepeat))
            addCheck("manual readiness resend remains immediate and checkpoint-free", "true/true",
              table.concat({
                tostring(manualOptions.forceImmediate == true),
                tostring(manualOptions.suppressCheckpoint == true),
              }, "/"))
          end
        end
        if type(aggregateArchiveState) == "function" then
          addCheck("archive aggregation preserves yellow stale state without hiding pending proof",
            "STALE/PENDING/REVIEW",
            table.concat({
              aggregateArchiveState({
                lootList = "READY", itemHistory = "READY", sessionHistory = "STALE", funAwards = "READY",
              }),
              aggregateArchiveState({
                lootList = "READY", itemHistory = "PENDING", sessionHistory = "STALE", funAwards = "READY",
              }),
              aggregateArchiveState({
                lootList = "READY", itemHistory = "REVIEW", sessionHistory = "STALE", funAwards = "READY",
              }),
            }, "/"))
        end
        if type(selectLatestSession) == "function" then
          local latest = selectLatestSession({
            { id = "finished-old", status = "FINISHED", startedAt = 10, endedAt = 20 },
            { id = "active-current", status = "PREPARING", startedAt = 40 },
            { id = "finished-new", status = "FINISHED", startedAt = 30, endedAt = 35, historySealVersion = 1 },
          }, "active-current")
          addCheck("latest Session History catch-up selects one completed sealed leaf", "finished-new/1",
            tostring(type(latest) == "table" and latest.id or "")
              .. "/" .. tostring(type(latest) == "table" and latest.historySealVersion or 0))
        end
        if type(resolveHistoryAttempt) == "function" then
          local base = {
            expectedChecksum = "host-root",
            memberChecksum = "member-root",
            latestSessionId = "finished-new",
          }
          addCheck("latest Session History catch-up is one join attempt plus one start retry",
            "queue_join/suppress_duplicate/queue_start_retry/suppress_exhausted",
            table.concat({
              resolveHistoryAttempt(base),
              resolveHistoryAttempt({
                expectedChecksum = base.expectedChecksum,
                memberChecksum = base.memberChecksum,
                latestSessionId = base.latestSessionId,
                attempts = 1,
              }),
              resolveHistoryAttempt({
                expectedChecksum = base.expectedChecksum,
                memberChecksum = base.memberChecksum,
                latestSessionId = base.latestSessionId,
                attempts = 1,
                startRetry = true,
              }),
              resolveHistoryAttempt({
                expectedChecksum = base.expectedChecksum,
                memberChecksum = base.memberChecksum,
                latestSessionId = base.latestSessionId,
                attempts = 2,
                startRetry = true,
              }),
            }, "/"))
          addCheck("latest Session History catch-up skips aligned and missing proof",
            "aligned/missing_proof",
            table.concat({
              resolveHistoryAttempt({
                expectedChecksum = "same", memberChecksum = "SAME", latestSessionId = "finished-new",
              }),
              resolveHistoryAttempt({
                expectedChecksum = "same", memberChecksum = "", latestSessionId = "finished-new",
              }),
            }, "/"))
        end
        if type(shouldPrimeReplicaProof) == "function" then
          addCheck("identical returning replica schedules no detailed PSTATE work",
            "false/true/false",
            table.concat({
              tostring(shouldPrimeReplicaProof(true, { p1 = "READY", p2 = "READY", sessionHistory = "STALE" })),
              tostring(shouldPrimeReplicaProof(true, { p1 = "READY", p2 = "PENDING" })),
              tostring(shouldPrimeReplicaProof(false, { p1 = "PENDING", p2 = "PENDING" })),
            }, "/"))
        end
      end)();

      (function()
        local buildArchiveChecksums = deps.BuildProfileSyncArchiveScopeChecksums
        local buildPlan = deps.BuildAlignedReplicaArchivePlan
        local fixtureApisReady = type(RootDB) == "function"
          and type(GetLootProfileSubchecksumManifest) == "function"
          and type(buildArchiveChecksums) == "function"
          and type(buildPlan) == "function"
        addCheck("empty Item History normalization fixture APIs", true, fixtureApisReady)

        local missingChecksums = {}
        local emptyChecksums = {}
        local missingLeafCount = -1
        local emptyLeafCount = -1
        local emptyPlan = {}
        local executed = false
        if fixtureApisReady then
          local root = RootDB()
          local profiles = type(root) == "table" and type(root.profiles) == "table" and root.profiles or nil
          if type(profiles) == "table" then
            local missingName = "__LCPREFLIGHT_EMPTY_ITEM_MISSING__"
            local emptyName = "__LCPREFLIGHT_EMPTY_ITEM_TABLE__"
            local savedMissing = profiles[missingName]
            local savedEmpty = profiles[emptyName]
            local function restoreFixtures()
              profiles[missingName] = savedMissing
              profiles[emptyName] = savedEmpty
            end
            executed = pcall(function()
              profiles[missingName] = {
                settings = {},
                sessions = {},
                lootLedger = {},
                lootRollStats = {},
                meta = { profileId = "preflight-empty-item-missing", revision = 1, createdAt = 1, updatedAt = 1 },
              }
              profiles[emptyName] = {
                settings = {},
                sessions = {},
                liveBoardHistory = {},
                lootLedger = {},
                lootRollStats = {},
                meta = { profileId = "preflight-empty-item-table", revision = 1, createdAt = 1, updatedAt = 1 },
              }
              local missingManifest = GetLootProfileSubchecksumManifest(missingName, { "session" })
              local emptyManifest = GetLootProfileSubchecksumManifest(emptyName, { "session" })
              missingChecksums = buildArchiveChecksums(missingManifest, nil)
              emptyChecksums = buildArchiveChecksums(emptyManifest, nil)

              local function countItemHistoryLeaves(manifest)
                local count = 0
                local byDomain = type(manifest) == "table" and type(manifest.byDomain) == "table"
                  and manifest.byDomain
                  or {}
                local sessionState = type(byDomain.session) == "table" and byDomain.session or {}
                for subdomain in pairs(type(sessionState.subchecksums) == "table" and sessionState.subchecksums or {}) do
                  if string.lower(tostring(subdomain or "")):find("^slb:", 1, false) then
                    count = count + 1
                  end
                end
                return count
              end
              missingLeafCount = countItemHistoryLeaves(missingManifest)
              emptyLeafCount = countItemHistoryLeaves(emptyManifest)
              emptyPlan = buildPlan({
                existingReplica = true,
                localProfileId = "shared-empty-item-profile",
                memberProfileId = "shared-empty-item-profile",
                scopes = {
                  { scope = "lootList", memberChecksum = "same-loot-list", needsRepair = false },
                  { scope = "itemHistory", memberChecksum = emptyChecksums.itemHistory, needsRepair = false },
                  { scope = "sessionHistory", memberChecksum = "same-session-history", needsRepair = false },
                  { scope = "funAwards", memberChecksum = "same-fun-awards", needsRepair = false },
                },
              })
            end)
            restoreFixtures()
          end
        end
        addCheck("empty Item History normalization fixture executes", true, executed)
        addCheck("missing and empty Item History expose no archive leaves", "0/0",
          tostring(missingLeafCount) .. "/" .. tostring(emptyLeafCount))
        addCheck("missing and empty Item History share one canonical checksum", true,
          executed
            and tostring(missingChecksums.itemHistory or "") ~= ""
            and missingChecksums.itemHistory == emptyChecksums.itemHistory)
        addCheck("canonical empty Item History requires no repair", true,
          executed
            and emptyPlan.canReuseExistingReplica == true
            and #(type(emptyPlan.preciseDomains) == "table" and emptyPlan.preciseDomains or {}) == 0
            and #(type(emptyPlan.broadArchiveScopes) == "table" and emptyPlan.broadArchiveScopes or {}) == 0)
      end)();

      (function()
        local buildDiagnostics = deps.BuildLootListDifferenceDiagnostics
        addCheck("exact Loot List leaf diagnostic API", true, type(buildDiagnostics) == "function")
        if type(buildDiagnostics) ~= "function" then
          return
        end
        local diagnostics = buildDiagnostics({
          byDomain = {
            loot = {
              subchecksums = {
                ["lls"] = "same",
                ["llr:Raider-Realm"] = "local-row",
                ["lmr:HostOnly-Realm"] = "host-only",
                ["llr:Case-Realm"] = "case-same",
                ["lmr:Duplicate-Realm"] = "duplicate-a",
                ["lmr:duplicate-realm"] = "duplicate-b",
                ["lre:ignored-award"] = "local-award",
              },
            },
          },
        }, {
          byDomain = {
            loot = {
              subchecksums = {
                ["lls"] = "same",
                ["llr:Raider-Realm"] = "remote-row",
                ["lmr:MemberOnly-Realm"] = "member-only",
                ["llr:case-realm"] = "case-same",
                ["lmr:Duplicate-Realm"] = "duplicate-a",
                ["lre:ignored-award"] = "remote-award",
              },
            },
          },
        })
        local kindCounts = {}
        for _, leaf in ipairs(type(diagnostics) == "table" and type(diagnostics.leaves) == "table"
          and diagnostics.leaves or {})
        do
          local kind = tostring(type(leaf) == "table" and leaf.kind or "")
          kindCounts[kind] = math.max(0, tonumber(kindCounts[kind]) or 0) + 1
        end
        addCheck("exact Loot List diagnostics expose aggregate and five leaf-level causes", "true/true/5",
          table.concat({
            tostring(type(diagnostics) == "table" and diagnostics.available == true),
            tostring(type(diagnostics) == "table" and diagnostics.aggregateDiffers == true),
            tostring(type(diagnostics) == "table" and diagnostics.count or -1),
          }, "/"))
        addCheck("exact Loot List diagnostics distinguish content, presence, casing, and duplicate identity",
          "1/1/1/1/1",
          table.concat({
            tostring(kindCounts.checksum_mismatch or 0),
            tostring(kindCounts.missing_remote or 0),
            tostring(kindCounts.missing_local or 0),
            tostring(kindCounts.identity_case_mismatch or 0),
            tostring(kindCounts.duplicate_local_identity or 0),
          }, "/"))
        local aligned = buildDiagnostics({
          byDomain = { loot = { subchecksums = { ["llr:Aligned-Realm"] = "same" } } },
        }, {
          byDomain = { loot = { subchecksums = { ["llr:Aligned-Realm"] = "same" } } },
        })
        addCheck("exact Loot List diagnostics leave aligned proof empty", "true/false/0",
          table.concat({
            tostring(type(aligned) == "table" and aligned.available == true),
            tostring(type(aligned) == "table" and aligned.aggregateDiffers == true),
            tostring(type(aligned) == "table" and aligned.count or -1),
          }, "/"))
        local unavailable = buildDiagnostics({ byDomain = { loot = { subchecksums = {} } } }, {})
        addCheck("exact Loot List diagnostics require remote loot proof", "false/0",
          tostring(type(unavailable) == "table" and unavailable.available == true)
            .. "/" .. tostring(type(unavailable) == "table" and unavailable.count or -1))
      end)();

      (function()
        local buildDiagnostics = deps.BuildItemHistoryDifferenceDiagnostics
        addCheck("exact Item History leaf diagnostic API", true, type(buildDiagnostics) == "function")
        if type(buildDiagnostics) ~= "function" then
          return
        end
        local diagnostics = buildDiagnostics({
          byDomain = {
            session = {
              subchecksums = {
                ["slb:board%3aaligned"] = "same",
                ["slb:board%3adifferent"] = "local-a",
                ["slb:board%3alocal-only"] = "local-only",
                ["ssr:id%3aignored-session"] = "session-local",
              },
            },
          },
        }, {
          byDomain = {
            session = {
              subchecksums = {
                ["slb:board%3aaligned"] = "same",
                ["slb:board%3adifferent"] = "remote-a",
                ["slb:board%3aremote-only"] = "remote-only",
                ["ssr:id%3aignored-session"] = "session-remote",
              },
            },
          },
        })
        local kindsBySubdomain = {}
        for _, leaf in ipairs(type(diagnostics) == "table" and type(diagnostics.leaves) == "table" and diagnostics.leaves or {}) do
          kindsBySubdomain[tostring(leaf.subdomain or "")] = tostring(leaf.kind or "")
        end
        addCheck("exact Item History diagnostics report only differing slb leaves", "true/3",
          tostring(type(diagnostics) == "table" and diagnostics.available == true)
            .. "/" .. tostring(type(diagnostics) == "table" and diagnostics.count or -1))
        addCheck("exact Item History diagnostics distinguish mismatch and missing sides",
          "checksum_mismatch/missing_remote/missing_local",
          table.concat({
            kindsBySubdomain["slb:board%3adifferent"] or "",
            kindsBySubdomain["slb:board%3alocal-only"] or "",
            kindsBySubdomain["slb:board%3aremote-only"] or "",
          }, "/"))
        local unavailable = buildDiagnostics({ byDomain = { session = { subchecksums = {} } } }, {})
        addCheck("exact Item History diagnostics require remote session proof", "false/0",
          tostring(type(unavailable) == "table" and unavailable.available == true)
            .. "/" .. tostring(type(unavailable) == "table" and unavailable.count or -1))
      end)();

      (function()
        local buildDiagnostics = deps.BuildSessionHistoryDifferenceDiagnostics
        addCheck("exact Session History leaf diagnostic API", true, type(buildDiagnostics) == "function")
        if type(buildDiagnostics) ~= "function" then
          return
        end
        local activeSession = { id = "SESSION-current" }
        local diagnostics = buildDiagnostics({
          byDomain = {
            session = {
              subchecksums = {
                ["ssr:id%3aSESSION-current"] = "current-local",
                ["ssr:id%3aaligned"] = "same",
                ["ssr:id%3adifferent"] = "local-a",
                ["ssr:id%3alocal-only"] = "local-only",
                ["slb:board%3aignored"] = "board-local",
              },
            },
          },
        }, {
          byDomain = {
            session = {
              subchecksums = {
                ["ssr:id%3aSESSION-current"] = "current-remote",
                ["ssr:id%3aaligned"] = "same",
                ["ssr:id%3adifferent"] = "remote-a",
                ["ssr:id%3aremote-only"] = "remote-only",
                ["slb:board%3aignored"] = "board-remote",
              },
            },
          },
        }, activeSession)
        local kindsBySubdomain = {}
        for _, leaf in ipairs(type(diagnostics) == "table" and type(diagnostics.leaves) == "table" and diagnostics.leaves or {}) do
          kindsBySubdomain[tostring(leaf.subdomain or "")] = tostring(leaf.kind or "")
        end
        addCheck("exact Session History diagnostics exclude current session and live-board leaves", "true/3",
          tostring(type(diagnostics) == "table" and diagnostics.available == true)
            .. "/" .. tostring(type(diagnostics) == "table" and diagnostics.count or -1))
        addCheck("exact Session History diagnostics distinguish mismatch and missing sides",
          "checksum_mismatch/missing_remote/missing_local",
          table.concat({
            kindsBySubdomain["ssr:id%3adifferent"] or "",
            kindsBySubdomain["ssr:id%3alocal-only"] or "",
            kindsBySubdomain["ssr:id%3aremote-only"] or "",
          }, "/"))
        local unavailable = buildDiagnostics({ byDomain = { session = { subchecksums = {} } } }, {}, activeSession)
        addCheck("exact Session History diagnostics require remote session proof", "false/0",
          tostring(type(unavailable) == "table" and unavailable.available == true)
            .. "/" .. tostring(type(unavailable) == "table" and unavailable.count or -1))
      end)();

      (function()
        local resolveValidationState = deps.ResolveJoinManifestValidationState
        local applyValidationState = deps.ApplyJoinManifestValidationToStatusMatrix
        addCheck("returning-member validation resolver API", true, type(resolveValidationState) == "function")
        addCheck("returning-member validation matrix API", true, type(applyValidationState) == "function")
        if type(resolveValidationState) ~= "function" or type(applyValidationState) ~= "function" then
          return
        end

        local pendingState = {
          kind = "join_manifest",
          requirePreciseProof = true,
          token = "JMR-validation-token",
          sessionId = "SESSION-current",
          profileName = "Raid Profile",
          memberKey = "Raider-Realm",
          profileId = "shared-profile-id",
          memberProfileId = "shared-profile-id",
          domains = { "loot", "session", "loot" },
          preciseProofAttempts = 1,
          maxPreciseProofAttempts = 4,
        }
        local exactContext = {
          sessionId = "SESSION-current",
          profileName = "Raid Profile",
          memberKey = "Raider-Realm",
          profileId = "shared-profile-id",
          memberProfileId = "shared-profile-id",
        }
        local validationState = resolveValidationState(pendingState, exactContext)
        addCheck("returning-member exact proof is visible as validating", "VALIDATING/JMR-validation-token/loot,session",
          type(validationState) == "table" and table.concat({
            tostring(validationState.state),
            tostring(validationState.token),
            table.concat(type(validationState.domains) == "table" and validationState.domains or {}, ","),
          }, "/") or "missing")

        local function staleContext(overrides)
          local context = {
            sessionId = exactContext.sessionId,
            profileName = exactContext.profileName,
            memberKey = exactContext.memberKey,
            profileId = exactContext.profileId,
            memberProfileId = exactContext.memberProfileId,
          }
          for key, value in pairs(type(overrides) == "table" and overrides or {}) do
            context[key] = value
          end
          return resolveValidationState(pendingState, context) ~= nil
        end
        addCheck("returning-member stale session proof is rejected", false,
          staleContext({ sessionId = "SESSION-old" }))
        addCheck("returning-member stale profile proof is rejected", false,
          staleContext({ profileName = "Other Profile" }))
        addCheck("returning-member stale member proof is rejected", false,
          staleContext({ memberKey = "Other-Realm" }))
        addCheck("returning-member stale host profile identity is rejected", false,
          staleContext({ profileId = "other-profile-id" }))
        addCheck("returning-member stale replica identity is rejected", false,
          staleContext({ memberProfileId = "other-profile-id" }))

        local validatingMatrix = applyValidationState({
          p1 = "READY",
          p2 = "READY",
          p3 = "PENDING",
          lootList = "PENDING",
          itemHistory = "PENDING",
          sessionHistory = "PENDING",
          funAwards = "PENDING",
        }, validationState)
        addCheck("returning-member archive scopes publish validating", "VALIDATING/VALIDATING/VALIDATING/VALIDATING/VALIDATING",
          table.concat({
            tostring(validatingMatrix.p3),
            tostring(validatingMatrix.lootList),
            tostring(validatingMatrix.itemHistory),
            tostring(validatingMatrix.sessionHistory),
            tostring(validatingMatrix.funAwards),
          }, "/"))

        local preservedMatrix = applyValidationState({
          p3 = "REVIEW",
          lootList = "READY",
          itemHistory = "REVIEW",
          sessionHistory = "PENDING",
          funAwards = "READY",
        }, validationState)
        addCheck("returning-member validation preserves ready and review evidence", "REVIEW/READY/REVIEW/VALIDATING/READY",
          table.concat({
            tostring(preservedMatrix.p3),
            tostring(preservedMatrix.lootList),
            tostring(preservedMatrix.itemHistory),
            tostring(preservedMatrix.sessionHistory),
            tostring(preservedMatrix.funAwards),
          }, "/"))

        local lootOnlyState = resolveValidationState({
          kind = "join_manifest",
          requirePreciseProof = true,
          token = "JMR-loot-only",
          sessionId = exactContext.sessionId,
          profileName = exactContext.profileName,
          memberKey = exactContext.memberKey,
          profileId = exactContext.profileId,
          memberProfileId = exactContext.memberProfileId,
          domains = { "loot" },
        }, exactContext)
        local mixedMatrix = applyValidationState({
          p3 = "PENDING",
          lootList = "PENDING",
          itemHistory = "PENDING",
          sessionHistory = "READY",
          funAwards = "PENDING",
        }, lootOnlyState)
        addCheck("returning-member unrelated pending archive scope keeps P3 pending", "PENDING/VALIDATING/PENDING/VALIDATING",
          table.concat({
            tostring(mixedMatrix.p3),
            tostring(mixedMatrix.lootList),
            tostring(mixedMatrix.itemHistory),
            tostring(mixedMatrix.funAwards),
          }, "/"))
      end)();

      (function()
        local choiceBurstValidation = INTERNAL_API.LIDCOUNCIL_RunChoiceBurstValidation_Impl
        addCheck("choice burst validation API", true, type(choiceBurstValidation) == "function")
        if type(choiceBurstValidation) == "function" then
          local function runScenario(memberCount, itemCount)
            local scenarioLabel = tostring(memberCount) .. "-member " .. tostring(itemCount) .. "-item"
            local executed, validationOk, validationReport = pcall(
              choiceBurstValidation,
              memberCount,
              itemCount
            )
            if memberCount == 30 and itemCount == 5 then
              workflow6FaultMatrixEvidence.thirtyMemberFiveItemOk = executed and validationOk == true
              workflow6FaultMatrixEvidence.thirtyMemberFiveItemReport = validationReport
            end
            addCheck(scenarioLabel .. " choice burst validation completed", true, executed and validationOk == true)
            for _, validationCheck in ipairs(type(validationReport) == "table" and validationReport.checks or {}) do
              addCheck(
                "choice burst: " .. tostring(type(validationCheck) == "table" and validationCheck.name or "unnamed check"),
                true,
                type(validationCheck) == "table" and validationCheck.passed == true
              )
            end
          end
          runScenario(20, 5)
          runScenario(30, 5)
        end
      end)();

      (function()
        local boardReceiptValidation = INTERNAL_API.LIDCOUNCIL_RunBoardSyncReceiptValidation_Impl
        addCheck("Test Raid Items board receipt validation API", true, type(boardReceiptValidation) == "function")
        if type(boardReceiptValidation) == "function" then
          local executed, validationOk, validationReport = pcall(boardReceiptValidation)
          workflow6FaultMatrixEvidence.boardReceiptOk = executed and validationOk == true
          workflow6FaultMatrixEvidence.boardReceiptReport = validationReport
          addCheck("Test Raid Items board receipt validation completed", true, executed and validationOk == true)
          for _, validationCheck in ipairs(type(validationReport) == "table" and validationReport.checks or {}) do
            addCheck(
              "board receipt: " .. tostring(type(validationCheck) == "table" and validationCheck.name or "unnamed check"),
              true,
              type(validationCheck) == "table" and validationCheck.passed == true
            )
          end
        end
      end)();

      (function()
        local archiveTransactionValidation = INTERNAL_API.LIDCOUNCIL_RunArchiveTransactionValidation_Impl
        addCheck("archive transaction session validation API", true, type(archiveTransactionValidation) == "function")
        if type(archiveTransactionValidation) == "function" then
          local executed, validationOk, validationReport = pcall(archiveTransactionValidation)
          workflow6FaultMatrixEvidence.archiveTransactionOk = executed and validationOk == true
          workflow6FaultMatrixEvidence.archiveTransactionReport = validationReport
          addCheck("archive transaction session validation completed", true, executed and validationOk == true)
          for _, validationCheck in ipairs(type(validationReport) == "table" and validationReport.checks or {}) do
            addCheck(
              "archive transaction: " .. tostring(type(validationCheck) == "table" and validationCheck.name or "unnamed check"),
              true,
              type(validationCheck) == "table" and validationCheck.passed == true
            )
          end
        end
      end)();

      (function()
        local deltaDeliveryValidation = INTERNAL_API.LIDCOUNCIL_RunProfileDeltaDeliveryPolicyValidation_Impl
        addCheck("profile delta ACK-gated fallback validation API", true, type(deltaDeliveryValidation) == "function")
        if type(deltaDeliveryValidation) == "function" then
          local executed, validationOk, validationReport = pcall(deltaDeliveryValidation)
          addCheck("profile delta ACK-gated fallback validation completed", true, executed and validationOk == true)
          for _, validationCheck in ipairs(type(validationReport) == "table" and validationReport.checks or {}) do
            addCheck(
              "profile delta delivery: " .. tostring(type(validationCheck) == "table" and validationCheck.name or "unnamed check"),
              true,
              type(validationCheck) == "table" and validationCheck.passed == true
            )
          end
        end
      end)();

      (function()
        local serialValidation = INTERNAL_API.LIDCOUNCIL_RunAuthoritativeLootArchiveSerialValidation_Impl
        addCheck("authoritative Loot List serial validation API", true, type(serialValidation) == "function")
        if type(serialValidation) == "function" then
          local executed, validationOk, validationReport = pcall(serialValidation)
          addCheck("authoritative Loot List serial validation completed", true, executed and validationOk == true)
          for _, validationCheck in ipairs(type(validationReport) == "table" and validationReport.checks or {}) do
            addCheck(
              "authoritative Loot List serial: " .. tostring(type(validationCheck) == "table" and validationCheck.name or "unnamed check"),
              true,
              type(validationCheck) == "table" and validationCheck.passed == true
            )
          end
        end
      end)();

      if includeCommunicationSuites then
        local protocolValidation = deps.RunCommProtocolValidation
        addCheck("comm protocol validation API", true, type(protocolValidation) == "function")
        if type(protocolValidation) == "function" then
          local executed, protocolOk, protocolReport = pcall(protocolValidation)
          workflow6FaultMatrixEvidence.protocolOk = executed and protocolOk == true
          workflow6FaultMatrixEvidence.protocolReport = protocolReport
          addCheck("comm protocol validation completed", true, executed and protocolOk == true)
          for _, protocolCheck in ipairs(type(protocolReport) == "table" and protocolReport.checks or {}) do
            addCheck(
              "comm protocol: " .. tostring(type(protocolCheck) == "table" and protocolCheck.name or "unnamed check"),
              true,
              type(protocolCheck) == "table" and protocolCheck.passed == true
            )
          end
        end

        local transportValidation = RunCommOutboundTransportValidation
        addCheck("comm outbound transport validation API", true, type(transportValidation) == "function")
        if type(transportValidation) == "function" then
          local executed, transportOk, transportReport = pcall(transportValidation)
          workflow6FaultMatrixEvidence.transportOk = executed and transportOk == true
          workflow6FaultMatrixEvidence.transportReport = transportReport
          addCheck("comm outbound transport validation completed", true, executed and transportOk == true)
          for _, transportCheck in ipairs(type(transportReport) == "table" and transportReport.checks or {}) do
            addCheck(
              "comm outbound transport: " .. tostring(type(transportCheck) == "table" and transportCheck.name or "unnamed check"),
              true,
              type(transportCheck) == "table" and transportCheck.passed == true
            )
          end
        end

        local asymmetricCombatValidation = deps.RunAsymmetricCombatSyncValidation
        addCheck("asymmetric combat sync validation API", true, type(asymmetricCombatValidation) == "function")
        if type(asymmetricCombatValidation) == "function" then
          local executed, asymmetricOk, asymmetricReport = pcall(asymmetricCombatValidation)
          workflow6FaultMatrixEvidence.asymmetricCombatOk = executed and asymmetricOk == true
          addCheck("asymmetric combat sync validation completed", true, executed and asymmetricOk == true)
          for _, asymmetricCheck in ipairs(type(asymmetricReport) == "table" and asymmetricReport.checks or {}) do
            addCheck(
              "asymmetric combat sync: " .. tostring(type(asymmetricCheck) == "table" and asymmetricCheck.name or "unnamed check"),
              true,
              type(asymmetricCheck) == "table" and asymmetricCheck.passed == true
            )
          end
        end

      end

      (function()
        local combatInboxValidation = deps.RunCombatSyncInboxValidation
        addCheck("combat sync inbox validation API", true, type(combatInboxValidation) == "function")
        if type(combatInboxValidation) == "function" then
          local executed, inboxOk, inboxReport = pcall(combatInboxValidation)
          workflow6FaultMatrixEvidence.combatInboxOk = executed and inboxOk == true
          addCheck("combat sync inbox validation completed", true, executed and inboxOk == true)
          for _, inboxCheck in ipairs(type(inboxReport) == "table" and inboxReport.checks or {}) do
            addCheck(
              "combat sync inbox: " .. tostring(type(inboxCheck) == "table" and inboxCheck.name or "unnamed check"),
              true,
              type(inboxCheck) == "table" and inboxCheck.passed == true
            )
          end
        end
      end)();

      (function()
        local resolveLifecycle = deps.ResolvePreciseRequestLifecycle
        addCheck("precise request lifecycle validation API", true, type(resolveLifecycle) == "function")
        if type(resolveLifecycle) ~= "function" then
          return
        end
        local idle = resolveLifecycle(nil, 100)
        addCheck("precise request lifecycle distinguishes idle", "idle/0/0/false", table.concat({
          tostring(idle.status), tostring(idle.requestedCount), tostring(idle.receivedCount), tostring(idle.complete),
        }, "/"))
        local waiting = resolveLifecycle({
          status = "waiting",
          domains = { "loot", "session" },
          receivedDomains = {},
          deadlineAt = 115,
        }, 100)
        addCheck("precise request lifecycle distinguishes waiting", "waiting/2/0/true", table.concat({
          tostring(waiting.status), tostring(waiting.requestedCount), tostring(waiting.receivedCount), tostring(waiting.waiting),
        }, "/"))
        local partial = resolveLifecycle({
          status = "waiting",
          domains = { "loot", "session" },
          receivedDomains = { loot = true },
          deadlineAt = 115,
        }, 100)
        addCheck("precise request lifecycle retains partial replies", "waiting/2/1/false", table.concat({
          tostring(partial.status), tostring(partial.requestedCount), tostring(partial.receivedCount), tostring(partial.complete),
        }, "/"))
        local complete = resolveLifecycle({
          status = "waiting",
          domains = { "loot", "session" },
          receivedDomains = { loot = true, session = true },
          deadlineAt = 115,
        }, 100)
        addCheck("precise request lifecycle proves terminal completion", "complete/2/2/true", table.concat({
          tostring(complete.status), tostring(complete.requestedCount), tostring(complete.receivedCount), tostring(complete.complete),
        }, "/"))
        local timedOut = resolveLifecycle({
          status = "waiting",
          domains = { "loot" },
          receivedDomains = {},
          deadlineAt = 115,
        }, 115)
        addCheck("precise request lifecycle fails closed at deadline", "failed/response_timeout/true", table.concat({
          tostring(timedOut.status), tostring(timedOut.error), tostring(timedOut.failed),
        }, "/"))
        local sendFailure = resolveLifecycle({
          status = "failed",
          domains = { "session" },
          receivedDomains = {},
          deadlineAt = 115,
          error = "request_send_failed",
        }, 100)
        addCheck("precise request lifecycle preserves explicit failure", "failed/request_send_failed/true", table.concat({
          tostring(sendFailure.status), tostring(sendFailure.error), tostring(sendFailure.failed),
        }, "/"))
      end)();

      (function()
        local evidence = workflow6FaultMatrixEvidence
        local function hasPassedCheck(report, nameFragment)
          for _, check in ipairs(type(report) == "table" and report.checks or {}) do
            if type(check) == "table"
              and check.passed == true
              and string.find(tostring(check.name or ""), nameFragment, 1, true)
            then
              return true
            end
          end
          return false
        end

        if type(evidence.protocolReport) ~= "table" and type(deps.RunCommProtocolValidation) == "function" then
          local executed, validationOk, validationReport = pcall(deps.RunCommProtocolValidation)
          evidence.protocolOk = executed and validationOk == true
          evidence.protocolReport = validationReport
        end
        if type(evidence.transportReport) ~= "table" and type(RunCommOutboundTransportValidation) == "function" then
          local executed, validationOk, validationReport = pcall(RunCommOutboundTransportValidation)
          evidence.transportOk = executed and validationOk == true
          evidence.transportReport = validationReport
        end
        if evidence.asymmetricCombatOk == nil and type(deps.RunAsymmetricCombatSyncValidation) == "function" then
          local executed, validationOk = pcall(deps.RunAsymmetricCombatSyncValidation)
          evidence.asymmetricCombatOk = executed and validationOk == true
        end

        local oneItemValidation = INTERNAL_API.LIDCOUNCIL_RunChoiceBurstValidation_Impl
        local oneItemExecuted, oneItemOk, oneItemReport = false, false, nil
        if type(oneItemValidation) == "function" then
          oneItemExecuted, oneItemOk, oneItemReport = pcall(oneItemValidation, 30, 1)
        end
        addCheck("Workflow 6 fault matrix: 30-member one-item delivery retains every choice", true,
          oneItemExecuted and oneItemOk == true
            and hasPassedCheck(oneItemReport, "burst accepts every choice")
            and hasPassedCheck(oneItemReport, "duplicates never inflate authoritative rows"))

        addCheck("Workflow 6 fault matrix: 30-member five-item delivery has no silent loss", true,
          evidence.thirtyMemberFiveItemOk == true
            and hasPassedCheck(evidence.thirtyMemberFiveItemReport, "burst accepts every choice")
            and hasPassedCheck(evidence.thirtyMemberFiveItemReport, "receipt identities remain collision-free"))

        addCheck("Workflow 6 fault matrix: simultaneous choices preserve corrections and row counts", true,
          evidence.thirtyMemberFiveItemOk == true
            and hasPassedCheck(evidence.thirtyMemberFiveItemReport, "preserves every latest correction")
            and hasPassedCheck(evidence.thirtyMemberFiveItemReport, "duplicates never inflate authoritative rows"))

        addCheck("Workflow 6 fault matrix: mixed combat commits data and defers only protected UI", true,
          evidence.asymmetricCombatOk == true
            and evidence.combatInboxOk == true
            and hasPassedCheck(evidence.boardReceiptReport, "board sync commits and acknowledges during combat")
            and hasPassedCheck(evidence.boardReceiptReport, "ITEM_OPEN commits runtime data during combat"))

        addCheck("Workflow 6 fault matrix: one missing receipt is bounded, visible, and recoverable", true,
          evidence.boardReceiptOk == true
            and hasPassedCheck(evidence.boardReceiptReport, "ITEM_OPEN retry budget is bounded")
            and hasPassedCheck(evidence.boardReceiptReport, "ITEM_OPEN failure is visible by target")
            and hasPassedCheck(evidence.boardReceiptReport, "ITEM_OPEN receipt can recover a terminal target"))

        addCheck("Workflow 6 fault matrix: disconnect and rejoin refresh roster and reset recovery", true,
          evidence.protocolOk == true
            and evidence.archiveTransactionOk == true
            and hasPassedCheck(evidence.protocolReport, "session roster leave forces immediate refresh")
            and hasPassedCheck(evidence.protocolReport, "session roster join forces immediate refresh")
            and hasPassedCheck(evidence.archiveTransactionReport, "archive retry resets for a new session"))

        addCheck("Workflow 6 fault matrix: active P3 archive yields to live traffic and converges", true,
          evidence.protocolOk == true
            and evidence.transportOk == true
            and evidence.archiveConvergenceOk == true
            and hasPassedCheck(evidence.protocolReport, "protocol archive yield protects live lane")
            and hasPassedCheck(evidence.transportReport, "transport deferred archive yields to ready live packet"))

        addCheck("Workflow 6 fault matrix: late join refreshes immediately and reaches authoritative archive", true,
          evidence.protocolOk == true
            and evidence.archiveConvergenceOk == true
            and hasPassedCheck(evidence.protocolReport, "session roster join forces immediate refresh")
            and hasPassedCheck(evidence.archiveConvergenceReport, "70-session archive checksum converges")
            and hasPassedCheck(evidence.archiveConvergenceReport, "Fun Awards event manifest converges exactly"))
      end)();

      local report = {
        generatedAt = now(),
        suite = "profile_sync",
        version = 96,
        total = #checks,
        passed = passedCount,
        failed = #checks - passedCount,
        checks = checks,
      }
      if persistReport then
        local store = ensureStore()
        if type(store) == "table" then
          store.lastAutomatedValidation = report
          store.automatedValidationHistory = type(store.automatedValidationHistory) == "table" and store.automatedValidationHistory or {}
          store.automatedValidationHistory[#store.automatedValidationHistory + 1] = {
            generatedAt = report.generatedAt,
            total = report.total,
            passed = report.passed,
            failed = report.failed,
            version = report.version,
          }
          while #store.automatedValidationHistory > 8 do
            table.remove(store.automatedValidationHistory, 1)
          end
        end
      end
      return report.failed == 0, report
    end,
    ClearHarness = clearHarness,
    GetHarnessState = getHarnessState,
    GetSyntheticSessionContext = getSyntheticSessionContext,
    HasSyntheticSession = function()
      return getSyntheticSession() ~= nil
    end,
    GetSyntheticSyncCandidates = buildSyntheticCandidates,
    GetSyntheticSyncStatus = buildSyntheticStatus,
    GetStatefulTransferMatrix = buildStatefulTransferMatrix,
    RequestSyntheticSubchecks = requestSyntheticSubchecks,
    RequestSyntheticSnapshot = requestSyntheticSnapshot,
    PullSyntheticRepair = pullSyntheticRepair,
    PushSyntheticRepair = pushSyntheticRepair,
    PrepareSyntheticSession = prepareSyntheticSession,
    ActivateSyntheticSession = activateSyntheticSession,
    StopSyntheticSession = stopSyntheticSession,
    GetSyntheticConflictPreview = getConflictPreview,
    ApplySyntheticConflictResolution = applyConflictResolution,
  }
end
