<?xml version='1.0' encoding='utf-8'?>
<roblox version="4">
  <Meta name="ExplicitAutoJoints">true</Meta>
  <External>null</External>
  <External>nil</External>
  <Item class="Script" referent="RBX1">
    <Properties>
      <string name="Name">Script</string>
      <ProtectedString name="Source">if not plugin then
    warn("ForgeTools is a Studio plugin. Save this Script as a Local Plugin and remove the Workspace copy; do not run it as a game Script.")
    return
end
local Selection = game:GetService("Selection")
local LogService = game:GetService("LogService")
local ChangeHistoryService = game:GetService("ChangeHistoryService")
local ServerStorage = game:GetService("ServerStorage")
local ServerScriptService = game:GetService("ServerScriptService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local VERSION = "1.0.0"

-- Forge Inspector is isolated in its own ModuleScript to keep the main chunk below Luau register limits.
local openForgeInspector = function()
    warn("[ForgeTools] Forge Inspector module is not available.")
end
local inspectorModule = script:WaitForChild("Modules"):FindFirstChild("FORGE_INSPECTOR_MODULE")
if inspectorModule and inspectorModule:IsA("ModuleScript") then
    local ok, opener = pcall(require, inspectorModule)
    if ok and type(opener) == "function" then
        local initOK, openFn = pcall(opener, plugin)
        if initOK and type(openFn) == "function" then
            openForgeInspector = openFn
        else
            warn("[ForgeTools] Forge Inspector initialization failed: " .. tostring(openFn))
        end
    else
        warn("[ForgeTools] Forge Inspector module load failed: " .. tostring(opener))
    end
end

local HttpService = game:GetService("HttpService")
local TICKET_ENDPOINT = "https://analytics.mivvinet.xyz/api/v1/public/tickets"
local ANALYTICS_ENDPOINT = "https://analytics.mivvinet.xyz/api/v1/public/events"
local ANALYTICS_INSTALL_ID = "ForgeToolsAnalyticsInstallationIdV1"
local ANALYTICS_KEY="ForgeToolsLocalAnalyticsV1"
local ANALYTICS_OPT_IN="ForgeToolsAnalyticsEnabledV1"
local function readSetting(key)
    local ok,value=pcall(function() return plugin:GetSetting(key) end)
    return ok and value or nil
end
local analyticsEnabled=readSetting(ANALYTICS_OPT_IN)==true
local analytics=readSetting(ANALYTICS_KEY)
if type(analytics)~="table" then analytics={launches=0,opens=0,actions={}} end
if type(analytics.actions)~="table" then analytics.actions={} end
-- Remote telemetry contains only a random installation ID, version, and tool identifier.
local installation = readSetting(ANALYTICS_INSTALL_ID)
if type(installation) ~= "string" or not installation:match("^[%w_-]+$") or #installation &lt; 12 or #installation &gt; 80 then
    installation = HttpService:GenerateGUID(false):gsub("%-", "")
    pcall(function() plugin:SetSetting(ANALYTICS_INSTALL_ID, installation) end)
end
-- Installation tokens identify an API client installation for quotas, not an official build.
-- Never embed an API secret in the publicly distributed plugin.
local REGISTRATION_ENDPOINT = "https://analytics.mivvinet.xyz/api/v1/public/installations"
local INSTALL_TOKEN_SETTING = "ForgeToolsInstallationTokenV1"
local installToken = readSetting(INSTALL_TOKEN_SETTING)
if type(installToken) ~= "string" or not installToken:match("^ft_[%w_-]+$") then
    installToken = nil
end
local registeringInstallation = false
local function getInstallationToken()
    if installToken then return installToken end
    if registeringInstallation then
        -- Coalesce concurrent Feedback/Analytics registration attempts.
        local deadline = os.clock() + 8
        while registeringInstallation and os.clock() &lt; deadline do task.wait(0.15) end
        return installToken
    end
    registeringInstallation = true
    local ok, response = pcall(function()
        return HttpService:RequestAsync({
            Url=REGISTRATION_ENDPOINT, Method="POST",
            Headers={["Content-Type"]="application/json"},
            Body=HttpService:JSONEncode({installation=installation,version=VERSION})
        })
    end)
    if ok and response and response.StatusCode == 201 then
        local decoded, data = pcall(function() return HttpService:JSONDecode(response.Body) end)
        if decoded and type(data)=="table" and data.ok==true and
           type(data.token)=="string" and data.token:match("^ft_[%w_-]+$") and #data.token&lt;=128 then
            -- Never print or transmit the token to anything except the official API endpoints.
            local saved = pcall(function() plugin:SetSetting(INSTALL_TOKEN_SETTING,data.token) end)
            if saved then installToken = data.token end
        end
    end
    registeringInstallation = false
    return installToken
end
local function apiHeaders(token)
    local h={["Content-Type"]="application/json"}
    if token then h["Authorization"]="Bearer "..token end
    return h
end

local telemetryQueue = {}
local sendingTelemetry = false
local telemetryStatus = "idle"
local function enqueueTelemetry(event, tool)
    if not analyticsEnabled then return end
    if #telemetryQueue &gt;= 24 then return end
    telemetryQueue[#telemetryQueue+1] = {event=event, tool=tool or ""}
    if sendingTelemetry then return end
    sendingTelemetry = true
    task.spawn(function()
        while analyticsEnabled and #telemetryQueue &gt; 0 do
            local item = table.remove(telemetryQueue, 1)
            if not analyticsEnabled then break end
            local ok, response = pcall(function()
                if not analyticsEnabled then return nil end
                local token = getInstallationToken()
                if not token or not analyticsEnabled then return nil end
                return HttpService:RequestAsync({
                    Url=ANALYTICS_ENDPOINT, Method="POST",
                    Headers=apiHeaders(token),
                    Body=HttpService:JSONEncode({installation=installation, version=VERSION, event=item.event, tool=item.tool})
                })
            end)
            telemetryStatus = (not analyticsEnabled) and "disabled" or (ok and response and response.StatusCode == 202 and "sent" or "failed")
            if not analyticsEnabled then break end
            if telemetryStatus == "failed" then
                -- Never block plugin UI or repeatedly retry a denied/failed request.
                table.clear(telemetryQueue)
                break
            end
            if #telemetryQueue &gt; 0 then task.wait(1) end
        end
        sendingTelemetry = false
    end)
end
local function remoteToolName(event)
    -- Server accepts only [A-Za-z0-9_-], up to 48 characters.
    local safe=event:gsub("[^%w_-]", "_")
    return safe:sub(1,48)
end
local function saveAnalytics()
    if analyticsEnabled then pcall(function() plugin:SetSetting(ANALYTICS_KEY,analytics) end) end
end
local function recordUsage(event)
    if not analyticsEnabled then return end
    if type(event)~="string" or #event&gt;64 then return end
    analytics.actions[event]=math.min((tonumber(analytics.actions[event]) or 0)+1,10000000)
    saveAnalytics()
    -- Per-tool usage stays local; server only receives one opt-in version activity event.
end
if analyticsEnabled then
    analytics.launches=(tonumber(analytics.launches) or 0)+1
    saveAnalytics()
    enqueueTelemetry("launch", "")
end



local SETTINGS_KEY="ForgeToolsPreferencesV1"
local THEME_PALETTES={
    forge={name="Forge Orange",accent={217,119,6},hover={245,158,11},soft={58,42,24},bg={20,22,24},panel={27,31,35},surface={35,40,46},line={49,56,65}},
    steel={name="Steel Blue",accent={52,143,224},hover={93,176,248},soft={28,47,65},bg={19,23,29},panel={28,35,45},surface={38,47,59},line={57,70,86}},
    emerald={name="Emerald",accent={34,164,117},hover={68,205,151},soft={24,54,43},bg={18,25,22},panel={26,36,32},surface={35,47,41},line={53,70,61}},
    violet={name="Violet",accent={145,103,213},hover={176,139,232},soft={46,34,64},bg={24,21,29},panel={34,29,41},surface={46,39,55},line={69,59,80}},
    crimson={name="Crimson",accent={207,75,87},hover={235,110,119},soft={60,34,40},bg={27,20,23},panel={39,29,33},surface={51,39,44},line={74,55,62}}
}
local function prefColor(rgb) return Color3.fromRGB(rgb[1],rgb[2],rgb[3]) end
local defaults={theme="forge",scale=1,language="RU",moveStep=1,resizeStep=.5,rotateStep=15}
local preferences=readSetting(SETTINGS_KEY)
if type(preferences)~="table" then preferences={} end
for k,v in pairs(defaults) do
    if preferences[k]==nil then preferences[k]=v end
end
if not THEME_PALETTES[preferences.theme] then preferences.theme="forge" end
preferences.scale=tonumber(preferences.scale) or 1
if preferences.scale~=0.85 and preferences.scale~=1 and preferences.scale~=1.1 then preferences.scale=1 end
for k,minV,maxV in pairs({moveStep={.05,100},resizeStep={.05,100},rotateStep={1,90}}) do
    local n=tonumber(preferences[k])
    preferences[k]=n and math.clamp(n,minV[1],minV[2]) or defaults[k]
end
local oldPalette=THEME_PALETTES.forge
local activePalette=THEME_PALETTES[preferences.theme]
local function savePreferences()
    return pcall(function() plugin:SetSetting(SETTINGS_KEY,preferences) end)
end

local C = {
    bg=Color3.fromRGB(20,22,24), panel=Color3.fromRGB(27,31,35),
    surface=Color3.fromRGB(35,40,46), line=Color3.fromRGB(49,56,65),
    white=Color3.fromRGB(243,244,246), muted=Color3.fromRGB(169,178,188),
    blue=Color3.fromRGB(217,119,6), accentHover=Color3.fromRGB(245,158,11),
    accentSoft=Color3.fromRGB(58,42,24), green=Color3.fromRGB(63,164,106),
    red=Color3.fromRGB(201,90,90), yellow=Color3.fromRGB(217,164,65)
}
local LANGUAGE = "RU"
local storedLanguage=readSetting("UIToolsLanguage")
if storedLanguage=="RU" or storedLanguage=="EN" then LANGUAGE=storedLanguage end
if (preferences.language=="RU" or preferences.language=="EN") and storedLanguage==nil then LANGUAGE=preferences.language end
preferences.language=LANGUAGE
local strings={
RU={editor="Редактор GUI",animations="Анимации",animHint="Живой предпросмотр выше списка. Наведи курсор на образец для Hover, нажми для Press. В игре эффекты работают в Play.",animApply="Применить анимацию",animRemove="Удалить анимацию",copylog="Выделить текст лога",logDetail="Выделенная запись",sourcefilter="Источник",typefilter="Тип",selection="Выбор",responsive="Диагностика",gradients="Градиенты",textfx="Анимация цвета",output="Логи",tool="Tool",sentinel="Античит",none="Выдели GUI-объект в Explorer.",name="Название",class="Класс",path="Путь",size="Размер",position="Позиция",visible="Видимость",children="Потомков",resHint="Анализ не изменяет GUI. Кнопка адаптации создаёт контроллер, который реагирует на размер экрана.",noIssues="Базовых замечаний нет.",audit="Анализ выделенного GUI",desktop="ПК",tablet="Планшет",phone="Телефон",gradHint="Выбери GUI-объект. Пресеты можно применить к фону или тексту.",apply="Применить",animation="Анимации",style="Стиль",textHint="Для переливающегося текста выбери TextLabel, TextButton или TextBox.",shine="Перелив цвета",move="Движение градиента",off="Без движения",fxApply="Добавить эффект",fxRemove="Убрать эффект",fxWarning="Скрипт эффекта создаётся в выбранном GUI. Испытай в Play.",logs="Output · сообщения Studio",clear="Очистить список",search="Поиск в логах...",all="Все",errors="Ошибки",warnings="Предупреждения",info="Обычные",client="Клиент",server="Сервер",unknown="Не определено",sourceNote="Studio LogService не гарантирует метку Client/Server. Для точного разделения используй Tool в Play.",install="Установить инструмент",installNote="Tool хранится в ServerStorage. Доступ задаётся явно через список UserId.",installDone="Установлено. Укажи разрешённые UserId перед тестированием.",installed="Tool уже установлен. Нажми обновление скриптов ниже.",emptyLogs="Сообщений нет. Запусти Play или вызови print/warn для теста.",status="Изменения можно отменить через Studio",applied="Применено",selected="Выбрано",preset="Пресет",version="Версия",update="Обновления вручную; источник кода проверяй перед установкой.",copy="Копировать",review="Осмотреть",chooseText="Выбери текстовый GUI-объект.",invalid="Нет подходящих выбранных объектов.",noSource="Панель не видит историю запуска до своего включения, если Roblox её не предоставляет.",inspect="Инспектор выделения"},
EN={editor="GUI Editor",animations="Animations",animHint="Live preview above the list. Hover over the sample for Hover, click it for Press. Applied effects run in Play.",animApply="Apply animation",animRemove="Remove animation",copylog="Select log text",logDetail="Selected entry",sourcefilter="Source",typefilter="Type",selection="Selection",responsive="Diagnostics",gradients="Gradients",textfx="Color Animation",output="Output",tool="Tool",sentinel="Anti-cheat",none="Select a GUI object in Explorer.",name="Name",class="Class",path="Path",size="Size",position="Position",visible="Visible",children="Descendants",resHint="Heuristic warnings; always test on real devices.",noIssues="No basic issues found.",audit="Selected GUI audit",desktop="Desktop",tablet="Tablet",phone="Phone",gradHint="Select a GUI object. Apply presets to backgrounds or text.",apply="Apply",animation="Animation",style="Style",textHint="Select a TextLabel, TextButton, or TextBox for animated text.",shine="Color shimmer",move="Moving gradient",off="Static",fxApply="Add effect",fxRemove="Remove effect",fxWarning="Effect script is stored in selected GUI. Test using Play.",logs="Studio Output",clear="Clear view",search="Search logs...",all="All",errors="Errors",warnings="Warnings",info="Info",client="Client",server="Server",unknown="Unknown",sourceNote="Studio LogService does not reliably identify client/server origin. Use Roblox Studio server/client logs for confirmation.",install="Install developer Tool",installNote="Tool is stored in ServerStorage; server grants by UserId are disabled by default.",installDone="Installed. Fill AllowedUserIds on UIToolsGrant and enable the script.",installed="Tool already exists; no changes made.",emptyLogs="No messages yet. Start Play or use print/warn to test.",status="Changes can be undone in Studio",applied="Applied",selected="Selected",preset="Preset",version="Version",update="Updates are manual. Review source before installing.",copy="Copy",review="Inspect",chooseText="Select a text GUI object.",invalid="No compatible objects selected.",noSource="Earlier logs may be unavailable if Roblox does not provide them.",inspect="Selection inspector"}}
for key,rgb in pairs(activePalette) do
    if key=="accent" then C.blue=prefColor(rgb)
    elseif key=="hover" then C.accentHover=prefColor(rgb)
    elseif key=="soft" then C.accentSoft=prefColor(rgb)
    elseif key~="name" and C[key] then C[key]=prefColor(rgb) end
end
local function t(k) return strings[LANGUAGE][k] or k end
local function make(class,props,parent)
    local o=Instance.new(class)
    for k,v in pairs(props or {}) do o[k]=v end
    o.Parent=parent
    return o
end
local function corner(o,r) make("UICorner",{CornerRadius=UDim.new(0,r or 4)},o) end
local function outline(o,color,thickness)
    make("UIStroke",{Color=color or C.line,Thickness=thickness or 1,Transparency=0.36,ApplyStrokeMode=Enum.ApplyStrokeMode.Border},o)
end
local function label(parent,value,h,col,font,size)
    return make("TextLabel",{Size=UDim2.new(1,-2,0,h or 24),BackgroundTransparency=1,Text=tostring(value),TextColor3=col or C.white,TextWrapped=true,TextXAlignment=Enum.TextXAlignment.Left,TextYAlignment=Enum.TextYAlignment.Center,Font=font or Enum.Font.Gotham,TextSize=size or 13},parent)
end
local TweenService=game:GetService("TweenService")
local function button(parent,value,h)
    local b=make("TextButton",{Size=UDim2.new(1,-2,0,h or 30),BackgroundColor3=C.surface,BorderSizePixel=0,Text=value,TextWrapped=true,Font=Enum.Font.GothamMedium,TextSize=12,TextColor3=C.white,AutoButtonColor=false},parent)
    corner(b,5)
    local currentTween
    local function animate(target)
        if not b.Parent then return end
        if currentTween then currentTween:Cancel() end
        currentTween=TweenService:Create(b,TweenInfo.new(.11,Enum.EasingStyle.Quad,Enum.EasingDirection.Out),{BackgroundColor3=target})
        currentTween:Play()
    end
    
    local pressScale=make("UIScale",{Name="ForgeButtonMotion",Scale=1},b)
    local scaleTween
    local function moveButton(target,duration)
        if not b.Parent then return end
        if scaleTween then scaleTween:Cancel() end
        scaleTween=TweenService:Create(pressScale,TweenInfo.new(duration or .19,Enum.EasingStyle.Quint,Enum.EasingDirection.Out),{Scale=target})
        scaleTween:Play()
    end
    b.MouseEnter:Connect(function() moveButton(1.017,.23) end)
    b.MouseLeave:Connect(function() moveButton(1,.22) end)
    b.MouseButton1Down:Connect(function() moveButton(.967,.10) end)
    b.MouseButton1Up:Connect(function() moveButton(1.017,.24) end)
    local resting=C.surface
    b.MouseEnter:Connect(function()
        resting=b.BackgroundColor3
        if b.Active then animate(resting:Lerp(C.accentHover,.12)) end
    end)
    b.MouseLeave:Connect(function() animate(resting) end)
    b.MouseButton1Down:Connect(function() if b.Active then animate(resting:Lerp(C.accentHover,.20)) end end)
    b.MouseButton1Up:Connect(function() if b.Active then animate(resting:Lerp(C.accentHover,.12)) end end)
    return b
end


local function forgeChoiceIndicator(b,selected)
    local caption=b.Text
    b.Text=""
    b.BackgroundColor3=selected and C.accentSoft or C.panel
    local ring=make("Frame",{Name="ForgeChoiceRing",AnchorPoint=Vector2.new(0,.5),Size=UDim2.fromOffset(14,14),Position=UDim2.new(0,11,.5,0),BackgroundColor3=selected and C.blue or C.surface,BorderSizePixel=0,Active=false},b)
    corner(ring,7)
    if selected then
        local dot=make("Frame",{Name="Center",Size=UDim2.fromOffset(6,6),Position=UDim2.fromOffset(4,4),BackgroundColor3=C.white,BorderSizePixel=0,Active=false},ring)
        corner(dot,3)
        make("Frame",{Name="ForgeChoiceEdge",Size=UDim2.new(0,2,1,-12),Position=UDim2.fromOffset(2,6),BackgroundColor3=C.accentHover,BorderSizePixel=0,Active=false},b)
    else
        outline(ring,C.line,1)
    end
    local captionLabel=make("TextLabel",{
        Name="ForgeChoiceCaption",Position=UDim2.fromOffset(37,0),Size=UDim2.new(1,-47,1,0),
        BackgroundTransparency=1,Text=caption,TextColor3=selected and C.white or C.muted,
        TextSize=b.TextSize,Font=b.Font,TextXAlignment=Enum.TextXAlignment.Left,
        TextYAlignment=Enum.TextYAlignment.Center,TextWrapped=false,TextTruncate=Enum.TextTruncate.AtEnd,
        Active=false
    },b)
    return captionLabel
end
local function line(parent) make("Frame",{Size=UDim2.new(1,-2,0,1),BackgroundColor3=C.line,BorderSizePixel=0},parent) end

local function primaryAction(parent,caption,height)
    local b=button(parent,caption,height or 40)
    b.BackgroundColor3=C.blue
    b.TextColor3=C.white
    b.TextSize=13
    b.FontFace=Font.new("rbxasset://fonts/families/GothamSSm.json",Enum.FontWeight.Bold)
    local accentLine=make("Frame",{Name="ForgePrimaryEdge",Size=UDim2.new(0,3,1,-12),Position=UDim2.fromOffset(1,6),BackgroundColor3=C.accentHover,BorderSizePixel=0},b)
    corner(accentLine,2)
    return b
end
local function sectionHeading(parent,caption)
    local heading=label(parent,string.upper(caption),29,C.accentHover,Enum.Font.GothamBold,11)
    heading.TextXAlignment=Enum.TextXAlignment.Left
    return heading
end
local function helpNote(parent,caption,height)
    local holder=make("Frame",{Size=UDim2.new(1,-2,0,height or 60),BackgroundColor3=C.panel,BorderSizePixel=0},parent)
    corner(holder,6)
    local bar=make("Frame",{Size=UDim2.new(0,3,1,-14),Position=UDim2.fromOffset(4,7),BackgroundColor3=C.blue,BorderSizePixel=0},holder)
    local note=label(holder,caption,(height or 60)-10,C.muted,Enum.Font.Gotham,12)
    note.Position=UDim2.fromOffset(15,5)
    note.Size=UDim2.new(1,-20,1,-10)
    return holder
end

local function path(obj)
    local parts={}
    local p=obj
    while p and p~=game do table.insert(parts,1,p.Name) p=p.Parent end
    return "game."..table.concat(parts,".")
end
local function selectedObjects()
    local result={}
    for _,o in ipairs(Selection:Get()) do if o:IsA("GuiObject") then table.insert(result,o) end end
    return result
end
local TOOL_LOGO_ID = "rbxassetid://82910257800307"
local STUDIO_TOOLBAR_LOGO_ID = "rbxassetid://82910257800307"
local TOOL_ATTRIBUTION = "ForgeTools by lukamodric385"
local toolbar=plugin:CreateToolbar("ForgeTools")
local iconButton=toolbar:CreateButton("ForgeToolsPanel", TOOL_ATTRIBUTION.." · "..VERSION, STUDIO_TOOLBAR_LOGO_ID, "ForgeTools")
local widget=plugin:CreateDockWidgetPluginGuiAsync("ForgeTools_Dock_v02",DockWidgetPluginGuiInfo.new(Enum.InitialDockState.Float,false,true,760,760,520,520))
widget.Title="ForgeTools  ·  "..VERSION
local bg=make("Frame",{Size=UDim2.fromScale(1,1),BackgroundColor3=C.bg,BorderSizePixel=0},widget)
local FORGE_BACKGROUND_ASSET="rbxassetid://128313222919175"
local backgroundTexture=make("ImageLabel",{
    Name="ForgeCarbonBackdrop",
    Size=UDim2.fromScale(1,1),
    BackgroundTransparency=1,
    Image=FORGE_BACKGROUND_ASSET,
    ImageColor3=Color3.fromRGB(219,225,234),
    ImageTransparency=.64,
    ScaleType=Enum.ScaleType.Stretch,
    BorderSizePixel=0,
    ZIndex=0
},bg)

local forgeWindowScale=make("UIScale",{Scale=preferences.scale},bg)
local function applyWindowScale()
    forgeWindowScale.Scale=preferences.scale
    bg.Size=UDim2.fromScale(1/preferences.scale,1/preferences.scale)
end
applyWindowScale()
make("UIPadding",{PaddingLeft=UDim.new(0,10),PaddingRight=UDim.new(0,10),PaddingTop=UDim.new(0,8),PaddingBottom=UDim.new(0,8)},bg)
local head=make("Frame",{Size=UDim2.new(1,0,0,52),BackgroundColor3=C.panel,BorderSizePixel=0},bg)
corner(head,7)
make("Frame",{Name="ForgeAccentRule",Size=UDim2.new(1,-16,0,2),Position=UDim2.new(0,8,1,-3),BackgroundColor3=C.blue,BorderSizePixel=0},head)
local brand=label(head,"FORGE  /  TOOLS",26,C.white,Enum.Font.GothamBold,19)
brand.Position=UDim2.fromOffset(12,4)
brand.Size=UDim2.new(1,-112,0,25)
brand.FontFace=Font.new("rbxasset://fonts/families/GothamSSm.json",Enum.FontWeight.Bold)
local brandSub=label(head,"by lukamodric385   ·   v"..VERSION,16,C.muted,Enum.Font.Gotham,10)
brandSub.Position=UDim2.fromOffset(13,27)
brandSub.Size=UDim2.new(1,-112,0,16)
-- Header utilities: both actions have consistent 24px icons and bilingual labels.
local settingsButton=make("TextButton",{
    Name="ForgeSettingsButton",AnchorPoint=Vector2.new(1,0),Position=UDim2.new(1,-12,0,3),
    Size=UDim2.fromOffset(55,30),BackgroundColor3=C.surface,BorderSizePixel=0,
    Text="⚙",TextColor3=C.white,TextSize=21,Font=Enum.Font.GothamBold,AutoButtonColor=true
},head)
corner(settingsButton,6)
outline(settingsButton,C.line,1)
local feedbackButton=make("ImageButton",{
    Name="ForgeFeedbackButton",AnchorPoint=Vector2.new(1,0),Position=UDim2.new(1,-75,0,3),
    Size=UDim2.fromOffset(55,30),BackgroundColor3=C.surface,BorderSizePixel=0,
    Image="rbxassetid://73554913137506",ScaleType=Enum.ScaleType.Fit,AutoButtonColor=true
},head)
corner(feedbackButton,6)
outline(feedbackButton,C.line,1)
make("UIPadding",{PaddingTop=UDim.new(0,4),PaddingBottom=UDim.new(0,4),PaddingLeft=UDim.new(0,16),PaddingRight=UDim.new(0,16)},feedbackButton)
local settingsCaption=label(head,"",13,C.muted,Enum.Font.Gotham,9)
settingsCaption.Name="ForgeSettingsCaption"
settingsCaption.AnchorPoint=Vector2.new(1,0)
settingsCaption.Position=UDim2.new(1,-12,0,35)
settingsCaption.Size=UDim2.fromOffset(55,13)
settingsCaption.TextXAlignment=Enum.TextXAlignment.Center
settingsCaption.TextWrapped=false
local feedbackCaption=label(head,"",13,C.muted,Enum.Font.Gotham,9)
feedbackCaption.Name="ForgeFeedbackCaption"
feedbackCaption.AnchorPoint=Vector2.new(1,0)
feedbackCaption.Position=UDim2.new(1,-75,0,35)
feedbackCaption.Size=UDim2.fromOffset(55,13)
feedbackCaption.TextXAlignment=Enum.TextXAlignment.Center
feedbackCaption.TextWrapped=false
brand.Size=UDim2.new(1,-145,0,25)
brandSub.Size=UDim2.new(1,-145,0,16)
local selectionSummary=make("TextLabel",{Position=UDim2.fromOffset(5,60),Size=UDim2.new(1,-10,0,23),BackgroundTransparency=1,BorderSizePixel=0,TextColor3=C.muted,Font=Enum.Font.Gotham,TextSize=12,TextTruncate=Enum.TextTruncate.AtEnd,TextXAlignment=Enum.TextXAlignment.Left},bg)
local nav=make("Frame",{Position=UDim2.fromOffset(0,88),Size=UDim2.new(1,0,0,116),BackgroundTransparency=1},bg)
local main=make("Frame",{Position=UDim2.fromOffset(0,210),Size=UDim2.new(1,0,1,-245),BackgroundTransparency=1},bg)
local foot=make("TextLabel",{AnchorPoint=Vector2.new(0,1),Position=UDim2.new(0,0,1,0),Size=UDim2.new(1,0,0,25),BackgroundTransparency=1,TextColor3=C.muted,Font=Enum.Font.Gotham,TextSize=11,TextTruncate=Enum.TextTruncate.AtEnd,TextXAlignment=Enum.TextXAlignment.Left,Text="ForgeTools  ·  "..VERSION},bg)
local function applyTheme(nextTheme)
    local newPalette=THEME_PALETTES[nextTheme]
    if not newPalette then return end
    local previous={}
    for key,value in pairs(C) do previous[key]=value end
    for key,rgb in pairs(newPalette) do
        if key=="accent" then C.blue=prefColor(rgb)
        elseif key=="hover" then C.accentHover=prefColor(rgb)
        elseif key=="soft" then C.accentSoft=prefColor(rgb)
        elseif key~="name" and C[key] then C[key]=prefColor(rgb) end
    end
    local oldToNew={}
    for key,oldValue in pairs(previous) do
        if C[key] then oldToNew[oldValue:ToHex()]=C[key] end
    end
    for _,obj in ipairs(widget:GetDescendants()) do
        if obj:IsA("GuiObject") then
            for _,property in ipairs({"BackgroundColor3","TextColor3","ImageColor3","ScrollBarImageColor3"}) do
                local ok,oldColor=pcall(function() return obj[property] end)
                local mapped=ok and oldToNew[oldColor:ToHex()]
                if mapped then pcall(function() obj[property]=mapped end) end
            end
        elseif obj:IsA("UIStroke") then
            local mapped=oldToNew[obj.Color:ToHex()]
            if mapped then obj.Color=mapped end
        end
    end
end
local selectedSection="ui"
local selectedTab="home"
local NAV_ICONS={} 
local navButtons={}
local draw
local lastAnimatedTab=nil
local acceptedNotice=false
local welcomeVisible=false
local welcomeShownThisSession=false
local function showSystemWelcome(force)
    if not widget.Enabled or welcomeVisible or (welcomeShownThisSession and not force) or not acceptedNotice then return end
    welcomeVisible=true
    welcomeShownThisSession=true
    local overlay=make("Frame",{Name="ForgeSystemWelcome",Size=UDim2.fromScale(1,1),BackgroundColor3=C.bg,BackgroundTransparency=0,BorderSizePixel=0,ZIndex=210},bg)
    local welcomeBackdrop=make("ImageLabel",{Name="WelcomeCarbon",Size=UDim2.fromScale(1,1),BackgroundTransparency=1,Image=FORGE_BACKGROUND_ASSET,ImageTransparency=.24,ImageColor3=Color3.fromRGB(225,230,235),ScaleType=Enum.ScaleType.Stretch,ZIndex=211},overlay)
    local shade=make("Frame",{Name="WelcomeShade",Size=UDim2.fromScale(1,1),BackgroundColor3=C.bg,BackgroundTransparency=.58,BorderSizePixel=0,ZIndex=212},overlay)
    make("UIGradient",{Rotation=90,Transparency=NumberSequence.new({NumberSequenceKeypoint.new(0,.42),NumberSequenceKeypoint.new(.48,.79),NumberSequenceKeypoint.new(1,.35)})},shade)
    local kicker=make("TextLabel",{Position=UDim2.new(0,22,.31,0),Size=UDim2.new(1,-44,0,22),BackgroundTransparency=1,Text=LANGUAGE=="RU" and "FORGE / SYSTEM" or "FORGE / SYSTEM",Font=Enum.Font.GothamMedium,TextSize=12,TextXAlignment=Enum.TextXAlignment.Left,TextColor3=C.accentHover,TextTransparency=1,ZIndex=213},overlay)
    local greeting=make("TextLabel",{Position=UDim2.new(0,21,.36,12),Size=UDim2.new(1,-42,0,70),BackgroundTransparency=1,Text=LANGUAGE=="RU" and "С возвращением" or "Welcome back",Font=Enum.Font.GothamMedium,TextSize=math.min(32,preferences.scale&gt;1 and 29 or 32),TextWrapped=true,TextXAlignment=Enum.TextXAlignment.Left,TextColor3=C.white,TextTransparency=1,ZIndex=213},overlay)
    local accent=make("Frame",{Name="AccentRule",Position=UDim2.new(0,23,.50,-3),Size=UDim2.fromOffset(46,2),BackgroundColor3=C.accentHover,BackgroundTransparency=.15,BorderSizePixel=0,ZIndex=213},overlay)
    local sub=make("TextLabel",{Position=UDim2.new(0,23,.51,0),Size=UDim2.new(1,-46,0,30),BackgroundTransparency=1,Text="ForgeTools  /  "..VERSION,Font=Enum.Font.Gotham,TextSize=12,TextColor3=C.muted,TextTransparency=1,TextXAlignment=Enum.TextXAlignment.Left,ZIndex=213},overlay)
    local enter=TweenInfo.new(.45,Enum.EasingStyle.Quart,Enum.EasingDirection.Out)
    TweenService:Create(kicker,enter,{TextTransparency=0}):Play()
    TweenService:Create(greeting,enter,{TextTransparency=0,Position=UDim2.new(0,21,.36,0)}):Play()
    TweenService:Create(sub,TweenInfo.new(.65,Enum.EasingStyle.Sine,Enum.EasingDirection.Out),{TextTransparency=0}):Play()
    task.delay(1.7,function()
        if not overlay.Parent then welcomeVisible=false return end
        local exit=TweenInfo.new(.44,Enum.EasingStyle.Quart,Enum.EasingDirection.Out)
        TweenService:Create(kicker,exit,{TextTransparency=1}):Play()
        TweenService:Create(greeting,exit,{TextTransparency=1,Position=UDim2.new(0,21,.36,-10)}):Play()
        TweenService:Create(sub,exit,{TextTransparency=1}):Play()
        TweenService:Create(welcomeBackdrop,exit,{ImageTransparency=1}):Play()
        TweenService:Create(shade,exit,{BackgroundTransparency=1}):Play()
        TweenService:Create(accent,exit,{BackgroundTransparency=1}):Play()
        local closeTween=TweenService:Create(overlay,exit,{BackgroundTransparency=1})
        closeTween:Play()
        closeTween.Completed:Connect(function()
            if overlay.Parent then overlay:Destroy() end
            welcomeVisible=false
        end)
    end)
end
local scrollPositions={}
local lastScroller=nil
local lastScrollerTab=nil
local function makeScroller()
    if lastScroller and lastScroller.Parent then
        scrollPositions[lastScrollerTab or selectedTab]=lastScroller.CanvasPosition
    end
    for _,o in ipairs(main:GetChildren()) do o:Destroy() end
    local sc=make("ScrollingFrame",{Size=UDim2.fromScale(1,1),BackgroundTransparency=1,BorderSizePixel=0,ScrollBarThickness=4,ScrollBarImageColor3=C.muted,CanvasSize=UDim2.new(),AutomaticCanvasSize=Enum.AutomaticSize.Y},main)
    make("UIPadding",{PaddingRight=UDim.new(0,7),PaddingBottom=UDim.new(0,8)},sc)
    make("UIListLayout",{Padding=UDim.new(0,4),SortOrder=Enum.SortOrder.LayoutOrder},sc)
    lastScroller=sc
    lastScrollerTab=selectedTab
    local saved=scrollPositions[selectedTab]
    if saved then
        task.defer(function()
            if sc.Parent then sc.CanvasPosition=saved end
        end)
    end
    return sc
end
local function stat(sc,key,value)
    local r=make("Frame",{Size=UDim2.new(1,-1,0,28),BackgroundColor3=C.panel,BorderSizePixel=0},sc)
    corner(r,4)
    outline(r,C.line,1)
    make("TextLabel",{Size=UDim2.new(0.35,0,1,0),Position=UDim2.fromOffset(8,0),Text=key,FontFace=Font.new("rbxasset://fonts/families/GothamSSm.json",Enum.FontWeight.SemiBold),TextSize=12,TextColor3=C.muted,BackgroundTransparency=1,TextXAlignment=Enum.TextXAlignment.Left},r)
    local valueLabel=make("TextLabel",{Size=UDim2.new(.63,-8,1,0),Position=UDim2.fromScale(.35,0),Text=tostring(value),Font=Enum.Font.GothamBold,TextSize=12,TextTruncate=Enum.TextTruncate.AtEnd,TextColor3=C.white,BackgroundTransparency=1,TextXAlignment=Enum.TextXAlignment.Left},r)
    return valueLabel
end
local function selectionPage(sc)
    label(sc,t("inspect"),27,C.blue,Enum.Font.GothamBold,16)
    local list=Selection:Get()
    stat(sc,t("selected"),#list)
    if #list==0 then label(sc,t("none"),50,C.muted) return end
    for i,o in ipairs(list) do
        if i&gt;15 then label(sc,"+"..(#list-15),20,C.muted) break end
        local b=button(sc,o.Name.."   ·   "..o.ClassName,32)
        b.MouseButton1Click:Connect(function() Selection:Set({o}) end)
        stat(sc,t("path"),path(o))
        if o:IsA("GuiObject") then
            stat(sc,t("size"),o.Size)
            stat(sc,t("position"),o.Position)
            stat(sc,"AnchorPoint",o.AnchorPoint)
            stat(sc,"ZIndex",o.ZIndex)
            stat(sc,t("visible"),o.Visible)
        end
        stat(sc,t("children"),#o:GetDescendants())
        line(sc)
    end
end
local function changeAll(callback,waypoint)
    local n=0
    ChangeHistoryService:SetWaypoint("UITools Before "..waypoint)
    for _,o in ipairs(selectedObjects()) do
        local ok=pcall(function() if callback(o) then n+=1 end end)
        if not ok then warn("UITools: unable to edit "..o.Name) end
    end
    ChangeHistoryService:SetWaypoint("UITools "..waypoint)
    foot.Text=t("applied")..": "..n.." · "..t("status")
end

local RESPONSIVE_RUNTIME = require(script:WaitForChild("Modules"):WaitForChild("RESPONSIVE_RUNTIME"))
local RESPONSIVE_CONTROLLER = require(script:WaitForChild("Modules"):WaitForChild("RESPONSIVE_CONTROLLER"))
local function ensureResponsiveModule()
    local module=ReplicatedStorage:FindFirstChild("UIToolsResponsiveRuntime")
    if module and not module:IsA("ModuleScript") then error("UIToolsResponsiveRuntime name collision") end
    if not module then module=make("ModuleScript",{Name="UIToolsResponsiveRuntime",Source=RESPONSIVE_RUNTIME},ReplicatedStorage) end
    module.Source=RESPONSIVE_RUNTIME
    return module
end


local function repairResponsiveDependency()
    if ReplicatedStorage:FindFirstChild("UIToolsResponsiveRuntime") then return end
    local hasController = false
    for _, object in ipairs(game:GetDescendants()) do
        if object.Name == "UIToolsResponsiveController" and object:IsA("LocalScript") then
            hasController = true
            break
        end
    end
    if not hasController then return end
    local ok, err = pcall(ensureResponsiveModule)
    if ok then
        warn("[UITools Responsive] Restored missing UIToolsResponsiveRuntime in ReplicatedStorage. Save and publish the place to persist this repair.")
    else
        warn("[UITools Responsive] Could not restore runtime: " .. tostring(err))
    end
end
repairResponsiveDependency()
local baselineIndex=1
local BASELINES={
    {ru=" Телефон (390×844)",en=" Phone (390×844)",w=390,h=844},
    {ru=" Планшет (820×1180)",en=" Tablet (820×1180)",w=820,h=1180},
    {ru=" ПК (1366×768)",en=" Desktop (1366×768)",w=1366,h=768}
}
local DEVICE_PROFILES={
    {name="Compact phone · 360 × 780",w=360,h=780},
    {name="iPhone size · 390 × 844",w=390,h=844},
    {name="Large phone · 430 × 932",w=430,h=932},
    {name="Small tablet · 768 × 1024",w=768,h=1024},
    {name="Tablet landscape · 1024 × 768",w=1024,h=768},
    {name="Laptop · 1366 × 768",w=1366,h=768},
    {name="Desktop · 1920 × 1080",w=1920,h=1080},
    {name="Wide display · 2560 × 1440",w=2560,h=1440},
    {name="4K display · 3840 × 2160",w=3840,h=2160}
}
local deviceIndex=2
local GUI_DIAGNOSTICS = require(script:WaitForChild("Modules"):WaitForChild("GUI_DIAGNOSTICS"))
local diagnosticSummary={}
local function auditPage(sc)
    local device=DEVICE_PROFILES[deviceIndex]
    label(sc,LANGUAGE=="RU" and "Диагностика GUI (предварительная)" or "GUI diagnostics (estimate)",32,C.white,Enum.Font.GothamBold,17)
    label(sc,LANGUAGE=="RU" and "Выдели ScreenGui в Explorer. Проверка найдёт проблемные элементы, ничего не изменяя." or "Select a ScreenGui in Explorer. Detect issues without changing objects.",54,C.muted)
    local switch=button(sc,(LANGUAGE=="RU" and "Экран: " or "Viewport: ")..device.name.."  ▼",39)
    switch.MouseButton1Click:Connect(function() deviceIndex=deviceIndex%#DEVICE_PROFILES+1 draw() end)
    local roots=Selection:Get()
    local checked={}
    for _,obj in ipairs(roots) do
        if obj:IsA("GuiObject") or obj:IsA("LayerCollector") then table.insert(checked,obj) end
    end
    if #checked==0 then
        label(sc,LANGUAGE=="RU" and "Ничего не выбрано. Сначала выдели ScreenGui или элемент интерфейса." or "Nothing selected. Select a ScreenGui or UI element to begin.",68,C.yellow)
    end
    local found,stats=GUI_DIAGNOSTICS.Scan(checked,device.w,device.h)
    stat(sc,LANGUAGE=="RU" and "Объектов / предупреждений" or "Objects / warnings",stats.objects.." / "..#found)
    stat(sc,LANGUAGE=="RU" and "Градиентов / анимаций" or "Gradients / animations",stats.gradients.." / "..stats.animations)
    local critical,important=0,0
    for _,item in ipairs(found) do
        if item.level==3 then critical+=1 elseif item.level==2 then important+=1 end
    end
    stat(sc,LANGUAGE=="RU" and "Критичных / важных" or "Critical / important",critical.." / "..important)
    if #found==0 and #checked&gt;0 then label(sc,LANGUAGE=="RU" and "По статической проверке проблем не найдено. Проверь интерфейс в Device Emulator." or "No static warnings. Verify in Studio Device Emulator.",55,C.green) end
    if #found&gt;0 then
        label(sc,LANGUAGE=="RU" and "НАЖМИ НА ПРОБЛЕМУ — ВЫДЕЛЮ ОБЪЕКТ" or "SELECT A WARNING TO LOCATE OBJECT",26,C.blue,Enum.Font.GothamBold,12)
    end
    for i,item in ipairs(found) do
        if i&gt;60 then label(sc,"+"..(#found-60),24,C.muted) break end
        local symbol=item.level==3 and "!! " or item.level==2 and "! " or "· "
        local b=button(sc,symbol..item.object.Name.."  ·  "..(LANGUAGE=="RU" and item.ru or item.en),37)
        b.TextWrapped=true
        b.TextXAlignment=Enum.TextXAlignment.Left
        b.TextColor3=item.level==3 and C.red or item.level==2 and C.yellow or C.muted
        b.MouseButton1Click:Connect(function() Selection:Set({item.object}) end)
    end
    if #checked&gt;0 and #found&gt;0 then
        local fixes={}
        for _,issue in ipairs(found) do
            if issue.kind=="textConstraint" then table.insert(fixes,issue.object) end
        end
        if #fixes&gt;0 then
            label(sc,LANGUAGE=="RU" and "БЕЗОПАСНОЕ ИСПРАВЛЕНИЕ" or "SAFE FIX",25,C.blue,Enum.Font.GothamBold,13)
            label(sc,LANGUAGE=="RU" and "Добавить UITextSizeConstraint только объектам, у которых его нет. Остальные свойства не меняются." or "Add UITextSizeConstraint only where missing. No other properties are modified.",55,C.muted)
            local fix=button(sc,(LANGUAGE=="RU" and "Добавить ограничение текста: " or "Add text constraints: ")..#fixes,39)
            fix.MouseButton1Click:Connect(function()
                ChangeHistoryService:SetWaypoint("ForgeTools Before Text Constraints")
                local count=0
                for _,o in ipairs(fixes) do
                    if o.Parent and o.TextScaled and not o:FindFirstChildOfClass("UITextSizeConstraint") then
                        make("UITextSizeConstraint",{MinTextSize=10,MaxTextSize=48},o)
                        count+=1
                    end
                end
                ChangeHistoryService:SetWaypoint("ForgeTools Text Constraints")
                foot.Text=(LANGUAGE=="RU" and "Добавлено ограничений: " or "Constraints added: ")..count
                draw()
            end)
        end
    end
    label(sc,LANGUAGE=="RU" and "Примечание: координаты вычисляются приближённо; layout, UIScale и constraints влияют на фактический размер. Проверяй итог в Roblox Studio Device Emulator." or "Estimated geometry only: layout, UIScale and constraints affect true positions. Verify in Studio Device Emulator.",70,C.muted)
    line(sc)
    label(sc,LANGUAGE=="RU" and "АВТОМАСШТАБ · работает во время игры" or "AUTO SCALE · active during play",30,C.blue,Enum.Font.GothamBold,15)
    label(sc,LANGUAGE=="RU" and "Выбери устройство, для которого GUI сейчас выглядит правильно. Модуль будет менять UIScale при изменении окна, повороте телефона и запуске на ПК." or "Choose the device on which the GUI currently looks correct. The module updates UIScale when viewport size changes.",71,C.muted)
    local baseline=BASELINES[baselineIndex]
    local baselineButton=button(sc,(LANGUAGE=="RU" and "Исходный дизайн: " or "Designed for: ")..(LANGUAGE=="RU" and baseline.ru or baseline.en).."  v",42)
    baselineButton.MouseButton1Click:Connect(function() baselineIndex=baselineIndex%#BASELINES+1 draw() end)
    local apply=button(sc,LANGUAGE=="RU" and "OK Включить автоадаптацию" or "OK Enable responsive scaling",43)
    apply.BackgroundColor3=C.blue
    apply.MouseButton1Click:Connect(function()
        local roots=selectedObjects()
        if #roots==0 then foot.Text=t("none") return end
        local b=BASELINES[baselineIndex]
        ChangeHistoryService:SetWaypoint("UITools Before Responsive Install")
        local count=0
        for _,o in ipairs(roots) do
            local ok,err=pcall(function()
                if not o:FindFirstAncestorOfClass("ScreenGui") then return end
                ensureResponsiveModule()
                local scale=o:FindFirstChild("UIToolsResponsiveScale")
                if scale and not scale:IsA("UIScale") then error("UIScale name collision") end
                if not scale then scale=make("UIScale",{Name="UIToolsResponsiveScale",Scale=1},o) end
                o:SetAttribute("UIToolsReferenceWidth",b.w)
                o:SetAttribute("UIToolsReferenceHeight",b.h)
                o:SetAttribute("UIToolsMinScale",0.6)
                o:SetAttribute("UIToolsMaxScale",1.8)
                local ctrl=o:FindFirstChild("UIToolsResponsiveController")
                if ctrl and not ctrl:IsA("LocalScript") then error("Controller name collision") end
                if not ctrl then ctrl=make("LocalScript",{Name="UIToolsResponsiveController",Source=RESPONSIVE_CONTROLLER},o) end
                ctrl.Source=RESPONSIVE_CONTROLLER
                count+=1
            end)
            if not ok then warn("UITools Responsive: "..tostring(err)) end
        end
        ChangeHistoryService:SetWaypoint("UITools Responsive Installed")
        foot.Text=(LANGUAGE=="RU" and "Динамическая адаптация включена: " or "Responsive installed: ")..count
    end)
    local remove=button(sc,LANGUAGE=="RU" and "Удалить адаптацию UITools" or "Remove UITools responsive",35)
    remove.MouseButton1Click:Connect(function()
        changeAll(function(o)
            local removed=false
            for _,name in ipairs({"UIToolsResponsiveController","UIToolsResponsiveScale"}) do
                local child=o:FindFirstChild(name)
                if child then child:Destroy() removed=true end
            end
            return removed
        end,"Remove Responsive")
    end)
    label(sc,LANGUAGE=="RU" and "Модуль масштабирует выбранный GUI динамически; положение задаётся отдельно ниже. Для сложных меню может понадобиться адаптивная перестройка внутренних элементов." or "The module dynamically scales selected GUI. Position is configured separately below. Complex menus may need layout changes.",69,C.yellow)
    line(sc)
    label(sc,LANGUAGE=="RU" and "РАСПОЛОЖЕНИЕ · AnchorPoint / Position" or "POSITION · AnchorPoint / Position",28,C.blue,Enum.Font.GothamBold,15)
    label(sc,LANGUAGE=="RU" and "Выбери контейнер или кнопку. Расположение изменится относительно родителя: центр, угол или край экрана. К элементам внутри UIListLayout/UIGridLayout не применяй без проверки." or "Choose a container or control. Position is relative to its parent. Check layout-managed children manually.",66,C.muted)
    local anchors={
      {ru="NW Сверху слева",en="NW Top left",x=0,y=0},
      {ru="UP Сверху",en="UP Top center",x=.5,y=0},
      {ru="NE Сверху справа",en="NE Top right",x=1,y=0},
      {ru="LEFT Слева",en="LEFT Center left",x=0,y=.5},
      {ru="+ Центр",en="+ Center",x=.5,y=.5},
      {ru="RIGHT Справа",en="RIGHT Center right",x=1,y=.5},
      {ru="SW Снизу слева",en="SW Bottom left",x=0,y=1},
      {ru="DOWN Снизу",en="DOWN Bottom center",x=.5,y=1},
      {ru="SE Снизу справа",en="SE Bottom right",x=1,y=1}
    }
    local positions=make("Frame",{Size=UDim2.new(1,-1,0,129),BackgroundTransparency=1},sc)
    make("UIGridLayout",{CellSize=UDim2.new(1/3,-4,0,39),CellPadding=UDim2.fromOffset(5,5)},positions)
    for _,a in ipairs(anchors) do
        local b=button(positions,LANGUAGE=="RU" and a.ru or a.en,37)
        b.TextSize=11
        b.MouseButton1Click:Connect(function()
            changeAll(function(o)
                if o.Parent and (o.Parent:FindFirstChildOfClass("UIListLayout") or o.Parent:FindFirstChildOfClass("UIGridLayout")) then return false end
                o.AnchorPoint=Vector2.new(a.x,a.y)
                o.Position=UDim2.fromScale(a.x,a.y)
                return true
            end,"Position anchors")
        end)
    end

end
local PRESETS={
{name="Ocean",ru="Океан",a=Color3.fromRGB(0,100,190),b=Color3.fromRGB(57,231,255)},
{name="Electric",ru="Электро",a=Color3.fromRGB(37,98,255),b=Color3.fromRGB(162,86,255)},
{name="Mint",ru="Мята",a=Color3.fromRGB(14,157,135),b=Color3.fromRGB(116,252,172)},
{name="Sunset",ru="Закат",a=Color3.fromRGB(255,123,68),b=Color3.fromRGB(255,206,104)},
{name="Rose",ru="Роза",a=Color3.fromRGB(184,41,100),b=Color3.fromRGB(255,137,170)},
{name="Gold",ru="Золото",a=Color3.fromRGB(139,91,28),b=Color3.fromRGB(255,219,103)},
{name="Ice",ru="Лёд",a=Color3.fromRGB(88,174,215),b=Color3.fromRGB(220,248,255)},
{name="Royal",ru="Королевский",a=Color3.fromRGB(75,59,180),b=Color3.fromRGB(168,127,255)},
{name="Graphite",ru="Графит",a=Color3.fromRGB(35,46,65),b=Color3.fromRGB(108,129,153)},
{name="Lime",ru="Лайм",a=Color3.fromRGB(100,157,38),b=Color3.fromRGB(218,255,102)},
{name="Crimson",ru="Багрянец",a=Color3.fromRGB(133,33,55),b=Color3.fromRGB(245,76,91)},
{name="Sky",ru="Небо",a=Color3.fromRGB(21,123,232),b=Color3.fromRGB(125,195,255)},
{name="Aurora",ru="Сияние",a=Color3.fromRGB(28,202,157),b=Color3.fromRGB(64,94,255)},
{name="Lavender",ru="Лаванда",a=Color3.fromRGB(122,101,233),b=Color3.fromRGB(234,168,255)},
{name="Fire",ru="Пламя",a=Color3.fromRGB(255,65,48),b=Color3.fromRGB(255,191,49)},
{name="Candy",ru="Карамель",a=Color3.fromRGB(255,90,172),b=Color3.fromRGB(112,183,255)},
{name="Forest",ru="Лес",a=Color3.fromRGB(16,88,57),b=Color3.fromRGB(111,216,103)},
{name="Steel",ru="Сталь",a=Color3.fromRGB(62,79,100),b=Color3.fromRGB(166,193,219)},
{name="Neon Blue",ru="Неон синий",a=Color3.fromRGB(0,58,222),b=Color3.fromRGB(0,255,252)},
{name="Ruby",ru="Рубин",a=Color3.fromRGB(85,18,70),b=Color3.fromRGB(244,63,103)},
{name="Amber",ru="Янтарь",a=Color3.fromRGB(128,53,9),b=Color3.fromRGB(255,215,77)},
{name="Deep Sea",ru="Глубина",a=Color3.fromRGB(11,38,87),b=Color3.fromRGB(38,166,194)},
{name="Pearl",ru="Жемчуг",a=Color3.fromRGB(180,195,214),b=Color3.fromRGB(253,241,249)},
{name="Mist",ru="Туман",a=Color3.fromRGB(87,109,122),b=Color3.fromRGB(206,216,224)},
{name="Copper",ru="Медь",a=Color3.fromRGB(87,45,29),b=Color3.fromRGB(240,164,103)},
{name="Deep Mint",ru="Тёмная мята",a=Color3.fromRGB(28,119,116),b=Color3.fromRGB(187,255,206)},
{name="Twilight",ru="Сумерки",a=Color3.fromRGB(39,42,84),b=Color3.fromRGB(208,134,191)},
{name="Dark Lime",ru="Тёмный лайм",a=Color3.fromRGB(37,95,34),b=Color3.fromRGB(213,242,94)},
{name="Dark Graphite",ru="Тёмный графит",a=Color3.fromRGB(35,39,44),b=Color3.fromRGB(114,125,139)},
{name="Rainbow",ru="Радуга",a=Color3.fromRGB(255,65,99),b=Color3.fromRGB(81,139,255)}
}
local function presetName(p) return LANGUAGE=="RU" and p.ru or p.name end
local function presetSequence(p)
    if p.name=="Rainbow" then
        return ColorSequence.new({
            ColorSequenceKeypoint.new(0,Color3.fromRGB(255,65,99)),
            ColorSequenceKeypoint.new(.2,Color3.fromRGB(255,208,65)),
            ColorSequenceKeypoint.new(.4,Color3.fromRGB(79,239,132)),
            ColorSequenceKeypoint.new(.6,Color3.fromRGB(63,203,255)),
            ColorSequenceKeypoint.new(.8,Color3.fromRGB(134,94,250)),
            ColorSequenceKeypoint.new(1,Color3.fromRGB(255,65,99))})
    end
    return ColorSequence.new(p.a,p.b)
end
local activePreset=1
local gradientMode="Background"
local function gradientPage(sc)
    label(sc,t("gradients").." · "..#PRESETS,28,C.blue,Enum.Font.GothamBold,16)
    label(sc,t("gradHint"),34,C.muted)
    label(sc,(LANGUAGE=="RU" and "Предпросмотр: " or "Preview: ")..presetName(PRESETS[activePreset]),21,C.muted)
    local preview=make("Frame",{Size=UDim2.new(1,-2,0,35),BackgroundColor3=C.white,BorderSizePixel=0},sc)
    corner(preview,4)
    make("UIGradient",{Color=presetSequence(PRESETS[activePreset])},preview)
    local mode=button(sc,(LANGUAGE=="RU" and "Куда применить: " or "Apply to: ")..(gradientMode=="Text" and (LANGUAGE=="RU" and "Текст" or "Text") or (LANGUAGE=="RU" and "Фон" or "Background")).."  ▼",32)
    mode.MouseButton1Click:Connect(function() gradientMode=gradientMode=="Background" and "Text" or "Background" draw() end)
    for i,p in ipairs(PRESETS) do
        local row=make("Frame",{Size=UDim2.new(1,-1,0,43),BackgroundColor3=i==activePreset and C.surface or C.panel,BorderSizePixel=0},sc)
        corner(row,4)
        outline(row,C.line,1)
        local btn=make("TextButton",{Size=UDim2.new(.60,0,1,0),BackgroundColor3=i==activePreset and C.accentSoft or C.panel,BorderSizePixel=0,Text=presetName(p),Font=Enum.Font.GothamMedium,TextSize=12,AutoButtonColor=false},row)
        forgeChoiceIndicator(btn,i==activePreset)
        local swatch=make("Frame",{AnchorPoint=Vector2.new(1,.5),Position=UDim2.new(1,-9,.5,0),Size=UDim2.new(.35,0,0,27),BackgroundColor3=Color3.new(1,1,1),BorderSizePixel=0},row)
        corner(swatch,5)
        make("UIGradient",{Color=presetSequence(p)},swatch)
        btn.MouseButton1Click:Connect(function()activePreset=i draw()end)
        local choose=make("TextButton",{Size=UDim2.fromScale(1,1),BackgroundTransparency=1,Text="",ZIndex=2},swatch)
        choose.MouseButton1Click:Connect(function()activePreset=i draw()end)
    end
    local apply=button(sc,t("apply").." · "..presetName(PRESETS[activePreset]),38)
    apply.BackgroundColor3=C.blue
    apply.MouseButton1Click:Connect(function()
        local p=PRESETS[activePreset]
        changeAll(function(o)
            if gradientMode=="Text" and not (o:IsA("TextLabel") or o:IsA("TextButton") or o:IsA("TextBox")) then return false end
            local g=o:FindFirstChild("UIToolsGradient")
            if not g then g=make("UIGradient",{Name="UIToolsGradient"},o) end
            g.Color=presetSequence(p)
            return true
        end,"Gradient")
    end)
end
local GRADIENT_ANIM_SOURCE = require(script:WaitForChild("Modules"):WaitForChild("GRADIENT_ANIM_SOURCE"))
local gradientMotion="slide"
local gradientSpeed=0.2
local function textPage(sc)
    label(sc,t("textfx").." · UIGradient",32,C.blue,Enum.Font.GothamBold,16)
    label(sc,LANGUAGE=="RU" and "Здесь настраивается движение градиента, который уже применён к тексту или фону." or "Gradients define colors. This tab animates the EXISTING gradient on text or backgrounds.",62,C.muted)
    local demoContainer=make("Frame",{Size=UDim2.new(1,-2,0,63),BackgroundColor3=C.panel,BorderSizePixel=0},sc)
    corner(demoContainer,7)
    local demo=make("TextLabel",{Size=UDim2.new(1,-18,1,0),Position=UDim2.fromOffset(9,0),BackgroundTransparency=1,Text="FORGETOOLS",Font=Enum.Font.GothamBold,TextScaled=true,TextColor3=C.white,TextStrokeColor3=C.bg,TextStrokeTransparency=0.12},demoContainer)
    make("UITextSizeConstraint",{MaxTextSize=21,MinTextSize=12},demo)
    local demoGradient=make("UIGradient",{Color=presetSequence(PRESETS[activePreset])},demo)
    local previewAlive=true
    demo.Destroying:Connect(function() previewAlive=false end)
    task.spawn(function()
        local phase=0
        while previewAlive and demo.Parent and widget.Enabled and selectedTab=="textfx" do
            local dt=task.wait(0.045)
            if not demo.Parent then break end
            phase+=dt*gradientSpeed
            local wave=math.sin(phase*math.pi*2)
            demoGradient.Offset=Vector2.zero
            demoGradient.Rotation=0
            if gradientMotion=="rainbow" then
                local points={}
                for i=0,12 do points[#points+1]=ColorSequenceKeypoint.new(i/12,Color3.fromHSV((i/12+phase)%1,.8,1)) end
                demoGradient.Color=ColorSequence.new(points)
            elseif gradientMotion=="rotate" then
                demoGradient.Rotation=12*wave
                demoGradient.Offset=Vector2.new(.46*wave,0)
            elseif gradientMotion=="vertical" then demoGradient.Offset=Vector2.new(0,.55*wave)
            elseif gradientMotion=="diagonal" then demoGradient.Offset=Vector2.new(.4*wave,.4*wave)
            elseif gradientMotion=="sweep" then demoGradient.Offset=Vector2.new(.72*wave,0)
            else demoGradient.Offset=Vector2.new(.55*wave,0) end
        end
    end)
    local modes={{"slide",LANGUAGE=="RU" and "Горизонтальный перелив" or "Gradient slide"},{"rotate",LANGUAGE=="RU" and "Смена направления" or "Rotate gradient"},{"rainbow",LANGUAGE=="RU" and "Радужный цикл" or "Rainbow cycle"},{"vertical",LANGUAGE=="RU" and "Перелив снизу вверх" or "Vertical drift"},{"diagonal",LANGUAGE=="RU" and "Перелив по диагонали" or "Diagonal wave"},{"sweep",LANGUAGE=="RU" and "Мягкий проход" or "Linear sweep"}}
    for _,entry in ipairs(modes) do
        local b=button(sc,entry[2],34)
        forgeChoiceIndicator(b,gradientMotion==entry[1])
        
        b.MouseButton1Click:Connect(function() gradientMotion=entry[1] draw() end)
    end
    local speed=button(sc,(LANGUAGE=="RU" and "Скорость: " or "Speed: ")..gradientSpeed,33)
    speed.MouseButton1Click:Connect(function()
        if gradientSpeed==0.2 then gradientSpeed=0.5 elseif gradientSpeed==0.5 then gradientSpeed=1 else gradientSpeed=0.2 end
        draw()
    end)
    local apply=button(sc,LANGUAGE=="RU" and "Анимировать выделенный градиент" or "Animate selected gradient",40)
    apply.BackgroundColor3=C.blue
    apply.MouseButton1Click:Connect(function()
        changeAll(function(o)
            local g=o:FindFirstChild("UIToolsGradient") or o:FindFirstChild("UIToolsTextGradient") or o:FindFirstChildOfClass("UIGradient")
            if not g then return false end
            local old=o:FindFirstChild("UIToolsGradientAnimator")
            if old then old:Destroy() end
            local fx=make("LocalScript",{Name="UIToolsGradientAnimator",Source=GRADIENT_ANIM_SOURCE},o)
            fx:SetAttribute("Mode",gradientMotion)
            fx:SetAttribute("Speed",gradientSpeed)
            fx:SetAttribute("GradientName",g.Name)
            return true
        end,"Gradient Animation")
    end)
    local remove=button(sc,LANGUAGE=="RU" and "Остановить анимацию градиента" or "Stop gradient animation",34)
    remove.MouseButton1Click:Connect(function()
        changeAll(function(o)
            local n=false
            for _,name in ipairs({"UIToolsGradientAnimator","UIToolsTextFX"}) do
                local fx=o:FindFirstChild(name)
                if fx then fx:Destroy() n=true end
            end
            return n
        end,"Remove gradient animation")
    end)
    label(sc,LANGUAGE=="RU" and "Примечание: LocalScript запускается в поддерживаемом клиентском контейнере (например, PlayerGui). В Studio-редакторе анимация не проигрывается." or "A LocalScript runs only in supported client containers such as PlayerGui, not in the edit viewport.",68,C.yellow)
end
local ANIMATION_SOURCES={
hover=[=[
local TweenService=game:GetService("TweenService")
local button=script.Parent
if not button:IsA("GuiButton") then return end
local scale=button:FindFirstChild("UIToolsHoverScale") or Instance.new("UIScale")
scale.Name="UIToolsHoverScale"
scale.Parent=button
local info=TweenInfo.new(0.16,Enum.EasingStyle.Quad,Enum.EasingDirection.Out)
button.MouseEnter:Connect(function() TweenService:Create(scale,info,{Scale=1.055}):Play() end)
button.MouseLeave:Connect(function() TweenService:Create(scale,info,{Scale=1}):Play() end)
]=],
pulse=[=[
local TweenService=game:GetService("TweenService")
local object=script.Parent
local scale=object:FindFirstChild("UIToolsPulseScale") or Instance.new("UIScale")
scale.Name="UIToolsPulseScale"
scale.Parent=object
TweenService:Create(scale,TweenInfo.new(1.35,Enum.EasingStyle.Sine,Enum.EasingDirection.InOut,-1,true),{Scale=1.035}):Play()
]=],
rotate=[=[
local TweenService=game:GetService("TweenService")
local object=script.Parent
TweenService:Create(object,TweenInfo.new(5,Enum.EasingStyle.Linear,Enum.EasingDirection.InOut,-1),{Rotation=object.Rotation+360}):Play()
]=],
fade=[=[
local TweenService=game:GetService("TweenService")
local o=script.Parent
local original=o.BackgroundTransparency
while script.Parent do
    o.BackgroundTransparency=math.min(1,original+.65)
    local tw=TweenService:Create(o,TweenInfo.new(.7,Enum.EasingStyle.Sine,Enum.EasingDirection.Out),{BackgroundTransparency=original})
    tw:Play()
    tw.Completed:Wait()
    task.wait(1)
end
]=],
slide=[=[
local TweenService=game:GetService("TweenService")
local o=script.Parent
local scale=o:FindFirstChild("UIToolsPulseScale") or Instance.new("UIScale")
scale.Name="UIToolsPulseScale"
scale.Parent=o
local original=o.BackgroundTransparency
while script.Parent do
    scale.Scale=.86
    o.BackgroundTransparency=math.min(1,original+.38)
    local t=TweenService:Create(scale,TweenInfo.new(.65,Enum.EasingStyle.Quad,Enum.EasingDirection.Out),{Scale=1})
    TweenService:Create(o,TweenInfo.new(.65,Enum.EasingStyle.Quad,Enum.EasingDirection.Out),{BackgroundTransparency=original}):Play()
    t:Play()
    t.Completed:Wait()
    task.wait(.75)
end
]=],
loading=[=[
local TweenService=game:GetService("TweenService")
local holder=script.Parent
local squares={}
for i=1,4 do
    local f=Instance.new("Frame")
    f.Name="UIToolsLoadingSquare"..i
    f.Size=UDim2.fromOffset(9,9)
    f.AnchorPoint=Vector2.new(.5,.5)
    f.Position=UDim2.new((i-.5)/4,0,.5,0)
    f.BackgroundColor3=Color3.fromRGB(68,181,255)
    f.BackgroundTransparency=.72
    f.BorderSizePixel=0
    f.Parent=holder
    squares[i]=f
end
while script.Parent do
    for _,f in ipairs(squares) do
        if not f.Parent then return end
        local up=TweenService:Create(f,TweenInfo.new(.2,Enum.EasingStyle.Sine),{BackgroundTransparency=0,Size=UDim2.fromOffset(13,13)})
        up:Play()
        up.Completed:Wait()
        if not f.Parent then return end
        TweenService:Create(f,TweenInfo.new(.3,Enum.EasingStyle.Sine),{BackgroundTransparency=.72,Size=UDim2.fromOffset(9,9)}):Play()
    end
end
]=],
bounce=[=[
local TweenService=game:GetService("TweenService")
local o=script.Parent
local scale=o:FindFirstChild("UIToolsPulseScale") or Instance.new("UIScale")
scale.Name="UIToolsPulseScale"
scale.Parent=o
TweenService:Create(scale,TweenInfo.new(.7,Enum.EasingStyle.Back,Enum.EasingDirection.Out,-1,true),{Scale=1.12}):Play()
]=],
float=[=[
local TweenService=game:GetService("TweenService")
local o=script.Parent
local initial=o.Position
TweenService:Create(o,TweenInfo.new(1.8,Enum.EasingStyle.Sine,Enum.EasingDirection.InOut,-1,true),{Position=initial+UDim2.fromOffset(0,-9)}):Play()
]=],
shake=[=[
local TweenService=game:GetService("TweenService")
local o=script.Parent
local start=o.Rotation
while script.Parent do
    for _,angle in ipairs({-5,5,-3,3,0}) do
        if not script.Parent then return end
        local tw=TweenService:Create(o,TweenInfo.new(.055,Enum.EasingStyle.Linear),{Rotation=start+angle})
        tw:Play()
        tw.Completed:Wait()
    end
    task.wait(2.3)
end
]=],
pop=[=[
local TweenService=game:GetService("TweenService")
local o=script.Parent
local scale=o:FindFirstChild("UIToolsPulseScale") or Instance.new("UIScale")
scale.Name="UIToolsPulseScale"
scale.Parent=o
local original=o.BackgroundTransparency
while script.Parent do
    scale.Scale=.86
    o.BackgroundTransparency=math.min(1,original+.38)
    local t=TweenService:Create(scale,TweenInfo.new(.65,Enum.EasingStyle.Quad,Enum.EasingDirection.Out),{Scale=1})
    TweenService:Create(o,TweenInfo.new(.65,Enum.EasingStyle.Quad,Enum.EasingDirection.Out),{BackgroundTransparency=original}):Play()
    t:Play()
    t.Completed:Wait()
    task.wait(.75)
end
]=],
dots=[=[
local TweenService=game:GetService("TweenService")
local holder=script.Parent
local dots={}
for i=1,3 do
    local o=Instance.new("Frame")
    o.Name="UIToolsDot"..i
    o.Size=UDim2.fromOffset(9,9)
    o.AnchorPoint=Vector2.new(.5,.5)
    o.Position=UDim2.fromScale((i-.5)/3,.5)
    o.BackgroundColor3=Color3.fromRGB(27,173,255)
    o.BorderSizePixel=0
    o.Parent=holder
    local corner=Instance.new("UICorner")
    corner.CornerRadius=UDim.new(1,0)
    corner.Parent=o
    dots[#dots+1]=o
end
while script.Parent do
    for _,o in ipairs(dots) do
        if not o.Parent then return end
        local tw=TweenService:Create(o,TweenInfo.new(.25,Enum.EasingStyle.Sine,Enum.EasingDirection.Out,0,true),{Position=o.Position+UDim2.fromOffset(0,-7)})
        tw:Play()
        task.wait(.16)
    end
    task.wait(.35)
end
]=],
sway=[=[
local TweenService=game:GetService("TweenService")
local o=script.Parent
local start=o.Rotation
TweenService:Create(o,TweenInfo.new(1.6,Enum.EasingStyle.Sine,Enum.EasingDirection.InOut,-1,true),{Rotation=start+4}):Play()
]=],
softglow=[=[
local TweenService=game:GetService("TweenService")
local o=script.Parent
local stroke=o:FindFirstChild("UIToolsSoftStroke") or Instance.new("UIStroke")
stroke.Name="UIToolsSoftStroke"
stroke.Thickness=1
stroke.Transparency=.8
stroke.Color=Color3.fromRGB(175,192,208)
stroke.Parent=o
TweenService:Create(stroke,TweenInfo.new(1.6,Enum.EasingStyle.Sine,Enum.EasingDirection.InOut,-1,true),{Transparency=.22}):Play()
]=],
slideleft=[=[
local TweenService=game:GetService("TweenService")
local o=script.Parent
local scale=o:FindFirstChild("UIToolsPulseScale") or Instance.new("UIScale")
scale.Name="UIToolsPulseScale"
scale.Parent=o
local original=o.BackgroundTransparency
while script.Parent do
    scale.Scale=.86
    o.BackgroundTransparency=math.min(1,original+.38)
    local t=TweenService:Create(scale,TweenInfo.new(.65,Enum.EasingStyle.Quad,Enum.EasingDirection.Out),{Scale=1})
    TweenService:Create(o,TweenInfo.new(.65,Enum.EasingStyle.Quad,Enum.EasingDirection.Out),{BackgroundTransparency=original}):Play()
    t:Play()
    t.Completed:Wait()
    task.wait(.75)
end
]=],
press=[=[
local TweenService=game:GetService("TweenService")
local o=script.Parent
if not o:IsA("GuiButton") then return end
local scale=o:FindFirstChild("UIToolsPressScale") or Instance.new("UIScale")
scale.Name="UIToolsPressScale"
scale.Parent=o
local normal=TweenInfo.new(.14,Enum.EasingStyle.Quad,Enum.EasingDirection.Out)
o.MouseButton1Down:Connect(function() TweenService:Create(scale,normal,{Scale=.965}):Play() end)
o.MouseButton1Up:Connect(function() TweenService:Create(scale,normal,{Scale=1}):Play() end)
o.MouseLeave:Connect(function() TweenService:Create(scale,normal,{Scale=1}):Play() end)
]=],
pixelwipe=[=[
local TweenService=game:GetService("TweenService")
local holder=script.Parent
local cols=12
local rows=9
local overlay=Instance.new("Frame")
overlay.Name="UIToolsPixelOverlay"
overlay.Size=UDim2.fromScale(1,1)
overlay.BackgroundTransparency=1
overlay.BorderSizePixel=0
overlay.ClipsDescendants=true
overlay.ZIndex=holder.ZIndex+5
overlay.Parent=holder
local cells={}
for y=1,rows do
    for x=1,cols do
        local cell=Instance.new("Frame")
        cell.Name="Pixel_"..x.."_"..y
        cell.Size=UDim2.fromScale(1/cols+0.002,1/rows+0.002)
        cell.Position=UDim2.fromScale((x-1)/cols,(y-1)/rows)
        cell.BackgroundColor3=Color3.fromRGB(19,150,255)
        cell.BackgroundTransparency=1
        cell.BorderSizePixel=0
        cell.ZIndex=overlay.ZIndex+1
        cell.Parent=overlay
        table.insert(cells,{f=cell,delay=(x+y)*.025})
    end
end
local longest=(cols+rows)*.025
for _,data in ipairs(cells) do
    task.delay(data.delay,function()
        if data.f.Parent then TweenService:Create(data.f,TweenInfo.new(.12,Enum.EasingStyle.Quad),{BackgroundTransparency=0}):Play() end
    end)
end
task.wait(longest+.15)
for _,data in ipairs(cells) do
    task.delay(data.delay,function()
        if data.f.Parent then TweenService:Create(data.f,TweenInfo.new(.15,Enum.EasingStyle.Quart,Enum.EasingDirection.In),{Position=data.f.Position+UDim2.fromScale(.025,.025),BackgroundTransparency=1}):Play() end
    end)
end
task.wait(longest+.25)
overlay:Destroy()
]=]
}
local ANIMATION_RUNTIME_SOURCE=require(script:WaitForChild("Modules"):WaitForChild("ANIMATION_RUNTIME_SOURCE"))
local chosenAnimation="pulse"
local chosenTrigger="loop"
local animationOptions={
    {"pulse","Пульсация","Pulse"},{"rotate","Непрерывное вращение","Continuous rotation"},
    {"fade","Плавное проявление","Fade in"},{"slide","Раскрытие из центра","Center reveal"},
    {"loading","Четыре квадрата","Four squares"},{"bounce","Пружина","Bounce"},
    {"float","Парение","Float"},{"shake","Встряхивание","Shake"},
    {"pop","Мягкое увеличение","Smooth pop"},{"dots","Три точки","Three dots"},
    {"pixelwipe","Пиксельная мозаика","Pixel mosaic"},{"sway","Покачивание","Sway"},
    {"softglow","Светящийся контур","Glowing outline"},{"press","Отклик на нажатие","Press response"}
}
local function animationPage(sc)
    label(sc,t("animations"),28,C.blue,Enum.Font.GothamBold,16)
    label(sc,LANGUAGE=="RU" and "Предпросмотр совпадает по механике с эффектом. Режим выбирает способ запуска LocalScript в игре." or "Preview uses the same motion parameters as the runtime effect. Trigger controls its LocalScript.",39,C.muted)
    local previewHolder=make("Frame",{Size=UDim2.new(1,-2,0,136),BackgroundColor3=C.panel,BorderSizePixel=0,ClipsDescendants=true},sc)
    corner(previewHolder,5)
    local sample=make("TextButton",{AnchorPoint=Vector2.new(.5,.5),Position=UDim2.fromScale(.5,.5),Size=UDim2.fromOffset(180,42),BackgroundColor3=C.surface,Text="UITools",TextColor3=C.white,FontFace=Font.new("rbxasset://fonts/families/GothamSSm.json",Enum.FontWeight.SemiBold),TextSize=14,AutoButtonColor=false,BorderSizePixel=0},previewHolder)
    corner(sample,5)
    local s=make("UIScale",{Scale=1},sample)
    local st=make("UIStroke",{Color=C.blue,Thickness=2,Transparency=.86,ApplyStrokeMode=Enum.ApplyStrokeMode.Border},sample)
    local alive=true
    local busy=false
    local running={}
    local decorations={}
    previewHolder.Destroying:Connect(function() alive=false for _,v in ipairs(running) do v:Cancel() end end)
    local function tween(o,duration,goal,easing)
        if not alive or not o.Parent then return nil end
        local anim=TweenService:Create(o,TweenInfo.new(duration,easing or Enum.EasingStyle.Sine,Enum.EasingDirection.InOut),goal)
        table.insert(running,anim)
        anim:Play()
        return anim
    end
    local function reset()
        for _,v in ipairs(running) do v:Cancel() end
        table.clear(running)
        for _,v in ipairs(decorations) do v:Destroy() end
        table.clear(decorations)
        sample.Position=UDim2.fromScale(.5,.5)
        sample.Rotation=0
        sample.BackgroundTransparency=0
        sample.TextTransparency=0
        s.Scale=1
        st.Transparency=.86
    end
    local function animation()
        if busy or not alive then return end
        busy=true
        reset()
        local kind=chosenAnimation
        if kind=="rotate" then
            local tw=tween(sample,2.4,{Rotation=360},Enum.EasingStyle.Linear)
            if tw then tw.Completed:Wait() end
            sample.Rotation=0
        elseif kind=="fade" then
            sample.BackgroundTransparency=1
            sample.TextTransparency=1
            tween(sample,.75,{BackgroundTransparency=0,TextTransparency=0},Enum.EasingStyle.Quad)
            task.wait(.76)
        elseif kind=="slide" then
            s.Scale=.72
            sample.BackgroundTransparency=1
            sample.TextTransparency=1
            tween(s,.64,{Scale=1},Enum.EasingStyle.Quint)
            tween(sample,.64,{BackgroundTransparency=0,TextTransparency=0},Enum.EasingStyle.Quad)
            task.wait(.65)
        elseif kind=="loading" or kind=="dots" then
            local n=kind=="dots" and 3 or 4
            for i=1,n do
                local dot=make("Frame",{AnchorPoint=Vector2.new(.5,.5),Position=UDim2.fromScale(.5+(i-(n+1)/2)*.11,.5),Size=UDim2.fromOffset(10,10),BackgroundTransparency=.7,BackgroundColor3=C.blue,BorderSizePixel=0,ZIndex=5},sample)
                if kind=="dots" then corner(dot,10) end
                table.insert(decorations,dot)
            end
            sample.TextTransparency=1
            for _=1,2 do
                for _,cell in ipairs(decorations) do
                    if not alive then break end
                    local base=cell.Position
                    tween(cell,.2,{Position=base+UDim2.fromOffset(0,-7),BackgroundTransparency=0})
                    task.wait(.12)
                    tween(cell,.26,{Position=base,BackgroundTransparency=.7})
                end
            end
        elseif kind=="pixelwipe" then
            sample.TextTransparency=1
            for y=1,5 do for x=1,8 do
                local c=make("Frame",{Position=UDim2.fromScale((x-1)/8,(y-1)/5),Size=UDim2.fromScale(1/8+.01,1/5+.01),BackgroundColor3=C.blue,BackgroundTransparency=1,BorderSizePixel=0,ZIndex=6},sample)
                table.insert(decorations,c)
                task.delay((x+y)*.025,function() if alive and c.Parent then tween(c,.18,{BackgroundTransparency=.12}) end end)
            end end
            task.wait(.4)
            for _,c in ipairs(decorations) do tween(c,.2,{BackgroundTransparency=1}) end
            task.wait(.35)
        elseif kind=="shake" then
            for _,a in ipairs({-5,5,-4,3,0}) do
                local tw=tween(sample,.075,{Rotation=a})
                if tw then tw.Completed:Wait() end
            end
        elseif kind=="sway" then
            tween(sample,.6,{Rotation=5})
            task.wait(.61)
            tween(sample,.6,{Rotation=-5})
            task.wait(.61)
        elseif kind=="float" then
            tween(sample,.7,{Position=UDim2.new(.5,0,.5,-8)})
            task.wait(.72)
        elseif kind=="softglow" then
            tween(st,.65,{Transparency=.15})
            task.wait(.7)
        elseif kind=="press" then
            tween(s,.13,{Scale=.94})
            task.wait(.14)
            tween(s,.25,{Scale=1})
            task.wait(.26)
        elseif kind=="pop" or kind=="bounce" then
            s.Scale=kind=="bounce" and .78 or .88
            tween(s,.62,{Scale=1},kind=="bounce" and Enum.EasingStyle.Back or Enum.EasingStyle.Quart)
            task.wait(.65)
        else
            tween(s,.68,{Scale=1.06})
            task.wait(.70)
        end
        busy=false
    end
    sample.MouseEnter:Connect(function() if chosenTrigger=="hover" then task.spawn(animation) end end)
    sample.MouseButton1Click:Connect(function() if chosenTrigger=="click" then task.spawn(animation) end end)
    task.spawn(function()
        while alive and previewHolder.Parent do
            if chosenTrigger=="loop" then animation() end
            task.wait(chosenTrigger=="loop" and .08 or .12)
        end
    end)
    label(sc,LANGUAGE=="RU" and "Режим запуска" or "Trigger",25,C.white)
    local triggers=make("Frame",{Size=UDim2.new(1,-2,0,32),BackgroundTransparency=1},sc)
    local triggerGrid=make("UIGridLayout",{CellSize=UDim2.new(1/3,-4,1,0),CellPadding=UDim2.fromOffset(4,0)},triggers)
    for _,entry in ipairs({{"hover","Наведение","Hover"},{"click","Нажатие","Click"},{"loop","Цикл","Loop"}}) do
        local b=button(triggers,(chosenTrigger==entry[1] and "● " or "○ ")..(LANGUAGE=="RU" and entry[2] or entry[3]),30)
        if chosenTrigger==entry[1] then b.BackgroundColor3=C.blue end
        b.MouseButton1Click:Connect(function() chosenTrigger=entry[1] draw() end)
    end
    label(sc,LANGUAGE=="RU" and "Наведи или нажми на образец; циклические эффекты запускаются сами." or "Hover or click sample to test. Loop effects auto-play.",30,C.muted)
    line(sc)
    for _,entry in ipairs(animationOptions) do
        local b=button(sc,(LANGUAGE=="RU" and entry[2] or entry[3]),30)
        forgeChoiceIndicator(b,chosenAnimation==entry[1])
        
        b.MouseButton1Click:Connect(function() chosenAnimation=entry[1] draw() end)
    end
    local apply=button(sc,t("animApply"),38)
    apply.BackgroundColor3=C.blue
    apply.MouseButton1Click:Connect(function()
        changeAll(function(o)
            if not o:IsA("GuiObject") then return false end
            local old=o:FindFirstChild("UIToolsAnimation")
            if old then old:Destroy() end
            local scriptFX=make("LocalScript",{Name="UIToolsAnimation",Source=ANIMATION_RUNTIME_SOURCE},o)
            scriptFX:SetAttribute("Effect",chosenAnimation)
            scriptFX:SetAttribute("Trigger",chosenTrigger)
            return true
        end,"Animation")
    end)
    local remove=button(sc,t("animRemove"),34)
    remove.MouseButton1Click:Connect(function()
        changeAll(function(o)
            local old=o:FindFirstChild("UIToolsAnimation")
            if old then old:Destroy() return true end
            return false
        end,"Remove Animation")
    end)
    label(sc,LANGUAGE=="RU" and "Применить создаёт LocalScript с режимом запуска. Для выполнения в игре объект должен находиться в PlayerGui." or "Apply creates a LocalScript with its trigger. Put the GUI in PlayerGui for runtime execution.",53,C.muted)
end
local logs={}
local filter="all"
local searchText=""
local showLimit=200
local originFilter="all"
local selectedLog=nil
local function category(kind)
    if kind==Enum.MessageType.MessageError then return "errors" end
    if kind==Enum.MessageType.MessageWarning then return "warnings" end
    return "info"
end
local function addLog(msg,kind,origin)
    table.insert(logs,{msg=string.sub(tostring(msg),1,1000),kind=kind,origin=origin or "studio",stamp=os.date("%H:%M:%S")})
    if #logs&gt;500 then table.remove(logs,1) end
end
LogService.MessageOut:Connect(function(msg,kind) addLog(msg,kind,"studio") end)
local success,history=pcall(function() return LogService:GetLogHistory() end)
if success then
    for _,entry in ipairs(history) do addLog(entry.message,entry.messageType,"studio") end
end
local function outputPage(sc)
    label(sc,t("logs"),28,C.blue,Enum.Font.GothamBold,16)
    label(sc,LANGUAGE=="RU" and "Логи Studio помечены Studio, поскольку API не всегда указывает сторону. Во внутриигровом Tool клиент и сервер разделены." or "Studio LogService does not expose reliable origin metadata. Use Developer Tool during Play for client/server logs.",62,C.muted)
    local search=make("TextBox",{Size=UDim2.new(1,-1,0,34),BackgroundColor3=C.panel,BorderSizePixel=0,Text=searchText,PlaceholderText=t("search"),TextColor3=C.white,PlaceholderColor3=C.muted,ClearTextOnFocus=false,Font=Enum.Font.GothamMedium,TextSize=12},sc)
    corner(search,6)
    search.FocusLost:Connect(function() searchText=search.Text draw() end)
    label(sc,t("typefilter"),23,C.white,Enum.Font.GothamBold,12)
    local bar=make("Frame",{Size=UDim2.new(1,-1,0,32),BackgroundTransparency=1},sc)
    make("UIGridLayout",{CellSize=UDim2.new(.25,-5,1,0),CellPadding=UDim2.fromOffset(5,0)},bar)
    for _,f in ipairs({{"all",t("all")},{"errors",t("errors")},{"warnings",t("warnings")},{"info",t("info")}}) do
        local b=button(bar,f[2],30)
        if filter==f[1] then b.BackgroundColor3=C.blue end
        b.MouseButton1Click:Connect(function() filter=f[1] draw() end)
    end
    label(sc,t("sourcefilter"),22,C.white,Enum.Font.GothamBold,12)
    local origins=make("Frame",{Size=UDim2.new(1,-1,0,32),BackgroundTransparency=1},sc)
    make("UIGridLayout",{CellSize=UDim2.new(.25,-5,1,0),CellPadding=UDim2.fromOffset(5,0)},origins)
    for _,f in ipairs({{"all",t("all")},{"client",t("client")},{"server",t("server")},{"studio",LANGUAGE=="RU" and "Studio" or "Studio"}}) do
        local b=button(origins,f[2],30)
        if originFilter==f[1] then b.BackgroundColor3=C.blue end
        b.MouseButton1Click:Connect(function() originFilter=f[1] draw() end)
    end
    local clear=button(sc,t("clear"),30)
    clear.MouseButton1Click:Connect(function() table.clear(logs) selectedLog=nil draw() end)
    local matches=0
    for i=#logs,1,-1 do
        local m=logs[i]
        if (filter=="all" or filter==category(m.kind)) and (originFilter=="all" or originFilter==m.origin) and (searchText=="" or string.find(string.lower(m.msg),string.lower(searchText),1,true)) then
            matches+=1
            if matches&gt;showLimit then break end
            local col=m.kind==Enum.MessageType.MessageError and C.red or m.kind==Enum.MessageType.MessageWarning and C.yellow or C.muted
            local b=button(sc,m.stamp.."  ["..(m.origin=="studio" and "Studio" or t(m.origin)).."]  "..string.sub(m.msg,1,115),48)
            b.TextWrapped=true
            b.TextXAlignment=Enum.TextXAlignment.Left
            b.TextColor3=col
            b.BackgroundColor3=selectedLog==m and C.surface or C.panel
            b.MouseButton1Click:Connect(function() selectedLog=m draw() end)
            b.MouseButton2Click:Connect(function()
                selectedLog=m
                draw()
            end)
        end
    end
    if matches==0 then label(sc,t("emptyLogs"),50,C.muted) end
    stat(sc,LANGUAGE=="RU" and "Показано" or "Showing",math.min(matches,showLimit).." / "..#logs)
    if selectedLog then
        label(sc,t("logDetail"),25,C.blue,Enum.Font.GothamBold,13)
        local detail=make("TextBox",{Size=UDim2.new(1,-2,0,145),Text=selectedLog.stamp.." ["..selectedLog.origin.."] "..selectedLog.msg,ClearTextOnFocus=false,TextEditable=false,MultiLine=true,TextWrapped=true,Font=Enum.Font.Code,TextSize=12,TextColor3=C.white,BackgroundColor3=C.panel,TextXAlignment=Enum.TextXAlignment.Left,TextYAlignment=Enum.TextYAlignment.Top},sc)
        corner(detail,6)
        local selectText=button(sc,LANGUAGE=="RU" and "Выделить текст · Ctrl+C" or "Select text · Ctrl+C",32)
        selectText.MouseButton1Click:Connect(function() detail:CaptureFocus() detail.CursorPosition=#detail.Text+1 detail.SelectionStart=1 end)
    end
end
local FT_ANTICHEAT_AEGIS_SOURCE=require(script.Modules:WaitForChild("FT_ANTICHEAT_AEGIS_SOURCE"))
local FT_ANTICHEAT_CONTROLLER_SOURCE=require(script.Modules:WaitForChild("FT_ANTICHEAT_CONTROLLER_SOURCE"))
local FT_ANTICHEAT_CLIENT_SOURCE=require(script.Modules:WaitForChild("FT_ANTICHEAT_CLIENT_SOURCE"))
local FT_ANTICHEAT_PUBLIC_SOURCE=require(script.Modules:WaitForChild("FT_ANTICHEAT_PUBLIC_SOURCE"))
local FT_ANTICHEAT_LICENSE_SOURCE=require(script.Modules:WaitForChild("FT_ANTICHEAT_LICENSE_SOURCE"))
local FT_ANTICHEAT_CONFIG_SOURCE=require(script.Modules:WaitForChild("FT_ANTICHEAT_CONFIG_SOURCE"))
local FT_ANTICHEAT_GUARD_CORE_SOURCE=require(script.Modules:WaitForChild("FT_ANTICHEAT_GUARD_CORE_SOURCE"))
local AC_NAME="ForgeToolsAntiCheat"
local function antiCheatStatus()
    local folder=ServerScriptService:FindFirstChild(AC_NAME)
    if not folder then return "missing",nil end
    if not folder:IsA("Folder") or folder:GetAttribute("ForgeToolsManaged")~=true then return "conflict",folder end
    local core=folder:FindFirstChild("Aegis")
    local controller=folder:FindFirstChild("Controller")
    local configModule=folder:FindFirstChild("Config")
    local guardCore=folder:FindFirstChild("GuardCore")
    if not guardCore or not guardCore:IsA("ModuleScript") then return "outdated",folder end
    if not core or not core:IsA("ModuleScript") or not controller or not controller:IsA("Script") then return "broken",folder end
    if not configModule or not configModule:IsA("ModuleScript") then return "outdated",folder end
    local starter=game:GetService("StarterPlayer"):FindFirstChild("StarterPlayerScripts")
    local companion=starter and starter:FindFirstChild("FTAntiCheatAdmin")
    local public=starter and starter:FindFirstChild("FTAntiCheatPlayerList")
    local function sameSource(actual,expected)
        if type(actual)~="string" or type(expected)~="string" then return false end
        local function normalize(text)
            return text:gsub("\r\n","\n"):gsub("\r","\n"):gsub("[\n\t ]+$","")
        end
        return normalize(actual)==normalize(expected)
    end
    if not companion or not companion:IsA("LocalScript") or not public or not public:IsA("LocalScript")
        or not sameSource(guardCore.Source,FT_ANTICHEAT_GUARD_CORE_SOURCE)
        or not sameSource(core.Source,FT_ANTICHEAT_AEGIS_SOURCE)
        or not sameSource(controller.Source,FT_ANTICHEAT_CONTROLLER_SOURCE)
        or not sameSource(companion.Source,FT_ANTICHEAT_CLIENT_SOURCE)
        or not sameSource(public.Source,FT_ANTICHEAT_PUBLIC_SOURCE) then
        return "outdated",folder
    end
    return "ready",folder
end
local function antiCheatInstall(migrateOld)
    local status,folder=antiCheatStatus()
    local oldSentinel=ServerScriptService:FindFirstChild("UIToolsSentinel")
    if oldSentinel and oldSentinel:GetAttribute("ForgeToolsReplaced")~=true and not migrateOld then
        return false,LANGUAGE=="RU" and "Обнаружен старый Sentinel. Подтверди замену отдельной кнопкой." or "Old Sentinel found. Confirm replacement separately."
    end
    if status=="conflict" then return false,"Name conflict: ServerScriptService/"..AC_NAME end
    local previousController=folder and folder:FindFirstChild("Controller")
    local previousAdmin=previousController and tostring(previousController:GetAttribute("AllowedAdminUserIds") or "") or ""
    local previousPlayerList=previousController and previousController:GetAttribute("CustomPlayerListEnabled")==true or false
    ChangeHistoryService:SetWaypoint("ForgeTools Before FT AntiCheat")
    if not folder then
        folder=Instance.new("Folder")
        folder.Name=AC_NAME
        folder:SetAttribute("ForgeToolsManaged",true)
        folder.Parent=ServerScriptService
    end
    local function setSource(parent,name,clazz,body)
        local obj=parent:FindFirstChild(name)
        if obj and not obj:IsA(clazz) then error("Object conflict: "..name) end
        if not obj then obj=Instance.new(clazz); obj.Name=name; obj.Parent=parent end
        if obj:IsA("Script") or obj:IsA("LocalScript") then obj.Enabled=false end
        obj.Source=body
        if obj:IsA("Script") or obj:IsA("LocalScript") then obj.Enabled=true end
        return obj
    end
    local ok,err=pcall(function()
        setSource(folder,"Aegis","ModuleScript",FT_ANTICHEAT_AEGIS_SOURCE)
        setSource(folder,"GuardCore","ModuleScript",FT_ANTICHEAT_GUARD_CORE_SOURCE)
        
        local configObj=folder:FindFirstChild("Config")
        if configObj and not configObj:IsA("ModuleScript") then error("Object conflict: Config") end
        if not configObj then
            setSource(folder,"Config","ModuleScript",FT_ANTICHEAT_CONFIG_SOURCE)
        else
            
            
            local text=configObj.Source
            if not text:find("Fly%s*=") and text:find("    RemoteMonitor = {",1,true) then
                local flyDefaults=table.concat({
                    "    Fly = {",
                    "        Enabled = true,",
                    "        MinGroundClearance = 18,",
                    "        HoverSeconds = 2.75,",
                    "        SustainedAscentSeconds = 2.5,",
                    "        AlertCooldown = 15,",
                    "    },",
                },"\n")
                configObj.Source=text:gsub("    RemoteMonitor = {",flyDefaults.."\n    RemoteMonitor = {",1)
            end
        end
        local licence=folder:FindFirstChild("AegisMITLicense")
        if not licence then licence=Instance.new("StringValue");licence.Name="AegisMITLicense";licence.Parent=folder end
        assert(licence:IsA("StringValue"),"AegisMITLicense name conflict")
        licence.Value=FT_ANTICHEAT_LICENSE_SOURCE
        local controller=setSource(folder,"Controller","Script",FT_ANTICHEAT_CONTROLLER_SOURCE)
        controller:SetAttribute("AllowedAdminUserIds",previousAdmin)
        controller:SetAttribute("CustomPlayerListEnabled",previousPlayerList)
        local starter=game:GetService("StarterPlayer"):WaitForChild("StarterPlayerScripts")
        setSource(starter,"FTAntiCheatAdmin","LocalScript",FT_ANTICHEAT_CLIENT_SOURCE)
        setSource(starter,"FTAntiCheatPlayerList","LocalScript",FT_ANTICHEAT_PUBLIC_SOURCE)
        folder:SetAttribute("ForgeToolsManaged",true)
        folder:SetAttribute("AuditOnly",true)
        folder:SetAttribute("UpstreamProject","https://github.com/Pannu2009/Aegis")
        folder:SetAttribute("UpstreamLicense","MIT")
        folder:SetAttribute("UpstreamName","Aegis v0.5 (original header: Dakait; MIT copyright: Arzh)")
        if oldSentinel and migrateOld then
            local archive=game:GetService("ServerStorage"):FindFirstChild("ForgeToolsBackup")
            if not archive then archive=Instance.new("Folder");archive.Name="ForgeToolsBackup";archive.Parent=game:GetService("ServerStorage") end
            local clone=oldSentinel:Clone()
            clone.Name="UIToolsSentinel_Backup_"..os.date("!%Y%m%d_%H%M%S")
            for _,obj in ipairs(clone:GetDescendants()) do
                if obj:IsA("BaseScript") then obj.Enabled=false end
            end
            clone.Parent=archive
            for _,obj in ipairs(oldSentinel:GetDescendants()) do
                if obj:IsA("BaseScript") then obj.Enabled=false end
            end
            oldSentinel:SetAttribute("ForgeToolsReplaced",true)
        end
    end)
    if not ok then warn("[FT AntiCheat] Install issue: "..tostring(err));return false,tostring(err) end
    ChangeHistoryService:SetWaypoint("ForgeTools FT AntiCheat installed")
    return true,"FT AntiCheat installed in monitor-only mode. Restart Play."
end


local editorCreateClass = "Frame"
local editorFeedback = ""
local editorFeedbackOk = true
local editorNewName = ""
local function editorMsg(sc, text, ok)
    editorFeedback=text
    editorFeedbackOk=ok~=false
    local child=sc:FindFirstChild("EditorStatus")
    if child then
        child.Text=text
        child.TextColor3=editorFeedbackOk and C.green or C.red
    end
end
local function editorSelected()
    local objects=Selection:Get()
    if #objects~=1 then return nil end
    local obj=objects[1]
    return obj:IsA("GuiObject") and obj or nil
end
local function editorParent()
    local picked=Selection:Get()[1]
    if picked and (picked:IsA("ScreenGui") or picked:IsA("SurfaceGui") or picked:IsA("BillboardGui") or picked:IsA("GuiObject")) then
        return picked
    end
    return nil
end
local function editorParseNumbers(raw,count)
    local parts={}
    raw=tostring(raw):gsub(";",",")
    for token in raw:gmatch("[^,%s]+") do
        local value=tonumber(token)
        if not value or value~=value or value==math.huge or value==-math.huge then return nil end
        table.insert(parts,value)
    end
    if #parts~=count then return nil end
    return parts
end
local function editorColorParse(raw)
    raw=tostring(raw):gsub("%s+","")
    if raw:match("^#%x%x%x%x%x%x$") then
        return Color3.fromRGB(tonumber(raw:sub(2,3),16),tonumber(raw:sub(4,5),16),tonumber(raw:sub(6,7),16))
    end
    local p=editorParseNumbers(raw,3)
    if not p then
        local n=tonumber(raw)
        if n and n==n and n&gt;-math.huge and n&lt;math.huge then p={n,n,n} end
    end
    if not p then return nil end
    return Color3.fromRGB(math.clamp(math.floor(p[1]+.5),0,255),math.clamp(math.floor(p[2]+.5),0,255),math.clamp(math.floor(p[3]+.5),0,255))
end
local function editorFmtColor(color)
    return string.format("%d, %d, %d",math.floor(color.R*255+.5),math.floor(color.G*255+.5),math.floor(color.B*255+.5))
end
local function editorFmtUDim2(v)
    return string.format("%g, %g, %g, %g",v.X.Scale,v.X.Offset,v.Y.Scale,v.Y.Offset)
end
local function editorApply(obj,prop,value,sc)
    if not obj or not obj.Parent then editorMsg(sc,LANGUAGE=="RU" and "Объект больше не существует" or "Object is no longer available",false) return end
    local ok,err=pcall(function()
        ChangeHistoryService:SetWaypoint("UITools GUI Editor Before "..prop)
        obj[prop]=value
        ChangeHistoryService:SetWaypoint("UITools GUI Editor "..prop)
    end)
    if ok then
        editorMsg(sc,(LANGUAGE=="RU" and "Изменено: " or "Updated: ")..prop,true)
    else
        editorMsg(sc,tostring(err),false)
    end
end
local function editorField(sc,obj,key,format,parse,hint)
    local wrap=make("Frame",{Size=UDim2.new(1,-2,0,52),BackgroundTransparency=1},sc)
    make("TextLabel",{Size=UDim2.new(1,0,0,19),BackgroundTransparency=1,Text=key..(hint and "  ·  "..hint or ""),Font=Enum.Font.GothamMedium,TextSize=11,TextColor3=C.muted,TextXAlignment=Enum.TextXAlignment.Left},wrap)
    local existing=obj[key]
    local tb=make("TextBox",{Position=UDim2.fromOffset(0,20),Size=UDim2.new(1,0,0,30),Text=format(existing),ClearTextOnFocus=false,Font=Enum.Font.Code,TextSize=12,TextColor3=C.white,BackgroundColor3=C.surface,BorderSizePixel=0,TextXAlignment=Enum.TextXAlignment.Left},wrap)
    corner(tb,4)
    make("UIPadding",{PaddingLeft=UDim.new(0,8),PaddingRight=UDim.new(0,6)},tb)
    tb.FocusLost:Connect(function(enterPressed)
        
        if not tb.Parent then return end
        local value=parse(tb.Text)
        if value==nil then
            tb.Text=format(obj[key])
            editorMsg(sc,LANGUAGE=="RU" and ("Недопустимое значение: "..key) or ("Invalid value: "..key),false)
            return
        end
        editorApply(obj,key,value,sc)
        tb.Text=format(obj[key])
    end)
    return tb
end
local function editorSection(sc,title)
    label(sc,title,27,C.white,Enum.Font.GothamMedium,14)
end
local function editorAction(sc,title,fn)
    local b=button(sc,title,30)
    b.MouseButton1Click:Connect(fn)
    return b
end

local FONT_CHOICES={
    {"Gotham", "GothamSSm"},
    {"Arial", "Arial"},
    {"Source Sans", "SourceSansPro"},
    {"Montserrat", "Montserrat"},
    {"Roboto", "Roboto"},
    {"Nunito", "Nunito"},
    {"Ubuntu", "Ubuntu"},
    {"Fredoka", "FredokaOne"},
}
local FONT_WEIGHTS={
    {"Regular",Enum.FontWeight.Regular},
    {"Medium",Enum.FontWeight.Medium},
    {"Semibold",Enum.FontWeight.SemiBold},
    {"Bold",Enum.FontWeight.Bold},
    {"Heavy",Enum.FontWeight.Heavy},
}
local editorFamilyIndex=1
local editorWeightIndex=1
local editorItalic=false
local editorWordIndex="1"
local editorWordColor="#FF4DB3"
local editorWordBold=true
local editorWordUnderline=false
local editorWordItalic=false

local function editorFontFace()
    local family="rbxasset://fonts/families/"..FONT_CHOICES[editorFamilyIndex][2]..".json"
    return Font.new(family,FONT_WEIGHTS[editorWeightIndex][2],editorItalic and Enum.FontStyle.Italic or Enum.FontStyle.Normal)
end
local function editorTextEscape(value)
    local escaped=tostring(value):gsub("&amp;","&amp;amp;"):gsub("&lt;","&amp;lt;"):gsub("&gt;","&amp;gt;"):gsub('"',"&amp;quot;"):gsub("'","&amp;apos;")
    return escaped
end
local function editorFormatWord(raw,index,color,bold,underline,italic)
    local count=0
    local output={}
    local last=1
    for startPos,word,afterPos in raw:gmatch("()(%S+)()") do
        table.insert(output,editorTextEscape(raw:sub(last,startPos-1)))
        count+=1
        local segment=editorTextEscape(word)
        if count==index then
            local hex=string.format("#%02X%02X%02X",math.floor(color.R*255+.5),math.floor(color.G*255+.5),math.floor(color.B*255+.5))
            segment='&lt;font color="'..hex..'"&gt;'..segment..'&lt;/font&gt;'
            if bold then segment="&lt;b&gt;"..segment.."&lt;/b&gt;" end
            if italic then segment="&lt;i&gt;"..segment.."&lt;/i&gt;" end
            if underline then segment="&lt;u&gt;"..segment.."&lt;/u&gt;" end
        end
        table.insert(output,segment)
        last=afterPos
    end
    table.insert(output,editorTextEscape(raw:sub(last)))
    if index&gt;count then return nil,count end
    return table.concat(output),count
end
local function editorTextDesign(sc,obj)
    editorSection(sc,LANGUAGE=="RU" and "Типографика и Rich Text" or "Typography &amp; Rich Text")
    label(sc,LANGUAGE=="RU" and "Выбери шрифт и увидишь его до применения" or "Choose a font and preview before applying",23,C.muted,Enum.Font.Gotham,11)
    local preview=make("TextLabel",{Size=UDim2.new(1,-2,0,60),BackgroundColor3=C.panel,BorderSizePixel=0,
        Text="Aa  UITools 123",TextSize=23,TextColor3=C.white,FontFace=editorFontFace(),TextXAlignment=Enum.TextXAlignment.Center},sc)
    corner(preview,4)
    local fontList=make("Frame",{Size=UDim2.new(1,-2,0,0),AutomaticSize=Enum.AutomaticSize.Y,BackgroundTransparency=1},sc)
    make("UIGridLayout",{CellSize=UDim2.new(.5,-3,0,34),CellPadding=UDim2.fromOffset(5,5),SortOrder=Enum.SortOrder.LayoutOrder},fontList)
    for idx,entry in ipairs(FONT_CHOICES) do
        local b=make("TextButton",{LayoutOrder=idx,Text=entry[1],TextSize=12,
            FontFace=Font.new("rbxasset://fonts/families/"..entry[2]..".json"),
            TextColor3=C.white,BackgroundColor3=idx==editorFamilyIndex and C.blue or C.surface,BorderSizePixel=0,AutoButtonColor=true},fontList)
        corner(b,4)
        b.MouseButton1Click:Connect(function()
            editorFamilyIndex=idx
            preview.FontFace=editorFontFace()
            for _,other in ipairs(fontList:GetChildren()) do
                if other:IsA("TextButton") then other.BackgroundColor3=other.LayoutOrder==idx and C.blue or C.surface end
            end
        end)
    end
    local weight=editorAction(sc,(LANGUAGE=="RU" and "Насыщенность: " or "Weight: ")..FONT_WEIGHTS[editorWeightIndex][1],function()
        editorWeightIndex=editorWeightIndex%#FONT_WEIGHTS+1
        preview.FontFace=editorFontFace()
    end)
    local italic=editorAction(sc,LANGUAGE=="RU" and "Курсив: выкл." or "Italic: off",function()
        editorItalic=not editorItalic
        preview.FontFace=editorFontFace()
    end)
    local applyFont=editorAction(sc,LANGUAGE=="RU" and "Применить шрифт к объекту" or "Apply font to selection",function()
        editorApply(obj,"FontFace",editorFontFace(),sc)
    end)
    applyFont.BackgroundColor3=C.blue
    
    local updateCaptions
    updateCaptions=function()
        weight.Text=(LANGUAGE=="RU" and "Насыщенность: " or "Weight: ")..FONT_WEIGHTS[editorWeightIndex][1]
        italic.Text=(LANGUAGE=="RU" and "Курсив: " or "Italic: ")..(editorItalic and (LANGUAGE=="RU" and "ВКЛ" or "ON") or (LANGUAGE=="RU" and "ВЫКЛ" or "OFF"))
    end
    weight.MouseButton1Click:Connect(updateCaptions)
    italic.MouseButton1Click:Connect(updateCaptions)

    editorSection(sc,LANGUAGE=="RU" and "Оформление выбранного слова" or "Style one word")
    label(sc,LANGUAGE=="RU" and "Номер слова в тексте, начиная с 1. Исходный текст сохраняется до применения." or "Word position, starting at 1. Original text is kept until Apply.",42,C.muted,Enum.Font.Gotham,11)
    local row=make("Frame",{Size=UDim2.new(1,-2,0,35),BackgroundTransparency=1},sc)
    local wordNumber=make("TextBox",{Size=UDim2.new(.34,-4,1,0),Text=editorWordIndex,PlaceholderText=LANGUAGE=="RU" and "Слово №" or "Word #",ClearTextOnFocus=false,
        BackgroundColor3=C.surface,TextColor3=C.white,Font=Enum.Font.Code,TextSize=13},row)
    corner(wordNumber,4)
    local wordColor=make("TextBox",{Position=UDim2.new(.35,0,0,0),Size=UDim2.new(.65,0,1,0),Text=editorWordColor,
        BackgroundColor3=C.surface,TextColor3=C.white,Font=Enum.Font.Code,TextSize=13,ClearTextOnFocus=false},row)
    corner(wordColor,4)
    local richPreview=make("TextLabel",{Size=UDim2.new(1,-2,0,58),BackgroundColor3=C.panel,TextColor3=C.white,TextSize=16,
        TextWrapped=true,RichText=true,FontFace=editorFontFace(),Text="",BorderSizePixel=0},sc)
    corner(richPreview,4)
    local baseText=obj.ContentText
    
    local function richRefresh()
        local index=tonumber(wordNumber.Text)
        local color=editorColorParse(wordColor.Text)
        if not index or index%1~=0 or index&lt;1 or not color then
            richPreview.Text=editorTextEscape(baseText)
            return nil
        end
        local formatted=editorFormatWord(baseText,index,color,editorWordBold,editorWordUnderline,editorWordItalic)
        richPreview.Text=formatted or editorTextEscape(baseText)
        return formatted
    end
    richRefresh()
    wordNumber:GetPropertyChangedSignal("Text"):Connect(richRefresh)
    wordColor:GetPropertyChangedSignal("Text"):Connect(richRefresh)
    local function styleToggle(ru,en,getState,setState)
        local b=editorAction(sc,(LANGUAGE=="RU" and ru or en)..": "..(getState() and "ON" or "OFF"),function()
            setState(not getState())
            richRefresh()
        end)
        b.MouseButton1Click:Connect(function()
            b.Text=(LANGUAGE=="RU" and ru or en)..": "..(getState() and "ON" or "OFF")
        end)
    end
    styleToggle("Жирный","Bold",function() return editorWordBold end,function(v) editorWordBold=v end)
    styleToggle("Подчёркнутый","Underline",function() return editorWordUnderline end,function(v) editorWordUnderline=v end)
    styleToggle("Курсив слова","Word italic",function() return editorWordItalic end,function(v) editorWordItalic=v end)
    editorAction(sc,LANGUAGE=="RU" and "Применить оформление слова" or "Apply word styling",function()
        local result=richRefresh()
        if not result then
            editorMsg(sc,LANGUAGE=="RU" and "Укажи номер существующего слова и RGB/HEX цвет" or "Enter a valid word number and RGB/HEX color",false)
            return
        end
        local ok,err=pcall(function()
            ChangeHistoryService:SetWaypoint("UITools Before RichText")
            obj.RichText=true
            obj.Text=result
            ChangeHistoryService:SetWaypoint("UITools RichText")
        end)
        if ok then editorMsg(sc,LANGUAGE=="RU" and "Rich Text применён" or "Rich Text applied",true)
        else editorMsg(sc,tostring(err),false) end
    end)

    editorSection(sc,LANGUAGE=="RU" and "Обводка текста" or "Text outline")
    label(sc,LANGUAGE=="RU" and "Выбор цвета и толщины для всего текста" or "Outline color and thickness for full text",23,C.muted,Enum.Font.Gotham,11)
    local strokeRow=make("Frame",{Size=UDim2.new(1,-2,0,35),BackgroundTransparency=1},sc)
    local strokeColor=make("TextBox",{Size=UDim2.new(.55,-3,1,0),BackgroundColor3=C.surface,TextColor3=C.white,Font=Enum.Font.Code,TextSize=12,
        Text="#000000",ClearTextOnFocus=false},strokeRow)
    local strokeSize=make("TextBox",{Position=UDim2.new(.56,0,0,0),Size=UDim2.new(.44,0,1,0),BackgroundColor3=C.surface,
        TextColor3=C.white,Font=Enum.Font.Code,TextSize=12,Text="1.5",ClearTextOnFocus=false},strokeRow)
    editorAction(sc,LANGUAGE=="RU" and "Применить обводку" or "Apply outline",function()
        local color=editorColorParse(strokeColor.Text)
        local size=tonumber(strokeSize.Text)
        if not color or not size or size&lt;0.1 or size&gt;8 then
            editorMsg(sc,LANGUAGE=="RU" and "Цвет RGB/HEX, толщина 0.1–8" or "RGB/HEX color, thickness 0.1–8",false)
            return
        end
        local ok,err=pcall(function()
            ChangeHistoryService:SetWaypoint("UITools Before Stroke")
            local stroke=obj:FindFirstChild("UIToolsTextStroke")
            if not stroke then stroke=Instance.new("UIStroke") stroke.Name="UIToolsTextStroke" stroke.Parent=obj end
            stroke.Color=color
            stroke.Thickness=size
            stroke.ApplyStrokeMode=Enum.ApplyStrokeMode.Contextual
            ChangeHistoryService:SetWaypoint("UITools Stroke")
        end)
        if ok then editorMsg(sc,LANGUAGE=="RU" and "Обводка применена" or "Outline applied",true) else editorMsg(sc,tostring(err),false) end
    end)
    editorAction(sc,LANGUAGE=="RU" and "Убрать обводку UITools" or "Remove UITools outline",function()
        local stroke=obj:FindFirstChild("UIToolsTextStroke")
        if stroke then
            ChangeHistoryService:SetWaypoint("UITools Before Remove Stroke")
            stroke:Destroy()
            ChangeHistoryService:SetWaypoint("UITools Remove Stroke")
        end
        editorMsg(sc,LANGUAGE=="RU" and "Обводка убрана" or "Outline removed",true)
    end)
end

-- ForgeTools editor is optional: failure must not prevent UITools/Developer Tools/Aegis startup.
local editorLoaded, GUI_CANVAS = pcall(function()
    return require(script:WaitForChild("Modules"):WaitForChild("GUI_CANVAS"))
end)
if not editorLoaded then
    warn("ForgeTools GUI Editor startup failed: " .. tostring(GUI_CANVAS))
    GUI_CANVAS = nil
end
local function editorPage(sc)
    label(sc,LANGUAGE=="RU" and "UI Редактор" or "UI Editor",32,C.white,Enum.Font.GothamMedium,18)
    helpNote(sc,LANGUAGE=="RU" and "Визуальный редактор интерфейса: загрузи ScreenGui, редактируй на холсте и нажми «Применить». До этого исходный GUI не изменяется." or "Open a ScreenGui in the visual editor. All changes stay in a draft until Apply.",65)
    local openCanvas=primaryAction(sc,LANGUAGE=="RU" and "Открыть UI Редактор" or "Open UI Editor",40)
    if GUI_CANVAS then
        openCanvas.MouseButton1Click:Connect(function()
            local success,problem = pcall(function()
                GUI_CANVAS.open({plugin=plugin,Selection=Selection,History=ChangeHistoryService,language=LANGUAGE,theme=C})
            end)
            if not success then
                warn("ForgeTools GUI Editor open failed: " .. tostring(problem))
                editorMsg(sc,LANGUAGE=="RU" and "Редактор не открылся. Подробности в Output." or "Editor failed to open; check Output.",false)
            end
        end)
    else
        openCanvas.Text = LANGUAGE=="RU" and "GUI Editor недоступен (см. Output)" or "GUI Editor unavailable (see Output)"
        openCanvas.AutoButtonColor = false
        openCanvas.Active = false
    end
    label(sc,LANGUAGE=="RU" and "Слои · drag &amp; resize · предпросмотр экранов · выравнивание · Undo/Redo · Применить / Сбросить" or "Layers · drag &amp; resize · screen previews · alignment · Undo/Redo · Apply / Discard",54,C.muted,Enum.Font.Gotham,12)
    sectionHeading(sc,LANGUAGE=="RU" and "Быстрое редактирование выбранных элементов" or "Quick edit selected elements")
    sectionHeading(sc,LANGUAGE=="RU" and "Оформление текста" or "Text styling")
    label(sc,LANGUAGE=="RU" and "Оформление текста изменяет выбранный текст сразу. При необходимости отменяй действие через Roblox Studio (Ctrl+Z)." or "Text styling changes selected text immediately. Press Ctrl+Z to undo.",62,C.muted,Enum.Font.Gotham,11)
    local obj=editorSelected()
    if obj and (obj:IsA("TextLabel") or obj:IsA("TextButton") or obj:IsA("TextBox")) then
        editorTextDesign(sc,obj)
    else
        label(sc,LANGUAGE=="RU" and "Для оформления текста выдели TextLabel, TextButton или TextBox в Explorer." or "Select a TextLabel, TextButton or TextBox in Explorer.",43,C.muted,Enum.Font.Gotham,12)
    end
    sectionHeading(sc,LANGUAGE=="RU" and "Массовое оформление" or "Batch styling")
    local objects=selectedObjects()
    stat(sc,LANGUAGE=="RU" and "Выбрано GUI-элементов" or "Selected GUI elements",#objects)
    label(sc,LANGUAGE=="RU" and "Выдели несколько элементов в Explorer (Ctrl). Применяй одинаковые параметры без копирования каждого вручную." or "Multi-select GUI elements in Explorer (Ctrl) and apply consistent styling in one action.",62,C.muted)
    local function batch(name,callback)
        if #objects==0 then foot.Text=t("none") return end
        ChangeHistoryService:SetWaypoint("ForgeTools Before "..name)
        local count=0
        for _,o in ipairs(objects) do
            local ok,success=pcall(callback,o)
            if ok and success then count+=1 elseif not ok then warn("[ForgeTools] "..name.." skipped "..o.Name) end
        end
        ChangeHistoryService:SetWaypoint("ForgeTools "..name)
        foot.Text=(LANGUAGE=="RU" and "Изменено: " or "Updated: ")..count
    end
    local radius=button(sc,LANGUAGE=="RU" and "Одинаковое скругление · 8 px" or "Unify corner radius · 8 px",36)
    radius.MouseButton1Click:Connect(function()
        batch("Corners",function(o)
            local c=o:FindFirstChildOfClass("UICorner")
            if not c then c=Instance.new("UICorner") c.Parent=o end
            c.CornerRadius=UDim.new(0,8)
            return true
        end)
    end)
    local strokes=button(sc,LANGUAGE=="RU" and "Единая обводка · 1 px" or "Unify outline · 1 px",36)
    strokes.MouseButton1Click:Connect(function()
        batch("Outlines",function(o)
            local stroke=o:FindFirstChild("ForgeToolsOutline")
            if stroke and not stroke:IsA("UIStroke") then return false end
            if not stroke then stroke=Instance.new("UIStroke") stroke.Name="ForgeToolsOutline" stroke.Parent=o end
            stroke.ApplyStrokeMode=Enum.ApplyStrokeMode.Border
            stroke.Thickness=1
            stroke.Color=Color3.fromRGB(98,156,220)
            stroke.Transparency=0.3
            return true
        end)
    end)
    local equalWidth=button(sc,LANGUAGE=="RU" and "Одинаковая ширина · по первому элементу" or "Same width · match first selected",36)
    equalWidth.MouseButton1Click:Connect(function()
        if #objects&lt;2 then foot.Text=LANGUAGE=="RU" and "Выдели минимум 2 объекта" or "Select at least 2 objects" return end
        local target=objects[1].Size.X
        batch("Equal widths",function(o)
            if o==objects[1] then return false end
            o.Size=UDim2.new(target.Scale,target.Offset,o.Size.Y.Scale,o.Size.Y.Offset)
            return true
        end)
    end)

    label(sc,LANGUAGE=="RU" and "Холст открывается отдельным окном Studio. В разделе оформления можно изменить текст и применить стиль сразу к нескольким выбранным объектам." or "The canvas opens in its own Studio window. Use this page for text styling and batch operations.",64,C.muted,Enum.Font.Gotham,12)
end

local function antiCheatPage(sc)
    sectionHeading(sc,LANGUAGE=="RU" and "FT ANTICHEAT / СЕРВЕРНАЯ ЗАЩИТА" or "FT ANTICHEAT / SERVER SECURITY")
    label(sc,"FT AntiCheat",35,C.white,Enum.Font.GothamBold,18)
    helpNote(sc,LANGUAGE=="RU" and "Защита работает на сервере игры. Начальная конфигурация — только наблюдение: без киков, банов и откатов позиции." or "Server-side detection. Initial setup is audit-only: no kicks, bans or position rollbacks.",68)
    local status,folder=antiCheatStatus()
    local statusText={missing=LANGUAGE=="RU" and "Не установлен" or "Not installed",ready=LANGUAGE=="RU" and "Установлен / наблюдение" or "Installed / audit-only",outdated=LANGUAGE=="RU" and "Требуется обновление" or "Update required",broken=LANGUAGE=="RU" and "Неполные компоненты" or "Incomplete installation",conflict=LANGUAGE=="RU" and "Конфликт имени" or "Name conflict"}
    local statusRow=stat(sc,LANGUAGE=="RU" and "Статус" or "Status",statusText[status] or status)
    sectionHeading(sc,LANGUAGE=="RU" and "УСТАНОВКА" or "INSTALLATION")
    local doInstall=primaryAction(sc,status=="missing" and (LANGUAGE=="RU" and "Установить FT AntiCheat" or "Install FT AntiCheat") or (LANGUAGE=="RU" and "Проверить / обновить компоненты" or "Verify / update components"),39)
    if status=="conflict" then doInstall.Active=false;doInstall.BackgroundColor3=C.panel;doInstall.TextColor3=C.muted end
    local message=label(sc,"",0,C.muted,Enum.Font.Gotham,11)
    doInstall.MouseButton1Click:Connect(function()
        if status=="conflict" then return end
        local ok,info=antiCheatInstall()
        message.Text=LANGUAGE=="RU" and (ok and "Установлено. Перезапусти Play и открой журнал FT AntiCheat в игре." or "Ошибка: "..tostring(info)) or tostring(info)
        message.TextColor3=ok and C.green or C.red
        message.Size=UDim2.new(1,-2,0,48)
        if ok then
            
            local statusNow=antiCheatStatus()
            statusRow.Text=tostring(statusText[statusNow] or statusNow)
            if statusNow=="ready" then
                doInstall.Text=LANGUAGE=="RU" and "Компоненты актуальны" or "Components current"
                message.Text=LANGUAGE=="RU" and "Компоненты актуальны. Перезапусти Play." or "Components current. Restart Play."
                message.TextColor3=C.green
            else
                doInstall.Text=LANGUAGE=="RU" and "Проверить / обновить компоненты" or "Verify / update components"
                message.Text=LANGUAGE=="RU" and ("Не все компоненты обновлены: "..tostring(statusNow)) or ("Components need attention: "..tostring(statusNow))
                message.TextColor3=C.red
            end
        end
    end)
    if ServerScriptService:FindFirstChild("UIToolsSentinel") and ServerScriptService.UIToolsSentinel:GetAttribute("ForgeToolsReplaced")~=true then
        helpNote(sc,LANGUAGE=="RU" and "Найден старый UIToolsSentinel. Перед заменой его настройки сохранятся в ServerStorage/ForgeToolsBackup; старый Controller будет отключён, а не удалён." or "Old UIToolsSentinel found. Its settings will be backed up to ServerStorage/ForgeToolsBackup; the old controller will be disabled, not deleted.",72)
        local migrate=button(sc,LANGUAGE=="RU" and "Подтвердить замену Sentinel" or "Confirm Sentinel replacement",38)
        migrate.MouseButton1Click:Connect(function()
            local ok,info=antiCheatInstall(true)
            message.Text=ok and (LANGUAGE=="RU" and "Новая защита установлена. Перезапусти Play." or "Installed. Restart Play.") or tostring(info)
            message.TextColor3=ok and C.green or C.red
            message.Size=UDim2.new(1,-2,0,50)
            if ok then migrate.Active=false;migrate.Text=LANGUAGE=="RU" and "Sentinel отключён" or "Sentinel disabled" end
        end)
    end
    sectionHeading(sc,LANGUAGE=="RU" and "АКТИВНЫЕ ПРОВЕРКИ" or "ACTIVE DETECTORS")
    label(sc,LANGUAGE=="RU" and "• Проверка серверной позиции по времени\n• Телепорт / возможный noclip\n• Fly: зависание / устойчивый подъём без опоры\n• Журнал сессии (до 300 событий)" or "• Speed and abnormal movement\n• Possible noclip\n• Server audit log (up to 150 entries)",80,C.white,Enum.Font.Gotham,12)
    helpNote(sc,LANGUAGE=="RU" and "Cash и другие валюты leaderstats теперь отслеживаются сервером. Большие/частые изменения попадают в 'Баланс' только для проверки. Настройки: ServerScriptService / ForgeToolsAntiCheat / Config. Это НЕ блокировка и не доказательство чита; для реальной защиты начисления должны проверяться в серверном коде." or "Server leaderstats currency changes are now monitored (review-only). Edit ServerScriptService / ForgeToolsAntiCheat / Config. Real security requires validation in your server reward handlers.",105)
    sectionHeading(sc,LANGUAGE=="RU" and "ДОСТУП К ЖУРНАЛУ" or "AUDIT LOG ACCESS")
    label(sc,LANGUAGE=="RU" and "Разрешённые UserId (через запятую). В личной игре владелец также имеет доступ." or "Authorized UserIds (comma-separated). User-owned place creators also have access.",45,C.muted,Enum.Font.Gotham,11)
    local ctrl=folder and folder:FindFirstChild("Controller")
    local field=make("TextBox",{Size=UDim2.new(1,-2,0,33),BackgroundColor3=C.surface,Text=tostring(ctrl and ctrl:GetAttribute("AllowedAdminUserIds") or ""),PlaceholderText="123456789, 987654321",ClearTextOnFocus=false,TextColor3=C.white,PlaceholderColor3=C.muted,Font=Enum.Font.Code,TextSize=12,TextXAlignment=Enum.TextXAlignment.Left,BorderSizePixel=0},sc)
    corner(field,5)
    local save=button(sc,LANGUAGE=="RU" and "Сохранить доступ к журналу" or "Save audit access",32)
    save.MouseButton1Click:Connect(function()
        local current=ServerScriptService:FindFirstChild(AC_NAME)
        local server=current and current:FindFirstChild("Controller")
        if not server or not server:IsA("Script") then message.Text=LANGUAGE=="RU" and "Сначала установи FT AntiCheat" or "Install FT AntiCheat first";message.Size=UDim2.new(1,-2,0,29);return end
        if not field.Text:match("^[%d,%s]*$") then message.Text=LANGUAGE=="RU" and "Нужны только UserId через запятую" or "Use comma-separated UserIds";message.Size=UDim2.new(1,-2,0,29);return end
        local seen,ids={},{}
        for id in field.Text:gmatch("%d+") do
            if #id&gt;17 or tonumber(id)==0 then return end
            if not seen[id] then seen[id]=true;table.insert(ids,id) end
        end
        table.sort(ids)
        server:SetAttribute("AllowedAdminUserIds",table.concat(ids,","))
        message.Text=LANGUAGE=="RU" and "Доступ сохранён. Перезапусти Play." or "Saved. Restart Play."
        message.Size=UDim2.new(1,-2,0,29)
        message.TextColor3=C.green
    end)
    sectionHeading(sc,LANGUAGE=="RU" and "СПИСОК ИГРОКОВ / НАБЛЮДЕНИЕ" or "PLAYER LIST / OBSERVER")
    helpNote(sc,LANGUAGE=="RU" and "Свой TAB включается отдельно: он заменяет стандартный PlayerList и показывает Cash. Наблюдатель скрывается из этого TAB для обычных игроков, администраторы видят значок ◉ у ника. Это НЕ скрывает Player из API Roblox." or "Optional player list replaces Roblox PlayerList and displays Cash. Hidden observers show a ◉ symbol to admins. This does NOT hide Player instances from Roblox APIs.",102)
    local tabToggle=button(sc,ctrl and ctrl:GetAttribute("CustomPlayerListEnabled")==true and (LANGUAGE=="RU" and "Свой TAB: включён (выключить)" or "Custom TAB: on (disable)") or (LANGUAGE=="RU" and "Свой TAB: выключен (включить)" or "Custom TAB: off (enable)"),36)
    tabToggle.MouseButton1Click:Connect(function()
        local current=ServerScriptService:FindFirstChild(AC_NAME)
        local server=current and current:FindFirstChild("Controller")
        if not server or not server:IsA("Script") then return end
        local on=server:GetAttribute("CustomPlayerListEnabled")~=true
        server:SetAttribute("CustomPlayerListEnabled",on)
        tabToggle.Text=LANGUAGE=="RU" and (on and "Свой TAB: включён (выключить)" or "Свой TAB: выключен (включить)") or (on and "Custom TAB: on (disable)" or "Custom TAB: off (enable)")
    end)
    helpNote(sc,LANGUAGE=="RU" and "Граф связей открывается в игровом журнале FT AntiCheat → Анализ связей. Поиск по нику или UserId, наведение показывает карточку. Источник данных — только завершённые серверные операции, добровольно переданные через BindableEvent RecordTransaction. Сканирование DataStore и изменение предметов не выполняются." or "Open FT AntiCheat in Play → Player relationships. The graph uses only confirmed server operations sent to RecordTransaction; it never scans DataStore or modifies items.",129)

    label(sc,LANGUAGE=="RU" and "События текущей сессии не сохраняются после её завершения. Aegis v0.5 — MIT, авторство исходного проекта сохранено; безопасность требует настройки под игру." or "Session events are not persistent. Aegis v0.5 (MIT), upstream attribution preserved. Tune against your game before release.",67,C.muted,Enum.Font.Gotham,11)
end




local sections={
    ui={{"home","Начало","Start"},{"responsive","Диагностика","Diagnostics"},{"editor","UI Редактор","UI Editor"},{"animations","Анимации","Animations"},{"gradients","Градиенты","Gradients"},{"textfx","Цветовые эффекты","Color FX"}},
    developer={{"devhome","Начало","Start"},{"anticheat","FT AntiCheat","FT AntiCheat"},{"inspector","Forge Inspector","Forge Inspector"}},
}
local function navButton(parent,caption,x,y,w,h)
    local b=make("TextButton",{
        Position=UDim2.new(x,0,0,y),Size=UDim2.new(w,-4,0,h),
        BackgroundColor3=C.panel,BorderSizePixel=0,Text=caption,
        TextColor3=C.muted,TextSize=12,Font=Enum.Font.GothamMedium,
        TextWrapped=true,TextTruncate=Enum.TextTruncate.AtEnd,AutoButtonColor=false
    },parent)
    corner(b,4)
    local scale=make("UIScale",{Scale=1},b)
    local function ease(target)
        if not b.Parent then return end
        TweenService:Create(scale,TweenInfo.new(.16,Enum.EasingStyle.Sine,Enum.EasingDirection.Out),{Scale=target}):Play()
    end
    b.MouseEnter:Connect(function() ease(1.025) end)
    b.MouseLeave:Connect(function() ease(1) end)
    b.MouseButton1Down:Connect(function() ease(.975) end)
    b.MouseButton1Up:Connect(function() ease(1.025) end)
    return b
end
local sectionButtons={
    ui=navButton(nav,"UITools",0,0,.5,37),
    developer=navButton(nav,"Developer Tools",.5,0,.5,37),
}
sectionButtons.ui.MouseButton1Click:Connect(function()
    selectedSection="ui";selectedTab="home";recordUsage("section:ui:home");draw()
end)
sectionButtons.developer.MouseButton1Click:Connect(function()
    selectedSection="developer";selectedTab="devhome";recordUsage("section:developer:devhome");draw()
end)
local function renderNavigation()
    -- Settings and Feedback have no secondary tabs. Reclaim that space instead
    -- of keeping the large empty navigation slot above the page content.
    local compactNavigation=(selectedTab=="settings" or selectedTab=="feedback")
    main.Position=UDim2.fromOffset(0,compactNavigation and 138 or 210)
    main.Size=UDim2.new(1,0,1,compactNavigation and -173 or -245)
    nav.Size=UDim2.new(1,0,0,compactNavigation and 43 or 116)
    settingsButton.BackgroundColor3=selectedTab=="settings" and C.accentSoft or C.surface
    feedbackButton.BackgroundColor3=selectedTab=="feedback" and C.accentSoft or C.surface
    settingsCaption.Text=LANGUAGE=="RU" and "Настройки" or "Settings"
    feedbackCaption.Text=LANGUAGE=="RU" and "Связь" or "Feedback"
    for _,o in ipairs(nav:GetChildren()) do
        if o.Name=="ForgeSubTab" then o:Destroy() end
    end
    for section,b in pairs(sectionButtons) do
        local active=(selectedTab~="settings" and selectedTab~="feedback") and section==selectedSection
        b.BackgroundColor3=active and C.accentSoft or C.panel
        b.TextColor3=active and C.accentHover or C.muted
        b.FontFace=Font.new("rbxasset://fonts/families/GothamSSm.json",active and Enum.FontWeight.Bold or Enum.FontWeight.Medium)
        local edge=b:FindFirstChild("SelectedLine")
        if not edge then
            edge=make("Frame",{Name="SelectedLine",AnchorPoint=Vector2.new(.5,1),Position=UDim2.new(.5,0,1,-1),Size=UDim2.new(1,-14,0,2),BackgroundColor3=C.blue,BorderSizePixel=0},b)
        end
        edge.Visible=active
    end
    local tabList=(selectedTab=="settings" or selectedTab=="feedback") and {} or sections[selectedSection]
    local perRow=3
    for i,data in ipairs(tabList) do
        local row=math.floor((i-1)/perRow)
        local column=(i-1)%perRow
        local b=navButton(nav,LANGUAGE=="RU" and data[2] or data[3],column/perRow,43+row*33,1/perRow,29)
        b.Name="ForgeSubTab"
        local active=selectedTab==data[1]
        b.BackgroundColor3=active and C.accentSoft or C.panel
        b.TextColor3=active and C.white or C.muted
        if active then
            local marker=make("Frame",{Size=UDim2.new(1,-12,0,2),Position=UDim2.new(0,6,1,-2),BackgroundColor3=C.blue,BorderSizePixel=0},b)
        end
        b.MouseButton1Click:Connect(function()
            selectedTab=data[1]
            recordUsage("section:"..selectedSection..":"..selectedTab)
            draw()
            if data[1]=="inspector" then
                recordUsage("tool:forge_inspector")
                local ok,err=pcall(openForgeInspector)
                if not ok then warn("[ForgeTools] Cannot open Forge Inspector: "..tostring(err)) end
            end
        end)
    end
end


local function actionTile(sc,titleText,description,tab,isPrimary,enabled,onClick)
    local outer=make("Frame",{Size=UDim2.new(1,-2,0,67),BackgroundColor3=isPrimary and C.accentSoft or C.panel,BorderSizePixel=0},sc)
    corner(outer,7)
    local stripe=make("Frame",{Size=UDim2.new(0,3,1,-16),Position=UDim2.fromOffset(7,8),BackgroundColor3=isPrimary and C.blue or C.line,BorderSizePixel=0},outer)
    corner(stripe,2)
    local title=label(outer,titleText,23,enabled==false and C.muted or C.white,Enum.Font.GothamBold,13)
    title.Position=UDim2.fromOffset(19,8)
    title.Size=UDim2.new(1,-43,0,23)
    local info=label(outer,description,26,C.muted,Enum.Font.Gotham,11)
    info.Position=UDim2.fromOffset(19,32)
    info.Size=UDim2.new(1,-43,0,27)
    local chevron=make("TextLabel",{Size=UDim2.fromOffset(20,24),Position=UDim2.new(1,-25,0,17),BackgroundTransparency=1,Text=enabled==false and "–" or "&gt;",TextColor3=enabled==false and C.muted or C.accentHover,TextSize=15,Font=Enum.Font.GothamBold},outer)
    local hit=make("TextButton",{Name="OpenAction",Size=UDim2.fromScale(1,1),BackgroundTransparency=1,Text="",AutoButtonColor=false,Active=enabled~=false},outer)
    local baseTileColor=isPrimary and C.accentSoft or C.panel
    local tileTween,chevronTween
    local function tileMotion(active)
        if enabled==false or not outer.Parent then return end
        if tileTween then tileTween:Cancel() end
        if chevronTween then chevronTween:Cancel() end
        local info=TweenInfo.new(active and .15 or .19,Enum.EasingStyle.Quad,Enum.EasingDirection.Out)
        tileTween=TweenService:Create(outer,info,{BackgroundColor3=active and baseTileColor:Lerp(C.accentHover,.14) or baseTileColor})
        chevronTween=TweenService:Create(chevron,info,{Position=UDim2.new(1,active and -21 or -25,0,17)})
        tileTween:Play()
        chevronTween:Play()
    end
    hit.MouseEnter:Connect(function() tileMotion(true) end)
    hit.MouseLeave:Connect(function() tileMotion(false) end)
    hit.MouseButton1Click:Connect(function() if enabled~=false then if onClick then onClick() else selectedTab=tab recordUsage("section:"..selectedSection..":"..tab) draw() end end end)
    return outer
end
local function homePage(sc)
    sectionHeading(sc,LANGUAGE=="RU" and "РАБОЧАЯ ОБЛАСТЬ / UI" or "WORKSPACE / UI")
    label(sc,LANGUAGE=="RU" and "Создавай. Проверяй. Улучшай." or "Create. Inspect. Refine.",37,C.white,Enum.Font.GothamBold,18)
    helpNote(sc,LANGUAGE=="RU" and "Выдели ScreenGui или элемент в Explorer. Начни с проверки адаптации, затем добавляй оформление и эффекты." or "Select a ScreenGui or UI element in Explorer. Start with diagnostics, then style or animate it.",66)
    local list=Selection:Get()
    local count=0
    for _,obj in ipairs(list) do
        if obj:IsA("GuiObject") or obj:IsA("LayerCollector") then count+=1 end
    end
    stat(sc,LANGUAGE=="RU" and "GUI в выборе" or "GUI selected",count)
    sectionHeading(sc,LANGUAGE=="RU" and "НАЧАТЬ С ЭТОГО" or "START HERE")
    actionTile(sc,LANGUAGE=="RU" and "Проверить адаптацию" or "Run GUI diagnostics",LANGUAGE=="RU" and "Проблемы размеров, обрезания и экранов" or "Screen sizes, clipping and layout issues","responsive",true,count&gt;0)
    if count==0 then label(sc,LANGUAGE=="RU" and "Сначала выбери GUI-объект в Explorer." or "Select a GUI object in Explorer first.",25,C.yellow) end
    sectionHeading(sc,LANGUAGE=="RU" and "ОФОРМЛЕНИЕ И ЭФФЕКТЫ" or "STYLING &amp; EFFECTS")
    actionTile(sc,LANGUAGE=="RU" and "UI Редактор" or "UI Editor",LANGUAGE=="RU" and "GUI Editor, оформление текста, массовые операции" or "GUI Editor, text styling, batch operations","editor",false,true)
    actionTile(sc,LANGUAGE=="RU" and "Анимации" or "Animations",LANGUAGE=="RU" and "Эффект, живой предпросмотр, применение" or "Choose an effect, preview it, apply","animations",false,true)
    actionTile(sc,LANGUAGE=="RU" and "Градиенты" or "Gradients",LANGUAGE=="RU" and "Цветовые пресеты и переходы" or "Color presets and transitions","gradients",false,true)
    actionTile(sc,LANGUAGE=="RU" and "Анимация цвета" or "Color animation",LANGUAGE=="RU" and "Движение и переливы цвета" or "Color flow and shimmer","textfx",false,true)
end
local function developerHomePage(sc)
    sectionHeading(sc,LANGUAGE=="RU" and "ИНСТРУМЕНТЫ РАЗРАБОТЧИКА" or "DEVELOPER UTILITIES")
    label(sc,"Developer Tools",36,C.white,Enum.Font.GothamBold,18)
    helpNote(sc,LANGUAGE=="RU" and "Здесь собраны инструменты разработчика. Выбирай нужный инструмент на панели вкладок выше. Настройки доступны через шестерёнку вверху." or "Developer utilities are available in the tabs above. Open preferences with the top-right gear.",88)
    sectionHeading(sc,LANGUAGE=="RU" and "ИНСТРУМЕНТЫ" or "TOOLS")
    actionTile(sc,"FT AntiCheat",LANGUAGE=="RU" and "Проверки сервера, конфигурация, журнал и доступ" or "Server monitoring, configuration, audit and permissions","anticheat",true,true)
    -- Studio log tile removed by user request; internal log code retained for compatibility.
    if ServerStorage:FindFirstChild("UIToolsDeveloperTool") or ServerScriptService:FindFirstChild("UIToolsGrant") then
        sectionHeading(sc,LANGUAGE=="RU" and "КОМПОНЕНТЫ СТАРОЙ ВЕРСИИ" or "LEGACY COMPONENTS")
        helpNote(sc,LANGUAGE=="RU" and "Найден ранее установленный строительный Tool. Новая версия его не использует и не обновляет. Если он больше не нужен, удали вручную ServerStorage/UIToolsDeveloperTool и ServerScriptService/UIToolsGrant после сохранения копии игры." or "An older building Tool is still installed. This version does not use or update it. Back up the place and manually remove ServerStorage/UIToolsDeveloperTool and ServerScriptService/UIToolsGrant if no longer needed.",110)
    end
end
local function inspectorLaunchPage(sc)
    sectionHeading(sc,LANGUAGE=="RU" and "FORGE INSPECTOR" or "FORGE INSPECTOR")
    label(sc,"Forge Inspector",36,C.white,Enum.Font.GothamBold,18)
    helpNote(sc,LANGUAGE=="RU" and "Окно анализатора открывается отдельно. Если оно не появилось, нажми кнопку ниже." or "The analyzer opens in its own window. If it did not appear, use the button below.",76)
    local launch=primaryAction(sc,LANGUAGE=="RU" and "Открыть Forge Inspector" or "Open Forge Inspector",40)
    launch.MouseButton1Click:Connect(function()
        local ok,err=pcall(openForgeInspector)
        if not ok then warn("[ForgeTools] Cannot open Forge Inspector: "..tostring(err)) end
    end)
    helpNote(sc,LANGUAGE=="RU" and "Local Scan работает в Studio. Deep Scan отправляет выбранный код на сервер только после явного запуска." or "Local Scan runs in Studio. Deep Scan sends selected source to the server only after explicit activation.",64)
end
local function feedbackPage(sc)
    sectionHeading(sc,LANGUAGE=="RU" and "ОБРАТНАЯ СВЯЗЬ" or "FEEDBACK / SUPPORT")
    helpNote(sc,LANGUAGE=="RU" and "Сообщи об ошибке или предложи улучшение. Ник не подтверждает владение аккаунтом. Не отправляй пароли и личные данные." or "Report an issue or suggest an improvement. Nickname does not verify account ownership. Never send passwords or personal data.",75)
    local draft=readSetting("ForgeToolsFeedbackDraftV1")
    if type(draft)~="table" then draft={nick="",subject="",message=""} end
    local function feedbackField(caption,placeholder,key,height,multiline)
        label(sc,caption,25,C.muted,Enum.Font.GothamMedium,12)
        local field=make("TextBox",{Name="Feedback_"..key,Size=UDim2.new(1,-4,0,height),Text=tostring(draft[key] or ""),PlaceholderText=placeholder,ClearTextOnFocus=false,MultiLine=multiline or false,TextWrapped=multiline or false,TextColor3=C.white,PlaceholderColor3=C.muted,BackgroundColor3=C.surface,BorderSizePixel=0,Font=Enum.Font.Gotham,TextSize=13,TextXAlignment=Enum.TextXAlignment.Left,TextYAlignment=multiline and Enum.TextYAlignment.Top or Enum.TextYAlignment.Center},sc)
        make("UICorner",{CornerRadius=UDim.new(0,6)},field)
        return field
    end
    local ticketNick=feedbackField(LANGUAGE=="RU" and "Ник Roblox (обязательно)" or "Roblox nickname (required)","qwerty123","nick",36,false)
    local ticketSubject=feedbackField(LANGUAGE=="RU" and "Тема обращения (обязательно)" or "Ticket subject (required)",LANGUAGE=="RU" and "Например: ошибка редактора" or "Example: Editor issue","subject",36,false)
    local ticketMessage=feedbackField(LANGUAGE=="RU" and "Сообщение (обязательно)" or "Message (required)",LANGUAGE=="RU" and "Опиши проблему или предложение..." or "Describe the issue or suggestion...","message",120,true)
    local ticketStatus=label(sc,LANGUAGE=="RU" and "Тикет не отправлен" or "Ticket not sent",30,C.muted)
    local saveTicket=button(sc,LANGUAGE=="RU" and "Сохранить черновик" or "Save draft",34)
    saveTicket.MouseButton1Click:Connect(function()
        local nick=string.sub(ticketNick.Text,1,20)
        local subject=string.sub(ticketSubject.Text,1,120)
        local message=string.sub(ticketMessage.Text,1,3000)
        if nick:match("^%s*$") or subject:match("^%s*$") or message:match("^%s*$") then
            ticketStatus.Text=LANGUAGE=="RU" and "Заполни ник, тему и сообщение" or "Fill in nickname, subject and message"
            return
        end
        local ok=pcall(function() plugin:SetSetting("ForgeToolsFeedbackDraftV1",{nick=nick,subject=subject,message=message}) end)
        ticketStatus.Text=ok and (LANGUAGE=="RU" and "Черновик сохранён локально · НЕ отправлен" or "Draft saved locally · NOT sent") or (LANGUAGE=="RU" and "Не удалось сохранить черновик" or "Could not save draft")
    end)
    local submitTicket=button(sc,LANGUAGE=="RU" and "Отправить тикет" or "Submit ticket",34)
    local busy=false
    submitTicket.MouseButton1Click:Connect(function()
        if busy then return end
        local nick=ticketNick.Text:match("^%s*(.-)%s*$") or ""
        local subject=ticketSubject.Text:match("^%s*(.-)%s*$") or ""
        local message=ticketMessage.Text:match("^%s*(.-)%s*$") or ""
        if not nick:match("^[%w_]+$") or #nick&lt;3 or #nick&gt;20 or #subject&lt;3 or #subject&gt;120 or #message&lt;10 or #message&gt;3000 then
            ticketStatus.Text=LANGUAGE=="RU" and "Проверь ник (3-20), тему (3-120), сообщение (10-3000)" or "Check nickname (3-20), subject (3-120), message (10-3000)"
            return
        end
        local lastSent=tonumber(readSetting("ForgeToolsTicketSentAtV1")) or 0
        if os.time()-lastSent&lt;60 then
            ticketStatus.Text=LANGUAGE=="RU" and "Подожди минуту перед новой отправкой" or "Wait one minute before another ticket"
            return
        end
        busy=true
        submitTicket.Text=LANGUAGE=="RU" and "Отправка..." or "Sending..."
        ticketStatus.Text=LANGUAGE=="RU" and "Соединение с сервером..." or "Contacting server..."
        task.spawn(function()
            local ok,response=pcall(function()
                local token=getInstallationToken()
                return HttpService:RequestAsync({Url=TICKET_ENDPOINT,Method="POST",Headers=apiHeaders(token),Body=HttpService:JSONEncode({nickname=nick,subject=subject,message=message,installation=installation,version=VERSION})})
            end)
            busy=false
            if ok and response and response.StatusCode==201 then
                local parsed,body=pcall(function() return HttpService:JSONDecode(response.Body) end)
                if parsed and type(body)=="table" and body.ok==true and type(body.id)=="number" then
                    ticketStatus.Text=(LANGUAGE=="RU" and "Тикет создан: #" or "Ticket created: #")..tostring(body.id)
                    submitTicket.Text=LANGUAGE=="RU" and "Отправить ещё" or "Submit another"
                    pcall(function() plugin:SetSetting("ForgeToolsFeedbackDraftV1",nil) end)
                    pcall(function() plugin:SetSetting("ForgeToolsTicketSentAtV1",os.time()) end)
                    return
                end
            end
            local code=ok and response and tostring(response.StatusCode) or "network"
            if code=="429" then
                ticketStatus.Text=LANGUAGE=="RU" and "Слишком часто. Попробуй позже." or "Too many requests. Try again later."
                submitTicket.Text=LANGUAGE=="RU" and "Повторить позже" or "Retry later"
                return
            end
            ticketStatus.Text=(LANGUAGE=="RU" and "Не отправлено. Ошибка: " or "Not sent. Error: ")..code
            submitTicket.Text=LANGUAGE=="RU" and "Повторить отправку" or "Retry submit"
        end)
    end)
end

-- Authenticity status is informational. No embedded secret or claim that client Luau cannot be modified.
-- Privacy: release-status check sends installation/version; disclose this in the plugin notice.
-- No remote executable code or commands may be consumed from the response.
local AUTH_ENDPOINT="https://analytics.mivvinet.xyz/api/v1/public/authenticity"
local authenticityState="not_checked"
local authenticityDetail=""
local authenticityBusy=false
local function checkAuthenticity()
    if authenticityBusy then return end
    authenticityBusy=true
    task.spawn(function()
        local ok,response=pcall(function()
            return HttpService:RequestAsync({Url=AUTH_ENDPOINT,Method="POST",
                Headers={["Content-Type"]="application/json"},
                Body=HttpService:JSONEncode({installation=installation,version=VERSION})})
        end)
        if not ok or not response or not response.Success then
            authenticityState="unavailable"
            authenticityDetail=ok and response and tostring(response.StatusCode) or "network"
        else
            local parsed,data=pcall(function() return HttpService:JSONDecode(response.Body) end)
            if parsed and type(data)=="table" and data.official==true then
                authenticityState="listed"
            elseif parsed and type(data)=="table" and data.revoked==true then
                authenticityState="revoked"
            else
                authenticityState="unverified"
            end
        end
        authenticityBusy=false
    end)
end
checkAuthenticity()

-- Update Center receives release metadata only. Never execute, require, or insert network content.
-- Checking updates does not send installation IDs, analytics or credentials.
local UPDATE_ENDPOINT="https://analytics.mivvinet.xyz/api/v1/public/updates"
local updateInfo={state="checking",latest=VERSION,importance="none",notes="",url=""}
local updateBusy=false
local UPDATE_CHECK_INTERVAL=12*60*60
local lastUpdateCheck=0
local function parseVersion(v)
    if type(v)~="string" then return nil end
    local a,b,c,d=v:match("^(%d+)%.(%d+)%.(%d+)%.(%d+)$")
    if not a then
        a,b,c=v:match("^(%d+)%.(%d+)%.(%d+)$")
        d="0"
    end
    if not a then return nil end
    a,b,c,d=tonumber(a),tonumber(b),tonumber(c),tonumber(d)
    if a&gt;999 or b&gt;999 or c&gt;999 or d&gt;999 then return nil end
    return ((a*1000+b)*1000+c)*1000+d
end
local function safeUpdateUrl(raw)
    -- The release server may provide a link, but only to this HTTPS hostname.
    if type(raw)~="string" or #raw&gt;350 then return "" end
    if raw:match("^https://analytics%.mivvinet%.xyz/[A-Za-z0-9%._%-%/]+$") then return raw end
    return ""
end
-- Modal only covers ForgeTools widget; it does not change Studio or execute remote code.
local updateModal=nil
local SKIPPED_UPDATE_SETTING="ForgeToolsSkippedUpdateVersionV1"
local dismissedUpdateVersion=readSetting(SKIPPED_UPDATE_SETTING)
if type(dismissedUpdateVersion)~="string" or not parseVersion(dismissedUpdateVersion) then dismissedUpdateVersion=nil end
local function showUpdateModal()
    if updateInfo.state~="available" or not widget.Enabled then return end
    if updateInfo.importance=="optional" and dismissedUpdateVersion==updateInfo.latest then return end
    if updateModal then updateModal:Destroy() updateModal=nil end
    local mandatory=(updateInfo.importance=="required" or updateInfo.importance=="critical")
    -- Do not lock users out when the release does not have a valid download link.
    if mandatory and updateInfo.url=="" then mandatory=false end
    local shade=make("Frame",{Name="ForgeUpdateModal",Size=UDim2.fromScale(1,1),BackgroundColor3=C.bg,BorderSizePixel=0,ZIndex=200},widget)
    updateModal=shade
    local panel=make("Frame",{AnchorPoint=Vector2.new(.5,.5),Position=UDim2.fromScale(.5,.5),Size=UDim2.new(1,-32,1,-48),BackgroundColor3=C.panel,BorderSizePixel=0,ZIndex=201},shade)
    corner(panel,12)
    outline(panel,C.line,1)
    local content=make("ScrollingFrame",{Position=UDim2.fromOffset(14,14),Size=UDim2.new(1,-28,1,-28),BackgroundTransparency=1,BorderSizePixel=0,ScrollBarThickness=4,CanvasSize=UDim2.new(),AutomaticCanvasSize=Enum.AutomaticSize.Y,ZIndex=202},panel)
    make("UIListLayout",{Padding=UDim.new(0,12),SortOrder=Enum.SortOrder.LayoutOrder},content)
    local function line(value,height,color,size)
        local item=label(content,value,height,color or C.white,Enum.Font.Gotham,size or 14)
        item.ZIndex=203
        return item
    end
    line("FORGE / TOOLS",30,C.accentHover,20)
    line(LANGUAGE=="RU" and "ДОСТУПНО ОБНОВЛЕНИЕ" or "UPDATE AVAILABLE",36,C.white,18)
    line("v"..VERSION.."  →  v"..updateInfo.latest,28,C.accentHover,16)
    line(mandatory and (LANGUAGE=="RU" and "Обязательное обновление" or "Required update") or (LANGUAGE=="RU" and "Обычное обновление" or "Optional update"),27,mandatory and C.yellow or C.muted,13)
    line(LANGUAGE=="RU" and "Что нового:" or "What's new:",25,C.white,15)
    line(updateInfo.notes~="" and updateInfo.notes or (LANGUAGE=="RU" and "Описание изменений не предоставлено." or "Release notes are not available."),math.max(64,math.min(144,math.ceil(#updateInfo.notes/55)*22)),C.muted,13)
    if updateInfo.url~="" then
        line(LANGUAGE=="RU" and "Ссылка для скачивания (выдели и нажми Ctrl+C):" or "Download address (select and press Ctrl+C):",40,C.muted,12)
        local urlBox=make("TextBox",{Size=UDim2.new(1,-2,0,56),Text=updateInfo.url,ClearTextOnFocus=false,TextEditable=true,MultiLine=false,TextWrapped=false,TextXAlignment=Enum.TextXAlignment.Left,Font=Enum.Font.Code,TextSize=12,TextColor3=C.white,BackgroundColor3=C.surface,BorderSizePixel=0,ZIndex=203},content)
        corner(urlBox,5)
        local copy=button(content,LANGUAGE=="RU" and "Выделить ссылку для копирования" or "Select download link",40)
        copy.ZIndex=203
        copy.MouseButton1Click:Connect(function()
            urlBox.Text=updateInfo.url
            urlBox:CaptureFocus()
            task.defer(function()
                if urlBox.Parent then
                    urlBox.CursorPosition=#urlBox.Text+1
                    urlBox.SelectionStart=1
                end
            end)
        end)
    else
        line(LANGUAGE=="RU" and "Ссылка на сборку пока не опубликована. Обновление нельзя установить." or "The release download is not published yet.",60,C.yellow,13)
    end
    if not mandatory then
        local later=button(content,LANGUAGE=="RU" and "Пропустить / Продолжить" or "Skip / Continue",42)
        later.ZIndex=203
        later.MouseButton1Click:Connect(function()
            if not shade.Parent or shade:FindFirstChild("SkipConfirmation") then return end
            local confirmation=make("Frame",{Name="SkipConfirmation",Size=UDim2.fromScale(1,1),BackgroundColor3=C.bg,BorderSizePixel=0,ZIndex=210},shade)
            local confirmPanel=make("Frame",{AnchorPoint=Vector2.new(.5,.5),Position=UDim2.fromScale(.5,.5),Size=UDim2.new(1,-36,0,230),BackgroundColor3=C.panel,BorderSizePixel=0,ZIndex=211},confirmation)
            corner(confirmPanel,12)
            outline(confirmPanel,C.line,1)
            local layout=make("UIListLayout",{Padding=UDim.new(0,12),SortOrder=Enum.SortOrder.LayoutOrder,HorizontalAlignment=Enum.HorizontalAlignment.Center},confirmPanel)
            local prompt=label(confirmPanel,LANGUAGE=="RU" and "Пропустить обновление "..updateInfo.latest.."?" or "Skip update "..updateInfo.latest.."?",46,C.white,Enum.Font.GothamBold,16)
            prompt.ZIndex=212
            local warning=label(confirmPanel,LANGUAGE=="RU" and "Больше не напоминать об этой версии? Скачать её позже можно в Настройки → Обновления." or "Stop reminding about this version? You can download it later in Settings → Updates.",78,C.muted,Enum.Font.Gotham,13)
            warning.TextWrapped=true
            warning.ZIndex=212
            local cancel=button(confirmPanel,LANGUAGE=="RU" and "Отмена" or "Cancel",36)
            cancel.ZIndex=212
            cancel.MouseButton1Click:Connect(function() confirmation:Destroy() end)
            local confirm=button(confirmPanel,LANGUAGE=="RU" and "Да, пропустить" or "Yes, skip",36)
            confirm.ZIndex=212
            confirm.MouseButton1Click:Connect(function()
                if updateInfo.state~="available" or updateInfo.importance~="optional" then confirmation:Destroy() return end
                dismissedUpdateVersion=updateInfo.latest
                local saved,err=pcall(function() plugin:SetSetting(SKIPPED_UPDATE_SETTING,dismissedUpdateVersion) end)
                if not saved then warn("[ForgeTools] Unable to save skipped update: "..tostring(err)) end
                if updateModal==shade then updateModal=nil end
                shade:Destroy()
                if selectedTab=="settings" and draw then task.defer(draw) end
            end)
        end)
    end
end

local function checkForUpdates(force)
    if updateBusy or (not force and os.time()-lastUpdateCheck&lt;UPDATE_CHECK_INTERVAL) then return end
    updateBusy=true
    updateInfo.state="checking"
    task.spawn(function()
        local responseOk,response=pcall(function()
            return HttpService:RequestAsync({
                Url=UPDATE_ENDPOINT.."?version="..VERSION,
                Method="GET",
                Headers={Accept="application/json"}
            })
        end)
        lastUpdateCheck=os.time()
        if not responseOk or not response or not response.Success or type(response.Body)~="string" or #response.Body&gt;8192 then
            updateInfo.state="unavailable"
        else
            local parsed,data=pcall(function() return HttpService:JSONDecode(response.Body) end)
            if parsed and type(data)=="table" and data.schema==1
               and parseVersion(data.latest) and parseVersion(VERSION)
               and (data.importance=="optional" or data.importance=="required" or data.importance=="critical" or data.importance=="none") then
                local newer=parseVersion(data.latest)&gt;parseVersion(VERSION)
                updateInfo.latest=data.latest
                updateInfo.importance=newer and data.importance or "none"
                updateInfo.notes=type(data.notes)=="string" and data.notes:sub(1,240) or ""
                updateInfo.url=safeUpdateUrl(data.download_url)
                updateInfo.state=newer and "available" or "current"
            else
                updateInfo.state="invalid"
            end
        end
        updateBusy=false
        settingsButton.Text=(updateInfo.state=="available") and "⚙ !" or "⚙"
        if widget.Enabled then
            if updateInfo.state=="available" then
                task.defer(showUpdateModal)
            elseif updateModal then
                updateModal:Destroy()
                updateModal=nil
            end
            if selectedTab=="settings" and draw then task.defer(draw) end
        end
    end)
end
checkForUpdates(false)

local function settingsPage(sc)
    sectionHeading(sc,LANGUAGE=="RU" and "НАСТРОЙКИ FORGETOOLS" or "FORGETOOLS SETTINGS")
    label(sc,LANGUAGE=="RU" and "Обновления и персонализация плагина" or "Plugin updates and preferences",34,C.white,Enum.Font.GothamBold,16)
    sectionHeading(sc,LANGUAGE=="RU" and "ОБНОВЛЕНИЯ ПЛАГИНА" or "PLUGIN UPDATES")
    label(sc,LANGUAGE=="RU" and "Установлена: "..VERSION or "Installed: "..VERSION,30,C.muted,Enum.Font.GothamBold,13)
    local updateLabels={
        checking=LANGUAGE=="RU" and "Проверяем обновления..." or "Checking for updates...",
        unavailable=LANGUAGE=="RU" and "Сервер обновлений недоступен. Плагин продолжает работать." or "Update server unavailable. Plugin still works.",
        invalid=LANGUAGE=="RU" and "Не удалось прочитать информацию об обновлении" or "Invalid update metadata",
        current=LANGUAGE=="RU" and "Установлена актуальная версия" or "You have the latest version",
        available=LANGUAGE=="RU" and "Новая версия: "..updateInfo.latest or "New version: "..updateInfo.latest
    }
    label(sc,updateLabels[updateInfo.state] or "—",31,updateInfo.state=="available" and C.yellow or C.muted)
    if updateInfo.state=="available" then
        local importanceLabels={optional=LANGUAGE=="RU" and "Обычное обновление" or "Optional update",
            required=LANGUAGE=="RU" and "Важное обновление" or "Important update",
            critical=LANGUAGE=="RU" and "Критическое обновление безопасности" or "Critical security update"}
        label(sc,importanceLabels[updateInfo.importance] or "—",27,C.yellow)
        if updateInfo.notes~="" then helpNote(sc,updateInfo.notes,76) end
        if updateInfo.url~="" then
            label(sc,LANGUAGE=="RU" and "Страница загрузки новой версии" or "New version download page",31,C.white,Enum.Font.GothamBold,13)
            local settingsUrl=make("TextBox",{Size=UDim2.new(1,-6,0,40),Text=updateInfo.url,ClearTextOnFocus=false,TextEditable=true,MultiLine=false,TextWrapped=false,Font=Enum.Font.Code,TextSize=12,TextColor3=C.white,BackgroundColor3=C.surface,BorderSizePixel=0},sc)
            corner(settingsUrl,5)
            local selectLink=button(sc,LANGUAGE=="RU" and "Выделить ссылку (Ctrl+C)" or "Select link (Ctrl+C)",32)
            selectLink.MouseButton1Click:Connect(function()
                settingsUrl.Text=updateInfo.url
                settingsUrl:CaptureFocus()
                task.defer(function()
                    if settingsUrl.Parent then
                        settingsUrl.CursorPosition=#settingsUrl.Text+1
                        settingsUrl.SelectionStart=1
                    end
                end)
            end)
            if updateInfo.importance=="optional" and dismissedUpdateVersion==updateInfo.latest then
                helpNote(sc,LANGUAGE=="RU" and "Вы пропустили это обновление. Оно остаётся доступным для скачивания здесь." or "You skipped this update. It remains available for download here.",54)
                local remind=button(sc,LANGUAGE=="RU" and "Снова напоминать об обновлении" or "Remind me again",32)
                remind.MouseButton1Click:Connect(function()
                    dismissedUpdateVersion=nil
                    pcall(function() plugin:SetSetting(SKIPPED_UPDATE_SETTING,"") end)
                    draw()
                end)
            end
        else
            helpNote(sc,LANGUAGE=="RU" and "Получите новую сборку .rbxmx у автора ForgeTools. Автоматическая установка отключена." or "Get the new .rbxmx from the ForgeTools author. Automatic installation is disabled.",65)
        end
    end
    local checkUpdate=button(sc,LANGUAGE=="RU" and "Проверить обновления" or "Check for updates",32)
    checkUpdate.MouseButton1Click:Connect(function()
        checkForUpdates(true)
        draw()
    end)
    sectionHeading(sc,LANGUAGE=="RU" and "ПОДЛИННОСТЬ" or "AUTHENTICITY")
    local authLabels={listed=LANGUAGE=="RU" and "Релиз указан на официальном сервере" or "Release listed by official server",
        revoked=LANGUAGE=="RU" and "Релиз отозван" or "Release revoked",
        unavailable=LANGUAGE=="RU" and "Нет связи с сервером проверки" or "Verification server unavailable",
        unverified=LANGUAGE=="RU" and "Не удалось подтвердить релиз" or "Release not verified",
        not_checked=LANGUAGE=="RU" and "Проверка ещё не выполнена" or "Not checked yet"}
    label(sc,authLabels[authenticityState] or "Unknown",30,C.muted)
    local refreshAuth=button(sc,LANGUAGE=="RU" and "Проверить версию" or "Check release",30)
    refreshAuth.MouseButton1Click:Connect(function() checkAuthenticity() end)
    sectionHeading(sc,LANGUAGE=="RU" and "ОФОРМЛЕНИЕ" or "APPEARANCE")
    label(sc,LANGUAGE=="RU" and "Цвет акцента" or "Accent color",25,C.white,Enum.Font.GothamBold,13)
    for _,entry in ipairs({{"forge","Forge Orange"},{"steel","Steel Blue"},{"emerald","Emerald"},{"violet","Violet"},{"crimson","Crimson"}}) do
        local id,caption=entry[1],entry[2]
        local option=button(sc,(preferences.theme==id and "●  " or "○  ")..caption,31)
        if preferences.theme==id then option.BackgroundColor3=C.accentSoft end
        option.MouseButton1Click:Connect(function()
            preferences.theme=id
            savePreferences()
            applyTheme(id)
            draw()
        end)
    end
    label(sc,LANGUAGE=="RU" and "Масштаб панели" or "Panel scale",25,C.white,Enum.Font.GothamBold,13)
    for _,entry in ipairs({{.85,"85%"},{1,"100%"},{1.1,"110%"}}) do
        local value,caption=entry[1],entry[2]
        local option=button(sc,(preferences.scale==value and "●  " or "○  ")..caption,29)
        if preferences.scale==value then option.BackgroundColor3=C.accentSoft end
        option.MouseButton1Click:Connect(function()
            preferences.scale=value
            savePreferences()
            applyWindowScale()
            draw()
        end)
    end
    sectionHeading(sc,LANGUAGE=="RU" and "ЯЗЫК" or "LANGUAGE")
    label(sc,LANGUAGE=="RU" and "Язык интерфейса / Interface language" or "Interface language / Язык интерфейса",23,C.muted)
    for _,entry in ipairs({{"RU","Русский"},{"EN","English"}}) do
        local value,caption=entry[1],entry[2]
        local option=button(sc,(LANGUAGE==value and "●  " or "○  ")..caption,31)
        if LANGUAGE==value then option.BackgroundColor3=C.accentSoft end
        option.MouseButton1Click:Connect(function()
            LANGUAGE=value
            preferences.language=value
            pcall(function() plugin:SetSetting("UIToolsLanguage",value) end)
            savePreferences()
            draw()
        end)
    end
    sectionHeading(sc,LANGUAGE=="RU" and "АНАЛИТИКА" or "ANALYTICS")
    helpNote(sc,LANGUAGE=="RU" and "Анонимная статистика ForgeTools. Выключена по умолчанию. После согласия отправляется ID установки и версия для подсчёта активных установок по версиям. Открытые инструменты и исходный код не передаются. Токен установки выдаётся автоматически сервером." or "Anonymous ForgeTools analytics. Off by default. With consent, sends an installation ID and plugin version to estimate active installations by version. Tool usage and scripts are not sent. The server issues an installation token automatically.",110)
    label(sc,LANGUAGE=="RU" and ("Сервер: "..telemetryStatus) or ("Server: "..telemetryStatus),22,C.muted)
    local toggle=button(sc,analyticsEnabled and (LANGUAGE=="RU" and "Включен" or "On") or (LANGUAGE=="RU" and "Выключен" or "Off"),34)
    toggle.MouseButton1Click:Connect(function()
        analyticsEnabled=not analyticsEnabled
        if not analyticsEnabled then
            table.clear(telemetryQueue)
            -- In-flight HTTP cannot be cancelled; no further requests will be enqueued.
        end
        pcall(function() plugin:SetSetting(ANALYTICS_OPT_IN,analyticsEnabled) end)
        if analyticsEnabled then
            analytics.launches=(tonumber(analytics.launches) or 0)+1
            saveAnalytics()
            enqueueTelemetry("launch", "")
        end
        draw()
    end)
    helpNote(sc,LANGUAGE=="RU" and "Статистика по версиям и уникальным установкам доступна владельцу на сервере. Количество установок не равно точному числу людей." or "Installations and version statistics are available on the server. Installations do not equal verified people.",58)
    sectionHeading(sc,LANGUAGE=="RU" and "ИСПОЛЬЗОВАНИЕ РАЗДЕЛОВ" or "SECTION USAGE")
    local items={}
    local usageLabels={
        ["section:developer:devhome"]="Главная Developer Tools",["section:developer:tool"]="Старый Developer Tool",
        ["section:developer:anticheat"]="FT AntiCheat",["section:developer:inspector"]="Forge Inspector",["section:developer:settings"]="Настройки разработчика",
        ["section:developer:output"]="Журнал Studio",["section:ui:home"]="Главная UITools",
        ["section:ui:responsive"]="Диагностика GUI",["section:ui:gradients"]="Градиенты",
        ["section:ui:textfx"]="Анимация цвета",["section:ui:animations"]="Анимации",
        ["section:ui:editor"]="GUI Editor",["section:settings"]="Настройки ForgeTools"
    }
    for name,count in pairs(analytics.actions) do
        table.insert(items,{name=(LANGUAGE=="RU" and usageLabels[name]) or name,count=tonumber(count) or 0})
    end
    table.sort(items,function(a,b) return a.count&gt;b.count end)
    for index,item in ipairs(items) do
        if index&gt;15 then break end
        label(sc,item.name.." — "..tostring(item.count),25,C.muted,Enum.Font.Gotham,11)
    end
    if #items==0 then label(sc,LANGUAGE=="RU" and "Нет записей" or "No records yet",26,C.muted) end
    local clear=button(sc,LANGUAGE=="RU" and "Очистить локальную статистику" or "Clear local analytics",33)
    clear.MouseButton1Click:Connect(function()
        analytics={launches=0,opens=0,actions={}}
        pcall(function() plugin:SetSetting(ANALYTICS_KEY,analytics) end)
        draw()
    end)
    sectionHeading(sc,LANGUAGE=="RU" and "СБРОС" or "RESET")
    local reset=button(sc,LANGUAGE=="RU" and "Вернуть стандартную тему и масштаб" or "Reset theme and scale",33)
    reset.MouseButton1Click:Connect(function()
        preferences.theme="forge"
        preferences.scale=1
        savePreferences()
        applyTheme("forge")
        applyWindowScale()
        draw()
    end)
end

draw=function()
    local sel=Selection:Get()
    local chosenName=sel[1] and sel[1].Name or (LANGUAGE=="RU" and "ничего" or "none")
    selectionSummary.Text=(LANGUAGE=="RU" and "Выделено: " or "Selected: ")..#sel.."  ·  "..string.sub(chosenName,1,42)
    renderNavigation()
    local sc=makeScroller()
    if selectedTab=="home" then homePage(sc)
    elseif selectedTab=="devhome" then developerHomePage(sc)
    elseif selectedTab=="responsive" then auditPage(sc)
    elseif selectedTab=="gradients" then gradientPage(sc)
    elseif selectedTab=="textfx" then textPage(sc)
    elseif selectedTab=="animations" then animationPage(sc)
    elseif selectedTab=="editor" then editorPage(sc)
    elseif selectedTab=="output" then outputPage(sc)
    elseif selectedTab=="anticheat" then antiCheatPage(sc)
    elseif selectedTab=="inspector" then inspectorLaunchPage(sc)
    elseif selectedTab=="settings" then settingsPage(sc)
    elseif selectedTab=="feedback" then feedbackPage(sc)
    else developerHomePage(sc) end
    if lastAnimatedTab~=selectedTab then
        lastAnimatedTab=selectedTab
        sc.Position=UDim2.fromOffset(0,10)
        TweenService:Create(sc,TweenInfo.new(.32,Enum.EasingStyle.Quart,Enum.EasingDirection.Out),{Position=UDim2.fromOffset(0,0)}):Play()
        local veil=make("Frame",{Name="ForgeTransition",Size=UDim2.fromScale(1,1),BackgroundColor3=C.bg,BackgroundTransparency=.22,BorderSizePixel=0,ZIndex=30},main)
        local fade=TweenService:Create(veil,TweenInfo.new(.28,Enum.EasingStyle.Sine,Enum.EasingDirection.Out),{BackgroundTransparency=1})
        fade:Play()
        fade.Completed:Connect(function() if veil.Parent then veil:Destroy() end end)
    end
end
feedbackButton.MouseButton1Click:Connect(function()
    selectedTab="feedback"
    recordUsage("section:feedback")
    draw()
end)
settingsButton.MouseButton1Click:Connect(function()
    selectedTab="settings"
    recordUsage("section:settings")
    draw()
end)
Selection.SelectionChanged:Connect(function()
    if widget.Enabled then
        if selectedTab=="responsive" or selectedTab=="home" then draw() else
            local sel=Selection:Get()
            selectionSummary.Text=(LANGUAGE=="RU" and "Выделено: " or "Selected: ")..#sel.."  ·  "..(sel[1] and string.sub(sel[1].Name,1,42) or "—")
        end
    end
end)



local NOTICE_VERSION="1"
acceptedNotice=false
local noticeOK,noticeValue=pcall(function() return plugin:GetSetting("ForgeToolsNoticeAccepted") end)
if noticeOK and noticeValue==NOTICE_VERSION then acceptedNotice=true end
local noticeOverlay
local noticeOpen=false
local function openWelcomeNotice()
    if acceptedNotice or noticeOpen then return end
    noticeOpen=true
    noticeOverlay=make("Frame",{Name="ForgeToolsWelcome",Size=UDim2.fromScale(1,1),BackgroundColor3=C.bg,BorderSizePixel=0,ZIndex=100},widget)
    local wrap=make("ScrollingFrame",{Position=UDim2.fromOffset(18,18),Size=UDim2.new(1,-36,1,-36),BackgroundTransparency=1,BorderSizePixel=0,ScrollBarThickness=4,CanvasSize=UDim2.new(),AutomaticCanvasSize=Enum.AutomaticSize.Y,ZIndex=101},noticeOverlay)
    make("UIListLayout",{Padding=UDim.new(0,11),SortOrder=Enum.SortOrder.LayoutOrder},wrap)
    local function textRow(value,height,color,size)
        local l=label(wrap,value,height,color or C.white,Enum.Font.Gotham,size or 13)
        l.ZIndex=102
        return l
    end
    textRow("FORGE  /  TOOLS   v"..VERSION,36,C.white,21)
    textRow("by lukamodric385",20,C.muted,12)
    textRow(LANGUAGE=="RU" and "НАЧАЛО РАБОТЫ" or "GETTING STARTED",31,C.accentHover,17)
    textRow(LANGUAGE=="RU" and "ForgeTools включает инструменты для интерфейсов, серверную диагностику и FT AntiCheat." or "ForgeTools includes UI tools, server diagnostics and FT AntiCheat.",63,C.white,13)
    textRow(LANGUAGE=="RU" and "1. Применяй изменения к собственным проектам или проектам, на которые у тебя есть разрешение. Соблюдай правила Roblox и права авторов." or "1. Use it only on projects you own or are authorized to edit. Follow Roblox rules and creators' rights.",78,C.muted)
    textRow(LANGUAGE=="RU" and "2. Не распространяй авторские компоненты ForgeTools без разрешения правообладателя. Сторонние открытые компоненты (Aegis MIT) регулируются собственными лицензиями." or "2. Do not redistribute proprietary ForgeTools components without permission. Open-source components (Aegis MIT) retain their own licenses.",77,C.muted)
    textRow(LANGUAGE=="RU" and "3. Перед установкой серверных компонентов создай копию проекта. Доступ к журналу FT AntiCheat выдавай только доверенным UserId." or "3. Back up your place before installing server components. Restrict FT AntiCheat audit access to trusted UserIds.",92,C.muted)
    textRow(LANGUAGE=="RU" and "4. Некоторые инструменты экспериментальные. Проверяй результат в Roblox Studio и в Play перед публикацией." or "4. Some features are experimental. Verify results in Roblox Studio and Play before publishing.",75,C.muted)
    textRow(LANGUAGE=="RU" and "Подтверждение сохраняется локально для этого плагина. Полные юридические условия могут быть предоставлены автором отдельно." or "Acceptance is stored locally for this plugin. Full legal license terms may be provided separately by the author.",81,C.muted,12)
    local accept=primaryAction(wrap,LANGUAGE=="RU" and "Принять и продолжить" or "Accept and continue",44)
    accept.ZIndex=103
    accept.MouseButton1Click:Connect(function()
        local ok,err=pcall(function() plugin:SetSetting("ForgeToolsNoticeAccepted",NOTICE_VERSION) end)
        if not ok then
            warn("[ForgeTools] Cannot save notice: "..tostring(err))
            foot.Text=LANGUAGE=="RU" and "Не удалось сохранить согласие" or "Failed to save acceptance"
            return
        end
        acceptedNotice=true
        noticeOpen=false
        if noticeOverlay then noticeOverlay:Destroy() noticeOverlay=nil end
        draw()
        showSystemWelcome()
    end)
    local close=button(wrap,LANGUAGE=="RU" and "Не принимать / закрыть плагин" or "Decline / close plugin",34)
    close.ZIndex=103
    close.MouseButton1Click:Connect(function()
        widget.Enabled=false
        if noticeOverlay then noticeOverlay:Destroy() noticeOverlay=nil end
        noticeOpen=false
    end)
end

iconButton.Click:Connect(function()
    widget.Enabled=not widget.Enabled
    if widget.Enabled then
        if analyticsEnabled then
            analytics.opens=(tonumber(analytics.opens) or 0)+1
            saveAnalytics()
        end
        draw()
        openWelcomeNotice()
        showSystemWelcome()
        checkForUpdates(true)
        task.defer(showUpdateModal)
    else
        local splash=bg:FindFirstChild("ForgeSystemWelcome")
        if splash then splash:Destroy() welcomeVisible=false end
    end
end)
draw()
if widget.Enabled then openWelcomeNotice() showSystemWelcome() end
</ProtectedString>
    </Properties>
    <Item class="Folder" referent="RBX2">
      <Properties>
        <string name="Name">Modules</string>
      </Properties>
      <Item class="ModuleScript" referent="RBX3">
        <Properties>
          <string name="Name">ANIMATION_RUNTIME_SOURCE</string>
          <ProtectedString name="Source">return [====[
local TweenService=game:GetService("TweenService")
local RunService=game:GetService("RunService")
local object=script.Parent
if not object:IsA("GuiObject") then return end
local effect=script:GetAttribute("Effect") or "pulse"
local trigger=script:GetAttribute("Trigger") or "loop"
local activeTween={}
local original={bg=object.BackgroundTransparency,rotation=object.Rotation,pos=object.Position}
local texts=object:IsA("TextLabel") or object:IsA("TextButton") or object:IsA("TextBox")
local images=object:IsA("ImageLabel") or object:IsA("ImageButton")
if texts then original.text=object.TextTransparency end
if images then original.image=object.ImageTransparency end
local scale=object:FindFirstChild("UIToolsMotionScale") or Instance.new("UIScale")
scale.Name="UIToolsMotionScale"
scale.Parent=object
local baseScale=scale.Scale
local stroke
local overlay
local stopFlag=false
local function tw(target,time,props,easing)
    if not target.Parent then return nil end
    local anim=TweenService:Create(target,TweenInfo.new(time,easing or Enum.EasingStyle.Sine,Enum.EasingDirection.InOut),props)
    table.insert(activeTween,anim)
    anim:Play()
    return anim
end
local function clear()
    for _,anim in ipairs(activeTween) do anim:Cancel() end
    table.clear(activeTween)
    if overlay then overlay:Destroy() overlay=nil end
end
local function fadeTo(value,time)
    local props={BackgroundTransparency=value}
    if texts then props.TextTransparency=value end
    if images then props.ImageTransparency=value end
    return tw(object,time,props,Enum.EasingStyle.Quad)
end
local function reset()
    clear()
    object.Rotation=original.rotation
    object.Position=original.pos
    object.BackgroundTransparency=original.bg
    if texts then object.TextTransparency=original.text end
    if images then object.ImageTransparency=original.image end
    scale.Scale=baseScale
    if stroke and stroke.Parent then stroke.Transparency=1 end
end
local function loading(isDots)
    if texts then object.TextTransparency=1 end
    overlay=Instance.new("Frame")
    overlay.Name="UIToolsMotionOverlay"
    overlay.Size=UDim2.fromScale(1,1)
    overlay.BackgroundTransparency=1
    overlay.ZIndex=object.ZIndex+3
    overlay.Parent=object
    local cells={}
    local n=isDots and 3 or 4
    for i=1,n do
        local item=Instance.new("Frame")
        item.Name="UIToolsMotionCell"..i
        item.AnchorPoint=Vector2.new(.5,.5)
        item.Size=UDim2.fromOffset(isDots and 9 or 11,isDots and 9 or 11)
        item.Position=UDim2.fromScale(.5+(i-(n+1)/2)*.11,.5)
        item.BackgroundColor3=Color3.fromRGB(98,180,246)
        item.BackgroundTransparency=.72
        item.BorderSizePixel=0
        item.ZIndex=overlay.ZIndex+1
        item.Parent=overlay
        if isDots then Instance.new("UICorner",item).CornerRadius=UDim.new(1,0) end
        table.insert(cells,item)
    end
    for _=1,2 do
        for _,cell in ipairs(cells) do
            if stopFlag or not cell.Parent then return end
            local jump=isDots and UDim2.fromOffset(0,-7) or UDim2.fromOffset(0,-3)
            local base=cell.Position
            tw(cell,.2,{Position=base+jump,BackgroundTransparency=0})
            task.wait(.12)
            tw(cell,.26,{Position=base,BackgroundTransparency=.72})
        end
    end
end
local function pixel()
    if texts then object.TextTransparency=1 end
    overlay=Instance.new("Frame")
    overlay.Name="UIToolsMotionOverlay"
    overlay.Size=UDim2.fromScale(1,1)
    overlay.BackgroundTransparency=1
    overlay.ClipsDescendants=true
    overlay.ZIndex=object.ZIndex+3
    overlay.Parent=object
    local cells={}
    for y=1,5 do for x=1,8 do
        local cell=Instance.new("Frame")
        cell.Size=UDim2.fromScale(1/8+.01,1/5+.01)
        cell.Position=UDim2.fromScale((x-1)/8,(y-1)/5)
        cell.BackgroundColor3=object.BackgroundColor3:Lerp(Color3.new(1,1,1),.18)
        cell.BorderSizePixel=0
        cell.BackgroundTransparency=1
        cell.Parent=overlay
        table.insert(cells,{cell=cell,delay=(x+y)*.025})
    end end
    for _,data in ipairs(cells) do
        task.delay(data.delay,function()
            if data.cell.Parent and not stopFlag then tw(data.cell,.18,{BackgroundTransparency=.08}) end
        end)
    end
    task.wait(.38)
    for _,data in ipairs(cells) do
        task.delay(data.delay,function()
            if data.cell.Parent and not stopFlag then tw(data.cell,.2,{BackgroundTransparency=1}) end
        end)
    end
    task.wait(.65)
end
local function once()
    reset()
    if effect=="rotate" then
        local anim=tw(object,2.4,{Rotation=original.rotation+360},Enum.EasingStyle.Linear)
        if anim then anim.Completed:Wait() end
        object.Rotation=original.rotation
    elseif effect=="fade" then
        object.BackgroundTransparency=1
        if texts then object.TextTransparency=1 end
        if images then object.ImageTransparency=1 end
        fadeTo(original.bg,.75)
        task.wait(.75)
        if texts then object.TextTransparency=original.text end
        if images then object.ImageTransparency=original.image end
    elseif effect=="slide" then
        scale.Scale=baseScale*.72
        object.BackgroundTransparency=1
        if texts then object.TextTransparency=1 end
        if images then object.ImageTransparency=1 end
        tw(scale,.64,{Scale=baseScale},Enum.EasingStyle.Quint)
        fadeTo(original.bg,.64)
        task.wait(.65)
        if texts then object.TextTransparency=original.text end
        if images then object.ImageTransparency=original.image end
    elseif effect=="pop" or effect=="bounce" or effect=="slideleft" then
        scale.Scale=baseScale*(effect=="bounce" and .78 or .88)
        tw(scale,.62,{Scale=baseScale},effect=="bounce" and Enum.EasingStyle.Back or Enum.EasingStyle.Quart)
        task.wait(.65)
    elseif effect=="loading" or effect=="dots" then
        loading(effect=="dots")
    elseif effect=="pixelwipe" then
        pixel()
    elseif effect=="softglow" then
        stroke=object:FindFirstChild("UIToolsSoftStroke") or Instance.new("UIStroke")
        stroke.Name="UIToolsSoftStroke"
        stroke.ApplyStrokeMode=Enum.ApplyStrokeMode.Border
        stroke.Color=Color3.fromRGB(140,197,250)
        stroke.Thickness=2
        stroke.Transparency=1
        stroke.Parent=object
        tw(stroke,.65,{Transparency=.15})
        task.wait(.7)
    elseif effect=="shake" then
        for _,a in ipairs({-5,5,-4,3,0}) do
            local anim=tw(object,.075,{Rotation=original.rotation+a})
            if anim then anim.Completed:Wait() end
        end
    elseif effect=="sway" then
        tw(object,.6,{Rotation=original.rotation+5})
        task.wait(.65)
        tw(object,.6,{Rotation=original.rotation-5})
        task.wait(.65)
    elseif effect=="float" then
        tw(object,.7,{Position=original.pos+UDim2.fromOffset(0,-8)})
        task.wait(.7)
    elseif effect=="press" then
        tw(scale,.13,{Scale=baseScale*.94})
        task.wait(.15)
        tw(scale,.25,{Scale=baseScale})
        task.wait(.26)
    else
        tw(scale,.68,{Scale=baseScale*1.06})
        task.wait(.7)
    end
end
local busy=false
local function run()
    if busy or not script.Parent then return end
    busy=true
    once()
    busy=false
end
if trigger=="hover" then
    object.MouseEnter:Connect(run)
    object.MouseLeave:Connect(reset)
elseif trigger=="click" then
    if object:IsA("GuiButton") then object.MouseButton1Click:Connect(run)
    else
        object.Active=true
        object.InputBegan:Connect(function(input) if input.UserInputType==Enum.UserInputType.MouseButton1 then run() end end)
    end
else
    if effect=="rotate" then
        
        local tween=TweenService:Create(object,TweenInfo.new(2.4,Enum.EasingStyle.Linear,Enum.EasingDirection.InOut,-1),{Rotation=original.rotation+360})
        tween:Play()
        script.Destroying:Connect(function() tween:Cancel() object.Rotation=original.rotation end)
    elseif effect=="pulse" or effect=="hover" then
        local tween=TweenService:Create(scale,TweenInfo.new(.85,Enum.EasingStyle.Sine,Enum.EasingDirection.InOut,-1,true),{Scale=baseScale*1.06})
        tween:Play()
        script.Destroying:Connect(function() tween:Cancel() scale.Scale=baseScale end)
    else
        task.spawn(function()
            while script.Parent and not stopFlag do
                once()
                
                if effect=="fade" or effect=="slide" or effect=="pixelwipe" then task.wait(.22) else task.wait(.06) end
            end
        end)
    end
end
script.Destroying:Connect(function() stopFlag=true reset() end)
]====]</ProtectedString>
        </Properties>
      </Item>
      <Item class="ModuleScript" referent="RBX4">
        <Properties>
          <string name="Name">GRADIENT_ANIM_SOURCE</string>
          <ProtectedString name="Source">return [====[
local RunService=game:GetService("RunService")
local parent=script.Parent
local name=script:GetAttribute("GradientName")
local gradient=(name and parent:FindFirstChild(name)) or parent:FindFirstChild("UIToolsGradient") or parent:FindFirstChild("UIToolsTextGradient") or parent:FindFirstChildOfClass("UIGradient")
if not gradient then return end
local mode=script:GetAttribute("Mode") or "slide"
local speed=tonumber(script:GetAttribute("Speed")) or .5
local originalColor=gradient.Color
local originalRotation=gradient.Rotation
local originalOffset=gradient.Offset
local phase=0
local con
local pi=math.pi
local rainbowCache={}
if mode=="rainbow" then
    for frame=0,47 do
        local points={}
        for i=0,12 do
            points[#points+1]=ColorSequenceKeypoint.new(i/12,Color3.fromHSV((i/12+frame/48)%1,.8,1))
        end
        rainbowCache[frame+1]=ColorSequence.new(points)
    end
end
local function update(t)
    if mode=="rainbow" then
        gradient.Color=rainbowCache[math.floor(t*48)%48+1]
    elseif mode=="rotate" then
        
        gradient.Rotation=originalRotation + 12*math.sin(t*2*pi)
        gradient.Offset=originalOffset + Vector2.new(.46*math.sin(t*2*pi),0)
    elseif mode=="vertical" then
        gradient.Offset=originalOffset+Vector2.new(0,.55*math.sin(t*2*pi))
    elseif mode=="diagonal" then
        gradient.Offset=originalOffset+Vector2.new(.4*math.sin(t*2*pi),.4*math.sin(t*2*pi))
    elseif mode=="sweep" then
        
        gradient.Offset=originalOffset+Vector2.new(.72*math.sin(t*2*pi),0)
    else
        gradient.Offset=originalOffset+Vector2.new(.55*math.sin(t*2*pi),0)
    end
end
local accumulator=0
con=RunService.Heartbeat:Connect(function(dt)
    if not script.Parent or not gradient.Parent then con:Disconnect() return end
    accumulator+=math.min(dt,0.2)
    if accumulator&lt;1/30 then return end
    local elapsed=accumulator
    accumulator=0
    phase=(phase+elapsed*speed)%1
    update(phase)
end)
script.Destroying:Connect(function()
    if con then con:Disconnect() end
    if gradient.Parent then
        gradient.Offset=originalOffset
        gradient.Rotation=originalRotation
        gradient.Color=originalColor
    end
end)
]====]</ProtectedString>
        </Properties>
      </Item>
      <Item class="ModuleScript" referent="RBX6">
        <Properties>
          <string name="Name">GUI_CANVAS</string>
          <ProtectedString name="Source">

local Selection = game:GetService("Selection")
local UIS = game:GetService("UserInputService")
local History = game:GetService("ChangeHistoryService")
local TweenService = game:GetService("TweenService")
local RunService = game:GetService("RunService")
local HttpService = game:GetService("HttpService")
local M = {}
local Viewport = require(script.Parent:WaitForChild("FT_EDITOR_VIEWPORT"))
local Icons = require(script.Parent:WaitForChild("FT_EDITOR_ICONS"))
local Geometry = require(script.Parent:WaitForChild("FT_EDITOR_GEOMETRY"))
local Style = require(script.Parent:WaitForChild("FT_EDITOR_STYLE"))
local TOOL_ICON_IDS = Icons.ids
local iconAsset = Icons.asset
local normalizeImage = Style.normalizeImage
local dock, canvas, scene, layerList, properties, status, footerInfo, workScroll
local viewportController
local pluginMouse
local cursorIcons={default="",sizeNWSE="rbxasset://SystemCursors/SizeNWSE",sizeNESW="rbxasset://SystemCursors/SizeNESW",sizeWE="rbxasset://SystemCursors/SizeWE",sizeNS="rbxasset://SystemCursors/SizeNS",move="rbxasset://SystemCursors/SizeAll",cross="rbxasset://SystemCursors/Cross"}
local currentCursorIcon=""
local function setCursorIcon(icon)
 local target=icon or cursorIcons.default
 if currentCursorIcon==target then return end
 currentCursorIcon=target
 if pluginMouse then pcall(function() pluginMouse.Icon=target end) end
end
local currentRoot, nodes, selectedId, selectedIds, nextId, checkpoints, redoStack, baseline
local viewportSize = Vector2.new(1920, 1080)
local zoom = 0.5
local zoomScale, zoomReadout, viewportReadout
-- Central canvas is a clipped Frame, not a ScrollingFrame: no dead scrollbars.
local emptyHint, rightPanel, middlePanel
local canvasSelectionInput
local popupIsBlocking=function() return false end
local popupConsumePress=function() return false end
local refreshGuiLinkState=function() end
local function formatPercent() return tostring(math.floor(zoom*100+0.5)).."%" end
local proxyById = {}
local overlayById = {}
local decoratedSelection = {}
local layerSelectButtons={}
local layerSelectionTweens={}
local layerAnimationGeneration=0
local updateLayerSelection
local overlayRefreshGeneration=0
local refreshOverlay
local updateSelectionDecorations
local overlayUpdateQueue={}
local overlayUpdatePending=false
local previewGeneration=0
-- Batch geometry reads/selection frames to one scheduled update per input frame.
local function queueOverlayUpdate(id)
 overlayUpdateQueue[id]=true
 if overlayUpdatePending then return end
 overlayUpdatePending=true
 local generation=previewGeneration
 local queued=overlayUpdateQueue
 task.defer(function()
  if generation~=previewGeneration or queued~=overlayUpdateQueue then return end
  -- Always unlock the queue, including when Studio temporarily removes the preview.
  overlayUpdatePending=false
  overlayUpdateQueue={}
  if not scene or not scene.Parent then return end
  for queuedId in pairs(queued) do
   if refreshOverlay then refreshOverlay(queuedId) end
  end
 end)
end
-- Selection affordances are outside user GUI hierarchy to avoid UIListLayout pollution.
refreshOverlay=function(id)
 local overlay,proxy=overlayById[id],proxyById[id]
 if not scene or not scene.Parent or not overlay or not overlay.Parent or not proxy or not proxy.Parent then return end
 local factor=math.max(zoom,0.1)
 local position=(proxy.AbsolutePosition-scene.AbsolutePosition)/factor
 local size=proxy.AbsoluteSize/factor
 -- Studio can report zero-sized PluginGui geometry while another window has focus.
 -- Do not overwrite the last valid selection bounds in that state.
 if size.X&lt;1 or size.Y&lt;1 then return end
 overlay.Position=UDim2.fromOffset(math.floor(position.X+0.5),math.floor(position.Y+0.5))
 overlay.Size=UDim2.fromOffset(math.max(1,math.floor(size.X+0.5)),math.max(1,math.floor(size.Y+0.5)))
 -- AbsoluteSize is already in on-screen pixels; the handles must adapt to the
 -- on-screen target, not the document-space rectangle.
 local screenW,screenH=proxy.AbsoluteSize.X,proxy.AbsoluteSize.Y
 for _,child in ipairs(overlay:GetChildren()) do
  if child.Name=="FT_SelectionDimensions" then
   child.Visible=screenW&gt;=105 and screenH&gt;=62
   local w,h=math.floor(size.X+0.5),math.floor(size.Y+0.5)
   local caption=tostring(w).." × "..tostring(h)
   if child.Text~=caption then child.Text=caption end
  elseif child.Name:sub(1,10)=="FT_Resize_" then
   local side=child.Name=="FT_Resize_n" or child.Name=="FT_Resize_s" or child.Name=="FT_Resize_e" or child.Name=="FT_Resize_w"
   child.Visible=(not side) or (screenW&gt;=72 and screenH&gt;=54)
  end
 end
end
-- FT-EDITOR-001: disclosure state belongs to the layer tree, not the Studio hierarchy.
local collapsedLayers = {}
local connections = {}
local moving = false
local cancelActiveGesture
local activeGestureInput
local activeGestureMode
local lastCanvasPressInput
local activeTool = "Select"
local dirty = false
local originalRefs = {}
local originalParents = {}
local context
local savedDraftKey = "ForgeToolsGUIEditorDraftV1"
local saveGeneration = 0
local saveDraft, clearDraft, restoreDraft, promptDraft
local recoveryBanner
local recoveryDismissed=false
local function showRecoveryBanner(visible)
 if recoveryBanner and recoveryBanner.Parent then recoveryBanner.Visible=visible and true or false end
end
local changed
local beginCanvasDraw
local openEditorContextForPoint
-- Single optional input entry point, shared by the canvas and all preview descendants.
local wheelHandler
local panInputHandler
-- FT shell theme tokens. Only editor chrome; never apply to user GUI or its preview.
local ink = {
 bg=Color3.fromRGB(20,22,24), pane=Color3.fromRGB(27,31,35), card=Color3.fromRGB(35,40,46),
 blue=Color3.fromRGB(217,119,6), text=Color3.fromRGB(243,244,246), muted=Color3.fromRGB(177,186,197),
 red=Color3.fromRGB(201,90,90), green=Color3.fromRGB(63,164,106), border=Color3.fromRGB(49,56,65)
}
local EDITOR_THEME_KEY="ForgeToolsEditorShellThemeV1"
local editorThemePresets={
 forge={blue=Color3.fromRGB(217,119,6),bg=Color3.fromRGB(20,22,24),pane=Color3.fromRGB(27,31,35),card=Color3.fromRGB(35,40,46),border=Color3.fromRGB(49,56,65)},
 steel={blue=Color3.fromRGB(52,143,224),bg=Color3.fromRGB(19,23,29),pane=Color3.fromRGB(28,35,45),card=Color3.fromRGB(38,47,59),border=Color3.fromRGB(57,70,86)},
 emerald={blue=Color3.fromRGB(34,164,117),bg=Color3.fromRGB(18,25,22),pane=Color3.fromRGB(26,36,32),card=Color3.fromRGB(35,47,41),border=Color3.fromRGB(53,70,61)},
 violet={blue=Color3.fromRGB(145,103,213),bg=Color3.fromRGB(24,21,29),pane=Color3.fromRGB(34,29,41),card=Color3.fromRGB(46,39,55),border=Color3.fromRGB(69,59,80)}
}
-- Custom editor shell colors are persisted as hex, never applied to project objects.
local EDITOR_CUSTOM_KEY="ForgeToolsEditorCustomShellV1"
local editorCustom=nil
local function fromHex(hex)
 if type(hex)~="string" or not hex:match("^#%x%x%x%x%x%x$") then return nil end
 return Color3.fromHex(hex)
end
local function loadCustomShell(plugin)
 local ok,data=pcall(function() return plugin:GetSetting(EDITOR_CUSTOM_KEY) end)
 if not ok or type(data)~="table" then return nil end
 local result={}
 for _,key in ipairs({"blue","bg","pane","card","border"}) do
  result[key]=fromHex(data[key])
  if not result[key] then return nil end
 end
 return result
end
local editorThemeName="forge"
local editorShellApply=function() end
local function setEditorShellTheme(name, persist)
 local p=name=="custom" and editorCustom or editorThemePresets[name]
 if not p then return end
 local before={}
 for k in pairs(p) do before[k]=ink[k] end
 for k,v in pairs(p) do ink[k]=v end
 editorThemeName=name
 editorShellApply(before)
 if persist and context and context.plugin then
  pcall(function() context.plugin:SetSetting(EDITOR_THEME_KEY,name) end)
 end
end
local function tr(ru,en) return en end
local function addConn(conn) table.insert(connections,conn) return conn end
-- In Studio edit mode the global mouse coordinates may differ from PluginGui coordinates.
-- Prefer the widget-local pointer when it lies inside our actual viewport.
local function mousePointer()
 local global=UIS:GetMouseLocation()
 if dock and canvas and canvas.Parent and workScroll and workScroll.Parent then
  local ok,relative=pcall(function() return dock:GetRelativeMousePosition() end)
  if ok and typeof(relative)=="Vector2" then
   local candidate=canvas.AbsolutePosition+relative
   local position,size=workScroll.AbsolutePosition,workScroll.AbsoluteSize
   if candidate.X&gt;=position.X and candidate.Y&gt;=position.Y and candidate.X&lt;position.X+size.X and candidate.Y&lt;position.Y+size.Y then
    return candidate
   end
  end
 end
 return global
end
local activeGestureMove
local activeGestureUp
local canvasMouseMotion
local panMouseMotion
local function disconnect()
 for _,conn in ipairs(connections) do conn:Disconnect() end
 table.clear(connections)
 viewportController=nil
 wheelHandler=nil
 panInputHandler=nil
 setCursorIcon(cursorIcons.default)
end
local function make(class,props,parent)
 local obj=Instance.new(class)
 for k,v in pairs(props or {}) do obj[k]=v end
 -- Bind colors to semantic roles ONCE at creation, never infer them from later RGB.
 -- This registration is only used on editor chrome, never on imported GUI objects.
 if props then
  for _,property in ipairs({"BackgroundColor3","TextColor3","ImageColor3","BorderColor3","Color"}) do
   local color=props[property]
   if typeof(color)=="Color3" then
    for _,role in ipairs({"blue","bg","pane","card","border","text","muted","red","green"}) do
     if ink[role] == color then
      obj:SetAttribute("FTShellRole_"..property,role)
      break
     end
    end
   end
  end
 end
 obj.Parent=parent
 return obj
end
local function clear(parent)
 if parent then
  for _,child in ipairs(parent:GetChildren()) do child:Destroy() end
 end
end
local function label(parent,s,size,muted)
 return make("TextLabel",{Text=s,Font=Enum.Font.Gotham,TextSize=size or 13,TextColor3=muted and ink.muted or ink.text,TextXAlignment=Enum.TextXAlignment.Left,BackgroundTransparency=1,Size=UDim2.new(1,-8,0,26),TextTruncate=Enum.TextTruncate.AtEnd},parent)
end
local function btn(parent,title,callback,w,color)
 local b=make("TextButton",{Text=title,Font=Enum.Font.GothamMedium,TextSize=12,TextColor3=ink.text,
  BackgroundColor3=color or ink.card,BorderSizePixel=0,Size=UDim2.fromOffset(w or 91,29),AutoButtonColor=true},parent)
 make("UICorner",{CornerRadius=UDim.new(0,6)},b)
 -- ForgeTools motion: original animation implementation; cancel stale tweens on rapid input.
 b.AutoButtonColor=false
 local baseColor=b.BackgroundColor3
 local function currentBaseColor()
  local selected=b:GetAttribute("SelectedBaseColor")
  if typeof(selected)=="Color3" then return selected end
  local role=b:GetAttribute("FTShellRole_BackgroundColor3")
  if role and ink[role] then return ink[role] end
  return baseColor
 end
 local scale=make("UIScale",{Name="FTEditorMotion",Scale=1},b)
 local scaleTween,colorTween
 local hovered=false
 local function motion(targetSize,targetColor,duration)
  if not b.Parent then return end
  if scaleTween then scaleTween:Cancel() end
  if colorTween then colorTween:Cancel() end
  local info=TweenInfo.new(duration or .17,Enum.EasingStyle.Quad,Enum.EasingDirection.Out)
  scaleTween=TweenService:Create(scale,info,{Scale=targetSize})
  colorTween=TweenService:Create(b,info,{BackgroundColor3=targetColor})
  scaleTween:Play()
  colorTween:Play()
 end
 b.MouseEnter:Connect(function()
  hovered=true
  motion(1.025,currentBaseColor():Lerp(Color3.new(1,1,1),.085),.16)
 end)
 b.MouseLeave:Connect(function()
  hovered=false
  motion(1,currentBaseColor(),.19)
 end)
 b.MouseButton1Down:Connect(function()
  motion(.955,currentBaseColor():Lerp(Color3.new(0,0,0),.14),.085)
 end)
 b.MouseButton1Up:Connect(function()
  local base=currentBaseColor()
  motion(hovered and 1.025 or 1,hovered and base:Lerp(Color3.new(1,1,1),.085) or base,.22)
 end)
 b.MouseButton1Click:Connect(callback)
 return b
end
local function row(parent,height)
 local f=make("Frame",{Size=UDim2.new(1,-2,0,height or 32),BackgroundTransparency=1},parent)
 make("UIListLayout",{FillDirection=Enum.FillDirection.Horizontal,Padding=UDim.new(0,5),VerticalAlignment=Enum.VerticalAlignment.Center},f)
 return f
end
local function stack(parent,padding)
 make("UIListLayout",{Padding=UDim.new(0,padding or 5),SortOrder=Enum.SortOrder.LayoutOrder},parent)
end
local function notice(msg)
 if status and status.Parent then status.Text=msg end
end
local function cursorForHandle(handleName)
 if handleName=="nw" or handleName=="se" then return cursorIcons.sizeNWSE end
 if handleName=="ne" or handleName=="sw" then return cursorIcons.sizeNESW end
 if handleName=="n" or handleName=="s" then return cursorIcons.sizeNS end
 if handleName=="e" or handleName=="w" then return cursorIcons.sizeWE end
 return cursorIcons.default
end
local copyKeys={"Name","Position","Size","AnchorPoint","Rotation","BackgroundColor3","BackgroundTransparency","BorderSizePixel","Visible","ZIndex","ClipsDescendants","LayoutOrder","Text","TextSize","TextColor3","TextTransparency","TextWrapped","TextXAlignment","TextYAlignment","Font","Image","ImageColor3","ImageTransparency","ScaleType","PlaceholderText","TextScaled","RichText","FontFace","TextTruncate","TextStrokeTransparency","TextStrokeColor3","LineHeight","AutomaticSize","ImageRectOffset","ImageRectSize","ResampleMode","CanvasSize","AutomaticCanvasSize","ScrollBarThickness","ScrollingDirection","GroupTransparency"}
local textClasses={TextLabel=true,TextButton=true,TextBox=true}
local imageClasses={ImageLabel=true,ImageButton=true}
local allowed={Frame=true,TextLabel=true,TextButton=true,TextBox=true,ImageLabel=true,ImageButton=true,ScrollingFrame=true,CanvasGroup=true,ViewportFrame=true}
-- Class-aware property projection: never write Text/Image/Canvas properties to Frame.
local function supportedProps(class,props)
 local test=Instance.new(class)
 local filtered={}
 for key,value in pairs(props) do
  if key=="CornerRadius" or key=="StrokeColor" or key=="StrokeThickness" then
   filtered[key]=value
  else
   local ok=pcall(function() local _=test[key] end)
   if ok then filtered[key]=value end
  end
 end
 test:Destroy()
 return filtered
end
local function readProps(obj)
 local props={}
 for _,key in ipairs(copyKeys) do
  local ok,value=pcall(function() return obj[key] end)
  if ok then props[key]=value end
 end
 local corner=obj:FindFirstChildOfClass("UICorner")
 if corner then props.CornerRadius=corner.CornerRadius end
 local stroke=obj:FindFirstChildOfClass("UIStroke")
 if stroke then props.StrokeColor=stroke.Color props.StrokeThickness=stroke.Thickness end
 return props
end
local function propsCopy(props)
 local result={}
 for k,v in pairs(props) do result[k]=v end
 return result
end
local function freshNodes(src)
 local result={}
 for id,item in pairs(src) do
  result[id]={id=id,parent=item.parent,original=item.original,componentSourceId=item.componentSourceId,class=item.class,props=propsCopy(item.props)}
 end
 return result
end
local function snap()
 return {nodes=freshNodes(nodes),selectedId=selectedId,selectedIds=propsCopy(selectedIds or {}),nextId=nextId}
end
local function restore(shot)
 nodes=freshNodes(shot.nodes)
 selectedId=shot.selectedId
 selectedIds=propsCopy(shot.selectedIds or {})
 nextId=shot.nextId
end
local function keyId(obj)
 nextId+=1
 return nextId
end
local function findRoot()
 local chosen=Selection:Get()[1]
 if not chosen then return nil end
 if chosen:IsA("ScreenGui") then return chosen end
 if not chosen:IsA("GuiObject") then return nil end
 local obj=chosen
 while obj and not obj:IsA("ScreenGui") do obj=obj.Parent end
 -- A loose GuiObject is not a document root. Importing it as a ScreenGui
 -- hides the object itself because renderNode only draws root children.
 return obj and obj:IsA("ScreenGui") and obj or nil
end
local function importTree(root)
 currentRoot=root
 refreshGuiLinkState()
 collapsedLayers={}
 nodes={}
 selectedId=nil
 selectedIds={}
 nextId=0
 local function collect(obj,parentId,depth)
  if depth&gt;12 then return end
  local id=keyId(obj)
  nodes[id]={id=id,original=obj,class=obj.ClassName,parent=parentId,props=readProps(obj)}
  if obj:IsA("ScreenGui") then selectedId=id end
  local children=obj:GetChildren()
  table.sort(children,function(a,b)
   if a:IsA("GuiObject") and b:IsA("GuiObject") then
    if a.LayoutOrder==b.LayoutOrder then return a.Name&lt;b.Name end
    return a.LayoutOrder&lt;b.LayoutOrder
   end
   return a.Name&lt;b.Name
  end)
  for _,child in ipairs(children) do
   if child:IsA("GuiObject") then collect(child,id,depth+1) end
  end
  return id
 end
 local rootId=collect(root,nil,0)
 local studioSelected=Selection:Get()[1]
 local focusId=rootId
 if studioSelected and studioSelected~=root then
  for id,entry in pairs(nodes) do
   if entry.original==studioSelected then focusId=id break end
  end
 end
 selectedId=focusId
 selectedIds={[focusId]=true}
 baseline={}
 for id,item in pairs(nodes) do baseline[id]=propsCopy(item.props) end
 dirty=false
 checkpoints={}
 redoStack={}
end
local function equalValue(a,b)
 if typeof(a)~=typeof(b) then return false end
 return a==b
end
local function sameProps(a,b)
 for key,value in pairs(a) do if not equalValue(value,b[key]) then return false end end
 for key,value in pairs(b) do if not equalValue(value,a[key]) then return false end end
 return true
end
local function isDirty()
 if not baseline then return false end
 for id,item in pairs(nodes) do
  local old=baseline[id]
  if not old or not sameProps(item.props,old) then return true end
 end
 for id in pairs(baseline) do if not nodes[id] then return true end end
 return false
end
local repaint, renderInspector, renderLayers, fitCanvas, setZoom, setViewport
-- Persistent JSON draft. This stores only visual GUI properties locally via Plugin Settings;
-- no Lua source, DataStore values, network traffic, or external telemetry.
local function encodeValue(value)
 local kind=typeof(value)
 if kind=="number" or kind=="string" or kind=="boolean" then return value end
 if kind=="Color3" then return {t="Color3",v={value.R,value.G,value.B}} end
 if kind=="Vector2" then return {t="Vector2",v={value.X,value.Y}} end
 if kind=="UDim" then return {t="UDim",v={value.Scale,value.Offset}} end
 if kind=="UDim2" then return {t="UDim2",v={value.X.Scale,value.X.Offset,value.Y.Scale,value.Y.Offset}} end
 if kind=="EnumItem" then return {t="EnumItem",category=tostring(value.EnumType),name=value.Name} end
 return nil
end
local function decodeValue(value)
 if type(value)~="table" then return value end
 if value.t=="Color3" and type(value.v)=="table" then return Color3.new(value.v[1],value.v[2],value.v[3]) end
 if value.t=="Vector2" and type(value.v)=="table" then return Vector2.new(value.v[1],value.v[2]) end
 if value.t=="UDim" and type(value.v)=="table" then return UDim.new(value.v[1],value.v[2]) end
 if value.t=="UDim2" and type(value.v)=="table" then return UDim2.new(value.v[1],value.v[2],value.v[3],value.v[4]) end
 if value.t=="EnumItem" and type(value.category)=="string" then
  local group=value.category:match("^Enum%.([%w_]+)$")
  if group and Enum[group] then
   local ok,item=pcall(function() return Enum[group][value.name] end)
   if ok then return item end
  end
 end
 return nil
end
local function encodeProps(props)
 local result={}
 for key,value in pairs(props) do
  local encoded=encodeValue(value)
  if encoded~=nil then result[key]=encoded end
 end
 return result
end
local function decodeProps(props)
 if type(props)~="table" then return {} end
 local result={}
 for key,value in pairs(props) do
  local decoded=decodeValue(value)
  if decoded~=nil then result[key]=decoded end
 end
 return result
end
local function draftIdentity()
 if not currentRoot or not currentRoot.Parent then return nil end
 return tostring(game.PlaceId)..":"..currentRoot:GetFullName()
end
-- A previous draft may exist before any ScreenGui is selected in Explorer.
-- Match the saved source by its exact path within THIS place; never select another place's GUI.
local function savedRootFromData(data)
 if type(data)~="table" or type(data.identity)~="string" then return nil end
 local placePrefix=tostring(game.PlaceId)..":"
 if data.identity:sub(1,#placePrefix)~=placePrefix then return nil end
 local starterGui=game:GetService("StarterGui")
 for _,candidate in ipairs(starterGui:GetDescendants()) do
  if candidate:IsA("ScreenGui") and placePrefix..candidate:GetFullName()==data.identity then
   return candidate
  end
 end
 return nil
end
local function readSavedDraft()
 if not context or not context.plugin then return nil,nil end
 local ok,json=pcall(function() return context.plugin:GetSetting(savedDraftKey) end)
 if not ok or type(json)~="string" then return nil,nil end
 local valid,data=pcall(function() return HttpService:JSONDecode(json) end)
 if not valid or type(data)~="table" or data.version~=1 then return nil,nil end
 return data,savedRootFromData(data)
end
clearDraft=function()
 showRecoveryBanner(false)
 saveGeneration+=1
 if context and context.plugin then
  pcall(function() context.plugin:SetSetting(savedDraftKey,nil) end)
 end
end
saveDraft=function()
 if not context or not context.plugin or not nodes or not baseline or not dirty then return end
 local identity=draftIdentity()
 if not identity then return end
 local snapshot={version=1,identity=identity,nextId=nextId,selectedId=selectedId,selectedIds={},base={},nodes={}}
 for id,enabled in pairs(selectedIds or {}) do if enabled then snapshot.selectedIds[tostring(id)]=true end end
 for id,props in pairs(baseline) do snapshot.base[tostring(id)]=encodeProps(props) end
 for id,n in pairs(nodes) do
  snapshot.nodes[#snapshot.nodes+1]={id=id,parent=n.parent,class=n.class,original=n.original~=nil,componentSourceId=n.componentSourceId,props=encodeProps(n.props)}
 end
 if #snapshot.nodes&gt;500 then notice(tr("Для JSON-сохранения поддерживается до 500 элементов","JSON backup supports up to 500 elements")) return end
 local ok,json=pcall(function() return HttpService:JSONEncode(snapshot) end)
 if not ok or #json&gt;500000 then
  notice(tr("Черновик слишком большой для автосохранения","Draft exceeds autosave size limit"))
  return
 end
 local success=pcall(function() context.plugin:SetSetting(savedDraftKey,json) end)
 if not success then notice(tr("Не удалось записать черновик в настройки плагина","Could not save draft to plugin settings")) end
end
local function scheduleSave()
 if not dirty then clearDraft() return end
 saveGeneration+=1
 local generation=saveGeneration
 task.delay(1,function()
  if generation==saveGeneration then saveDraft() end
 end)
end
restoreDraft=function()
 -- Dismiss immediately; validation must never leave a blocking banner behind.
 recoveryDismissed=true
 showRecoveryBanner(false)
 if not context or not context.plugin or not currentRoot or not nodes then return end
 if dirty then notice(tr("Перед восстановлением сбрось текущий черновик","Discard current draft before restoring")) return end
 local ok,json=pcall(function() return context.plugin:GetSetting(savedDraftKey) end)
 if not ok or type(json)~="string" then notice(tr("Сохранённого черновика нет","No saved draft")) return end
 local valid,data=pcall(function() return HttpService:JSONDecode(json) end)
 if not valid or type(data)~="table" or data.version~=1 or data.identity~=draftIdentity() then
  notice(tr("Черновик относится к другому GUI или проекту","Draft belongs to another GUI or place")) return
 end
 if type(data.base)~="table" or type(data.nodes)~="table" or #data.nodes&gt;500 then return end
 -- Refuse to restore if the source GUI has changed since the autosave.
 for id,props in pairs(baseline) do
  local stored=data.base[tostring(id)]
  if not stored or not sameProps(props,decodeProps(stored)) then
   notice(tr("Исходный GUI изменился — восстановление отменено","Source GUI changed; recovery cancelled")) return
  end
 end
 for id in pairs(data.base) do if not baseline[tonumber(id)] then
  notice(tr("Структура GUI изменилась — восстановление отменено","GUI hierarchy changed; recovery cancelled")) return
 end end
 local restored={}
 for _,record in ipairs(data.nodes) do
  if type(record)~="table" or type(record.id)~="number" or restored[record.id] or type(record.class)~="string" then return end
  local original=record.original and nodes[record.id] or nil
  if record.original and (not original or original.class~=record.class) then
   notice(tr("Слои изменились — восстановление отменено","Layers changed; recovery cancelled")) return
  end
  if not record.original and not allowed[record.class] then return end
  local sourceId=record.componentSourceId
  if sourceId~=nil then
   if type(sourceId)~="number" or not baseline[sourceId] or not nodes[sourceId] or not nodes[sourceId].original then
    notice(tr("Источник компонентов дубликата недоступен — восстановление отменено","Duplicate component source missing; recovery cancelled"))
    return
   end
  end
  restored[record.id]={id=record.id,parent=record.parent,original=original and original.original or nil,componentSourceId=sourceId,class=record.class,props=decodeProps(record.props)}
 end
 for id,record in pairs(restored) do
  if record.parent~=nil and not restored[record.parent] then return end
 end
 nodes=restored
 nextId=data.nextId or nextId
 selectedId=restored[data.selectedId] and data.selectedId or next(restored)
 selectedIds={}
 if type(data.selectedIds)=="table" then
  for id,enabled in pairs(data.selectedIds) do
   local num=tonumber(id)
   if enabled and num and restored[num] then selectedIds[num]=true end
  end
 end
 if not next(selectedIds) and selectedId then selectedIds[selectedId]=true end
 checkpoints={} redoStack={}
 changed() repaint()
 showRecoveryBanner(false)
 notice(tr("Черновик восстановлен. Нажми «Применить изменения», чтобы сохранить его в Studio.","Draft restored. Click Apply changes to save in Studio."))
end
promptDraft=function()
 local data,sourceRoot=readSavedDraft()
 -- Show the recovery card right when the editor opens, even with no GUI linked.
 -- If another GUI is currently loaded, wait until it is explicitly selected.
 if not recoveryDismissed and data and sourceRoot and (not currentRoot or currentRoot==sourceRoot) and not dirty then
  showRecoveryBanner(true)
 else
  showRecoveryBanner(false)
 end
end

changed=function()
 dirty=isDirty()
 if footerInfo then footerInfo.Text=dirty and tr("НЕ СОХРАНЕНО · изменения только в редакторе","UNSAVED · editor preview only") or tr("Сохранено · Roblox Studio без изменений","Saved · Roblox Studio unchanged") end
end
local function saveUndo()
 table.insert(checkpoints,snap())
 if #checkpoints&gt;45 then table.remove(checkpoints,1) end
 redoStack={}
end
local function mutate(fn)
 if not nodes then return end
 saveUndo()
 fn()
 changed()
 repaint()
 scheduleSave()
end
local function undo()
 if #checkpoints==0 then notice(tr("Нечего отменять","Nothing to undo")) return end
 table.insert(redoStack,snap())
 restore(table.remove(checkpoints))
 changed() repaint()
 scheduleSave()
end
local function redo()
 if #redoStack==0 then notice(tr("Нечего повторять","Nothing to redo")) return end
 table.insert(checkpoints,snap())
 restore(table.remove(redoStack))
 changed() repaint()
 scheduleSave()
end
local function childrenOf(id)
 local result={}
 for _,item in pairs(nodes or {}) do if item.parent==id then table.insert(result,item) end end
 table.sort(result,function(a,b)
  local la,lb=a.props.LayoutOrder or 0,b.props.LayoutOrder or 0
  if la==lb then return a.id&lt;b.id end
  return la&lt;lb
 end)
 return result
end
local nodeRect = Geometry.nodeRect
local function selected()
 return nodes and nodes[selectedId]
end
local function selectedEditable()
 local n=selected()
 if not n or n.parent==nil then notice(tr("Выбери элемент, не сам ScreenGui","Select an element, not ScreenGui")) return nil end
 return n
end
local function moveLayer(direction)
 local n=selectedEditable()
 if not n then return end
 local siblings=childrenOf(n.parent)
 local position
 for i,item in ipairs(siblings) do if item.id==n.id then position=i break end end
 if not position then return end
 local target=position+direction
 if target&lt;1 or target&gt;#siblings then return end
 mutate(function()
  siblings[position],siblings[target]=siblings[target],siblings[position]
  for i,item in ipairs(siblings) do item.props.LayoutOrder=i end
 end)
 notice(tr("Порядок слоёв обновлён в черновике","Layer order updated in draft"))
end
local function choose(id)
 -- Roblox Studio may swallow InputEnded when the widget loses pointer capture.
 -- A subsequent explicit layer selection is an escape route, never a dead end.
 if moving and cancelActiveGesture then cancelActiveGesture() end
 if moving then return end
 if not nodes or not nodes[id] then return end
 if selectedId==id and selectedIds and selectedIds[id] and not (
  UIS:IsKeyDown(Enum.KeyCode.LeftControl) or UIS:IsKeyDown(Enum.KeyCode.RightControl)
 ) then return end
 local multi=UIS:IsKeyDown(Enum.KeyCode.LeftControl) or UIS:IsKeyDown(Enum.KeyCode.RightControl)
 if multi then
  selectedIds=selectedIds or {}
  selectedIds[id]=not selectedIds[id] or nil
  if selectedIds[id] then selectedId=id
  elseif selectedId==id then selectedId=next(selectedIds) or id end
 else
  selectedId=id
  selectedIds={[id]=true}
 end
 if updateSelectionDecorations then updateSelectionDecorations() end
 if updateLayerSelection then updateLayerSelection() end
 if renderInspector then renderInspector() end
end
local function stageCreate(class,position,size)
 if not allowed[class] then return end
 -- Empty-canvas clicks clear the selected object, not the linked document.
 -- Creating a top-level element must fall back to the linked ScreenGui root.
 local parent=selected()
 if not parent and nodes and currentRoot and currentRoot.Parent then
  for _,candidate in pairs(nodes) do
   if candidate.class=="ScreenGui" and candidate.parent==nil and candidate.original==currentRoot then
    parent=candidate
    break
   end
  end
 end
 if not parent then notice(tr("Сначала выбери GUI через меню Link GUI","Choose a GUI from Link GUI first")) return end
 if parent.class~="ScreenGui" and not allowed[parent.class] then return end
 mutate(function()
  local id=keyId()
  local props={Name=class,Position=position or UDim2.fromOffset(28,28),Size=size or UDim2.fromOffset(170,70),AnchorPoint=Vector2.zero,
   Rotation=0,BackgroundColor3=Color3.fromRGB(48,83,126),BackgroundTransparency=0,BorderSizePixel=0,Visible=true,ZIndex=1,
   LayoutOrder=0,ClipsDescendants=false,Text=tr("Текст","Text"),TextSize=18,TextColor3=Color3.fromRGB(247,250,255),
   TextTransparency=0,TextWrapped=true,TextXAlignment=Enum.TextXAlignment.Center,TextYAlignment=Enum.TextYAlignment.Center,
   Font=Enum.Font.Gotham,Image="",ImageTransparency=0,ImageColor3=Color3.new(1,1,1),ScaleType=Enum.ScaleType.Fit,CornerRadius=UDim.new(0,8)}
  if class=="Frame" or class=="ScrollingFrame" then props.BackgroundTransparency=.05 end
  if class=="ImageLabel" or class=="ImageButton" then props.BackgroundTransparency=1 end
  if class=="TextButton" then props.Text=tr("Кнопка","Button") end
  nodes[id]={id=id,parent=parent.id,class=class,original=nil,props=supportedProps(class,props)}
  -- Leave the selected parent unchanged. Further insertions create siblings,
  -- not accidental nested children, and insertion mode stays active.
 end)
 notice(tr("Элемент создан в черновике. Нажми «Применить», чтобы сохранить.","Added to draft. Click Apply to save."))
end
local function descendants(id)
 local ids={[id]=true}
 local again=true
 while again do
  again=false
  for j,item in pairs(nodes) do
   if item.parent and ids[item.parent] and not ids[j] then ids[j]=true again=true end
  end
 end
 return ids
end
-- FT-EDITOR-DELETE-003: explicit two-click confirmation for container deletion.
local pendingDeleteId,pendingDeleteUntil=nil,0
local function deleteSelected()
 local n=selectedEditable()
 if not n then return end
 local subtree=descendants(n.id)
 local count=0
 for _ in pairs(subtree) do count+=1 end
 -- Never destroy embedded scripts, constraints, unmodelled GUI instances, or other
 -- content the UI editor cannot show. Only decorative components may be implicit.
 for id in pairs(subtree) do
  local entry=nodes[id]
  if entry and entry.original then
   for _,child in ipairs(entry.original:GetChildren()) do
    if not (child:IsA("UICorner") or child:IsA("UIStroke") or child:IsA("UIGradient") or
      (child:IsA("GuiObject") and allowed[child.ClassName] and (function()
       for childId in pairs(subtree) do
        local candidate=nodes[childId]
        if candidate and candidate.original==child then return true end
       end
       return false
      end)())) then
     notice("Delete blocked: contains unsupported "..child.ClassName.." ("..child.Name.."). No objects removed.")
     return
    end
   end
   if not entry.original.Parent or (originalRefs[id] and originalRefs[id]~=entry.original) then
    notice("Delete blocked: Studio objects have changed. Reload the GUI.")
    return
   end
  end
 end
 if count&gt;1 and (pendingDeleteId~=n.id or os.clock()&gt;pendingDeleteUntil) then
  pendingDeleteId=n.id pendingDeleteUntil=os.clock()+8
  notice("Delete "..count.." selected subtree objects? Press Delete again within 8 seconds to confirm.")
  return
 end
 pendingDeleteId=nil pendingDeleteUntil=0
 local parentId=n.parent
 mutate(function()
  for id in pairs(subtree) do nodes[id]=nil end
  selectedId=parentId
  selectedIds={[parentId]=true}
 end)
 notice("Removed "..count.." draft object(s). Apply to commit, or Undo to restore.")
end
local function duplicateSelected()
 local n=selectedEditable()
 if not n then return end
 mutate(function()
  local function duplicate(id,parentId)
   local old=nodes[id]
   nextId+=1
   local newId=nextId
   local p=propsCopy(old.props)
   p.Name=old.props.Name.."_Copy"
   p.Position=UDim2.new(p.Position.X.Scale,p.Position.X.Offset+20,p.Position.Y.Scale,p.Position.Y.Offset+20)
   -- Track the imported source node so cloned UICorners, UIGradients,
   -- layouts and constraints survive preview, undo, JSON draft recovery and Apply.
   nodes[newId]={id=newId,class=old.class,parent=parentId,props=p,original=nil,
    componentSourceId=old.componentSourceId or (old.original and id or nil)}
   local kids=childrenOf(id)
   for _,kid in ipairs(kids) do duplicate(kid.id,newId) end
   return newId
  end
  selectedId=duplicate(n.id,n.parent)
  selectedIds={[selectedId]=true}
 end)
end
local function modifySelected(fn)
 local n=selectedEditable()
 if n then mutate(function() fn(n.props) end) end
end
local function multiNodes()
 local list={}
 for id in pairs(selectedIds or {}) do
  local n=nodes and nodes[id]
  if n and n.parent~=nil then table.insert(list,n) end
 end
 table.sort(list,function(a,b) return a.id&lt;b.id end)
 return list
end
local function alignMulti(axis,side)
 local list=multiNodes()
 if #list&lt;2 then notice(tr("Выдели несколько элементов: Ctrl + клик по слоям","Select multiple layers with Ctrl + click")) return end
 mutate(function()
  for _,n in ipairs(list) do
   local p=n.props
   if axis=="x" then
    p.AnchorPoint=Vector2.new(side,p.AnchorPoint.Y)
    p.Position=UDim2.new(side,side==0 and 8 or side==1 and -8 or 0,p.Position.Y.Scale,p.Position.Y.Offset)
   else
    p.AnchorPoint=Vector2.new(p.AnchorPoint.X,side)
    p.Position=UDim2.new(p.Position.X.Scale,p.Position.X.Offset,side,side==0 and 8 or side==1 and -8 or 0)
   end
  end
 end)
end
local function distributeHorizontal()
 local list=multiNodes()
 if #list&lt;3 then notice(tr("Выдели минимум 3 элемента","Select at least 3 elements")) return end
 local parent=list[1].parent
 for _,n in ipairs(list) do if n.parent~=parent then notice(tr("Нужен один родитель","Elements must share a parent")) return end end
 local parentNode=nodes[parent]
 local size=parentNode and parentNode._renderSize or viewportSize
 table.sort(list,function(a,b) local pa=nodeRect(a,size) local pb=nodeRect(b,size) return pa.X&lt;pb.X end)
 local firstPos=nodeRect(list[1],size)
 local lastPos,lastSize=nodeRect(list[#list],size)
 local total=0
 for _,n in ipairs(list) do local _,sz=nodeRect(n,size) total+=sz.X end
 local gap=(lastPos.X+lastSize.X-firstPos.X-total)/(#list-1)
 if gap&lt;0 then notice(tr("Недостаточно места","Not enough space")) return end
 mutate(function()
  local cursor=firstPos.X
  for _,n in ipairs(list) do
   local p=n.props
   local _,sz=nodeRect(n,size)
   local x=cursor+sz.X*p.AnchorPoint.X-size.X*p.Position.X.Scale
   p.Position=UDim2.new(p.Position.X.Scale,math.floor(x+.5),p.Position.Y.Scale,p.Position.Y.Offset)
   cursor+=sz.X+gap
  end
 end)
end
local function groupSelected()
 local list=multiNodes()
 if #list&lt;2 then notice(tr("Выдели минимум два элемента (Ctrl + клик)","Select at least two elements (Ctrl + click)")) return end
 local parentId=list[1].parent
 for _,n in ipairs(list) do if n.parent~=parentId then notice(tr("Только элементы одного родителя","Only siblings can be grouped")) return end end
 local parent=nodes[parentId]
 local parentSize=parent and parent._renderSize or viewportSize
 local minx,miny,maxx,maxy=math.huge,math.huge,-math.huge,-math.huge
 local rects={}
 for _,n in ipairs(list) do
  local pos,sz=nodeRect(n,parentSize)
  rects[n.id]={pos=pos,size=sz}
  minx=math.min(minx,pos.X) miny=math.min(miny,pos.Y)
  maxx=math.max(maxx,pos.X+sz.X) maxy=math.max(maxy,pos.Y+sz.Y)
 end
 mutate(function()
  nextId+=1 local id=nextId
  nodes[id]={id=id,parent=parentId,class="Frame",original=nil,props={
   Name="Group",Position=UDim2.fromOffset(minx,miny),Size=UDim2.fromOffset(maxx-minx,maxy-miny),AnchorPoint=Vector2.zero,
   Rotation=0,BackgroundColor3=Color3.fromRGB(40,50,60),BackgroundTransparency=1,BorderSizePixel=0,Visible=true,ZIndex=1,
   LayoutOrder=0,ClipsDescendants=false}}
  for _,n in ipairs(list) do
   local rect=rects[n.id]
   n.parent=id
   n.props.Position=UDim2.fromOffset(rect.pos.X-minx,rect.pos.Y-miny)
   n.props.Size=UDim2.fromOffset(rect.size.X,rect.size.Y)
   n.props.AnchorPoint=Vector2.zero
  end
  selectedId=id selectedIds={[id]=true}
 end)
end
local toRGB = Style.toRGB
local parseHex = Style.parseHex
local function formatNumeric(value)
 if type(value)~="number" then return tostring(value) end
 -- Display shorter numbers without changing the underlying UDim/UDim2 property.
 -- Only an explicit user edit writes a new numerical value to the draft.
 if math.abs(value)&lt;0.00005 then return "0" end
 if math.abs(value-math.floor(value+0.5))&lt;0.00005 then return tostring(math.floor(value+0.5)) end
 return string.format("%.4f",value):gsub("0+$",""):gsub("%.$","")
end
local function numberField(parent,title,current,callback)
 local holder=row(parent,28)
 local l=label(holder,title,12,true)
 l.Size=UDim2.fromOffset(80,27)
 local input=make("TextBox",{Text=formatNumeric(current),PlaceholderText="0",ClearTextOnFocus=false,Size=UDim2.new(1,-91,0,26),Font=Enum.Font.Gotham,
 TextSize=13,TextColor3=ink.text,BackgroundColor3=ink.card,BorderSizePixel=0},holder)
 make("UICorner",{CornerRadius=UDim.new(0,4)},input)
 input.FocusLost:Connect(function(enter)
  -- Blurring an untouched rounded display must not corrupt exact Scale values.
  if input.Text==formatNumeric(current) then return end
  local value=tonumber(input.Text)
  if value and value==value and math.abs(value)&lt;100000 then
   callback(value)
  else
   input.Text=formatNumeric(current)
  end
 end)
 return input
end
local function textField(parent,title,current,callback)
 label(parent,title,12,true)
 local input=make("TextBox",{Text=tostring(current or ""),Size=UDim2.new(1,-8,0,28),Font=Enum.Font.Gotham,
  TextSize=13,TextColor3=ink.text,BackgroundColor3=ink.card,ClearTextOnFocus=false,BorderSizePixel=0},parent)
 make("UICorner",{CornerRadius=UDim.new(0,4)},input)
 input.FocusLost:Connect(function() if input.Text~=tostring(current or "") then callback(input.Text) end end)
 return input
end
-- FT-PROPERTIES-DISCLOSURE-002: stable top-down disclosure, no full panel effects.
-- Keep Explorer's tween constant intact: layer animation code also uses motionInfo.
local motionInfo=TweenInfo.new(.24,Enum.EasingStyle.Quart,Enum.EasingDirection.Out)
local inspectorSections={general=true,layout=true,appearance=true,stroke=false,actions=false}
local disclosureInfo=TweenInfo.new(.22,Enum.EasingStyle.Quad,Enum.EasingDirection.Out)
local inspectorPanelGroup
local inspectorMotionGeneration=0
-- FT-PROPERTIES-SELECTION-REVEAL-021: Sketch-style native row reveal.
-- No CanvasGroup wrappers, no position tween, no row-size animation.
local inspectorRowTweens={}
local inspectorRevealRestorers={}
local function cancelInspectorRowTweens()
 for _,tween in ipairs(inspectorRowTweens) do tween:Cancel() end
 table.clear(inspectorRowTweens)
 for _,restore in ipairs(inspectorRevealRestorers) do restore() end
 table.clear(inspectorRevealRestorers)
end
local function revealFieldProperties(row)
 local tracks={}
 local function collect(inst)
  local values={}
  if inst:IsA("GuiObject") then values.BackgroundTransparency=inst.BackgroundTransparency end
  if inst:IsA("TextLabel") or inst:IsA("TextButton") or inst:IsA("TextBox") then
   values.TextTransparency=inst.TextTransparency
   values.TextStrokeTransparency=inst.TextStrokeTransparency
  end
  if inst:IsA("ImageLabel") or inst:IsA("ImageButton") then values.ImageTransparency=inst.ImageTransparency end
  if inst:IsA("UIStroke") then values.Transparency=inst.Transparency end
  if inst:IsA("ScrollingFrame") then values.ScrollBarImageTransparency=inst.ScrollBarImageTransparency end
  for prop,original in pairs(values) do
   table.insert(tracks,{instance=inst,property=prop,original=original})
  end
  for _,child in ipairs(inst:GetChildren()) do collect(child) end
 end
 collect(row)
 local scale=row:FindFirstChild("FTSketchRowScale")
 if not scale then
  scale=Instance.new("UIScale")
  scale.Name="FTSketchRowScale"
  scale.Parent=row
 end
 local originalScale=scale.Scale
 scale.Scale=originalScale*0.985
 for _,rec in ipairs(tracks) do rec.instance[rec.property]=1 end
 local function restore()
  for _,rec in ipairs(tracks) do
   if rec.instance.Parent then rec.instance[rec.property]=rec.original end
  end
  if scale.Parent then scale.Scale=originalScale end
 end
 table.insert(inspectorRevealRestorers,restore)
 return function(info)
  for _,rec in ipairs(tracks) do
   if rec.instance.Parent then
    local tween=TweenService:Create(rec.instance,info,{[rec.property]=rec.original})
    table.insert(inspectorRowTweens,tween)
    tween:Play()
   end
  end
  if scale.Parent then
   local tween=TweenService:Create(scale,info,{Scale=originalScale})
   table.insert(inspectorRowTweens,tween)
   tween:Play()
  end
 end
end
local function animateInspectorPanel()
 if not properties then return end
 local generation=inspectorMotionGeneration
 local animators={}
 local sections={"general","layout","appearance","stroke","actions"}
 for _,key in ipairs(sections) do
  local shell=properties:FindFirstChild("InspectorSection_"..key)
  local viewport=shell and shell:FindFirstChild("InspectorContent_"..key)
  local content=viewport and viewport:FindFirstChild("Content")
  if content and inspectorSections[key] then
   local fields={}
   for _,child in ipairs(content:GetChildren()) do
    if child:IsA("GuiObject") then table.insert(fields,child) end
   end
   table.sort(fields,function(a,b)
    if a.LayoutOrder==b.LayoutOrder then return a.AbsolutePosition.Y&lt;b.AbsolutePosition.Y end
    return a.LayoutOrder&lt;b.LayoutOrder
   end)
   for _,field in ipairs(fields) do table.insert(animators,revealFieldProperties(field)) end
  end
 end
 -- Everything is hidden before we expose the rebuilt inspector.
 if generation~=inspectorMotionGeneration then return end
 properties.Visible=true
 task.spawn(function()
  -- Wait only for a render frame; the initial hidden state already exists.
  RunService.RenderStepped:Wait()
  if generation~=inspectorMotionGeneration or not properties.Parent then return end
  local info=TweenInfo.new(.16,Enum.EasingStyle.Quad,Enum.EasingDirection.Out)
  for index,animate in ipairs(animators) do
   task.delay((index-1)*.015,function()
    if generation~=inspectorMotionGeneration or not properties.Parent then return end
    animate(info)
   end)
  end
 end)
end
local inspectorLayoutToken=0
local inspectorSectionInstances={}
-- A section owns one layout row.  Only its controller changes the row height.
-- This makes UIListLayout move all following sections continuously.
local function inspectorSection(parent,key,caption)
 local expanded=inspectorSections[key]
 local shell=make("Frame",{Name="InspectorSection_"..key,Size=UDim2.new(1,-7,0,30),BackgroundTransparency=1,BorderSizePixel=0,ClipsDescendants=true},parent)
 local header=make("TextButton",{Name="Header",Text="",Size=UDim2.new(1,0,0,30),BackgroundTransparency=1,BorderSizePixel=0,AutoButtonColor=false},shell)
 make("UICorner",{CornerRadius=UDim.new(0,5)},header)
 local arrow=make("TextLabel",{Name="Disclosure",Text="›",Rotation=expanded and 90 or 0,Position=UDim2.fromOffset(1,2),Size=UDim2.fromOffset(19,25),BackgroundTransparency=1,Font=Enum.Font.GothamMedium,TextSize=19,TextColor3=ink.muted},header)
 make("TextLabel",{Text=caption,Position=UDim2.fromOffset(22,0),Size=UDim2.new(1,-24,1,0),BackgroundTransparency=1,Font=Enum.Font.GothamMedium,TextSize=12,TextColor3=ink.text,TextXAlignment=Enum.TextXAlignment.Left},header)
 local viewport=make("Frame",{Name="InspectorContent_"..key,Position=UDim2.fromOffset(0,30),Size=UDim2.new(1,0,0,0),ClipsDescendants=true,BackgroundTransparency=1,BorderSizePixel=0},shell)
 local content=make("Frame",{Name="Content",Size=UDim2.new(1,0,0,0),BackgroundTransparency=1,BorderSizePixel=0},viewport)
 local layout=make("UIListLayout",{Padding=UDim.new(0,5),SortOrder=Enum.SortOrder.LayoutOrder},content)
 local height=Instance.new("NumberValue")
 height.Name="DisclosureHeight"
 height.Value=0
 height.Parent=shell
 local heightTween,arrowTween,hoverTween
 local disposed=false
 local ready=false
 local desiredHeight=0
 local pendingInitial=true
 local function applyHeight(value)
  if disposed or not shell.Parent then return end
  local h=math.max(0,value)
  viewport.Size=UDim2.new(1,0,0,h)
  shell.Size=UDim2.new(1,-7,0,30+h)
 end
 local heightConnection=height.Changed:Connect(applyHeight)
 local function measure()
  local total,count=0,0
  for _,child in ipairs(content:GetChildren()) do
   if child:IsA("GuiObject") and child.Visible then
    local h=child.Size.Y.Offset
    if h&lt;=0 then h=child.AbsoluteSize.Y end
    total+=math.max(0,h)
    count+=1
   end
  end
  local manual=total+math.max(0,count-1)*layout.Padding.Offset
  local actual=layout.AbsoluteContentSize.Y
  -- The fixed-size editor fields are measurable even before the layout pass.
  return math.max(manual, actual)
 end
 local function cancelMotion()
  if heightTween then heightTween:Cancel();heightTween=nil end
  if arrowTween then arrowTween:Cancel();arrowTween=nil end
 end
 local function animate(open)
  if disposed then return end
  cancelMotion()
  local goal=open and desiredHeight or 0
  if math.abs(goal-height.Value)&lt;0.5 then
   height.Value=goal
  else
   heightTween=TweenService:Create(height,disclosureInfo,{Value=goal})
   heightTween:Play()
  end
  arrowTween=TweenService:Create(arrow,disclosureInfo,{Rotation=open and 90 or 0})
  arrowTween:Play()
 end
 local function syncContentHeight()
  if disposed then return end
  local measured=measure()
  if measured&lt;=0 then return end
  if math.abs(measured-desiredHeight)&lt;0.5 then return end
  desiredHeight=measured
  content.Size=UDim2.new(1,0,0,measured)
  if ready and inspectorSections[key] then animate(true) end
 end
 inspectorSectionInstances[key]={shell=shell,viewport=viewport,content=content,stop=cancelMotion}
 header.MouseEnter:Connect(function()
  if hoverTween then hoverTween:Cancel() end
  hoverTween=TweenService:Create(header,TweenInfo.new(.14),{BackgroundColor3=ink.blue,BackgroundTransparency=.88})
  hoverTween:Play()
 end)
 header.MouseLeave:Connect(function()
  if hoverTween then hoverTween:Cancel() end
  hoverTween=TweenService:Create(header,TweenInfo.new(.14),{BackgroundTransparency=1})
  hoverTween:Play()
 end)
 header.MouseButton1Click:Connect(function()
  inspectorSections[key]=not inspectorSections[key]
  syncContentHeight()
  animate(inspectorSections[key])
 end)
 layout:GetPropertyChangedSignal("AbsoluteContentSize"):Connect(function()
  if not ready or disposed then return end
  syncContentHeight() -- never assigns shell/viewport height directly
 end)
 shell.Destroying:Connect(function()
  disposed=true
  cancelMotion()
  heightConnection:Disconnect()
  if hoverTween then hoverTween:Cancel() end
  if inspectorSectionInstances[key] and inspectorSectionInstances[key].shell==shell then
   inspectorSectionInstances[key]=nil
  end
 end)
 task.defer(function()
  if disposed or not shell.Parent then return end
  syncContentHeight()
  -- Initial presentation is established once. Later changes only use animate().
  if pendingInitial then
   pendingInitial=false
   height.Value=inspectorSections[key] and desiredHeight or 0
   applyHeight(height.Value)
   ready=true
  end
 end)
 return content
end

local lastInspectorSelectionKey=nil
renderInspector=function()
 if not properties then return end
 local selectedNode=selected()
 local nextKey=selectedNode and selectedNode.id or "none"
 local selectionChanged=nextKey~=lastInspectorSelectionKey
 lastInspectorSelectionKey=nextKey
 inspectorLayoutToken+=1
 for _,controller in pairs(inspectorSectionInstances) do
  if controller.stop then controller.stop() end
 end
 table.clear(inspectorSectionInstances)
 -- Always cancel old row tweens before replacing Inspector contents.
 inspectorMotionGeneration+=1
 cancelInspectorRowTweens()
 if selectionChanged then properties.Visible=false end
 clear(properties)
 stack(properties,7)
 local n=selected()
 if not n then
  label(properties,currentRoot and tr("Выбери слой слева для редактирования. Новые элементы добавляются в корень GUI.","Select a layer to edit. New elements will be added to the GUI root.") or tr("Открой GUI через меню Link GUI слева","Open a GUI using Link GUI on the left"),12,true)
  if selectionChanged then properties.Visible=true end
  return
 end
 local name=label(properties,n.props.Name or n.class,14)
 name.Font=Enum.Font.GothamMedium
 label(properties,n.class..(dirty and "  • "..tr("черновик","draft") or ""),11,true)
 if not n.parent then
  label(properties,tr("Выдели элемент на холсте или слева в списке слоёв.","Select an element on the canvas or in Layers."),12,true)
  if selectionChanged then properties.Visible=true end
  return
 end
 local id=n.id
 local function edit(fn)
  if nodes and nodes[id] then mutate(function() fn(nodes[id].props) end) end
 end
 local p=n.props
 local general=inspectorSection(properties,"general",tr("Общие","General"))
 if general then
  textField(general,tr("Название","Name"),p.Name,function(v) edit(function(q) q.Name=v end) end)
  if textClasses[n.class] then textField(general,tr("Текст","Text"),p.Text,function(v) edit(function(q) q.Text=v end) end) end
  if imageClasses[n.class] then textField(general,"Image Asset ID",p.Image,function(v)
    local normalized=normalizeImage(v)
    if normalized then edit(function(q) q.Image=normalized end)
    else notice(tr("Нужен числовой Asset ID или rbxassetid://ID","Enter a numeric Asset ID or rbxassetid://ID")) end
   end) end
  numberField(general,"ZIndex",p.ZIndex,function(v) edit(function(q) q.ZIndex=math.max(1,math.floor(v)) end) end)
  btn(general,p.Visible and tr("◉  Видимый","◉  Visible") or tr("○  Скрытый","○  Hidden"),function() edit(function(q) q.Visible=not q.Visible end) end,196)
 end
 local layout=inspectorSection(properties,"layout",tr("Размеры и положение","Layout"))
 if layout then
  label(layout,"POSITION · OFFSET",10,true)
  numberField(layout,"X",p.Position.X.Offset,function(v) edit(function(q) q.Position=UDim2.new(q.Position.X.Scale,v,q.Position.Y.Scale,q.Position.Y.Offset) end) end)
  numberField(layout,"Y",p.Position.Y.Offset,function(v) edit(function(q) q.Position=UDim2.new(q.Position.X.Scale,q.Position.X.Offset,q.Position.Y.Scale,v) end) end)
  label(layout,"SIZE · OFFSET",10,true)
  numberField(layout,"W",p.Size.X.Offset,function(v) edit(function(q) q.Size=UDim2.new(q.Size.X.Scale,v,q.Size.Y.Scale,q.Size.Y.Offset) end) end)
  numberField(layout,"H",p.Size.Y.Offset,function(v) edit(function(q) q.Size=UDim2.new(q.Size.X.Scale,q.Size.X.Offset,q.Size.Y.Scale,v) end) end)
  label(layout,"POSITION · SCALE",10,true)
  numberField(layout,"X",p.Position.X.Scale,function(v) edit(function(q) q.Position=UDim2.new(v,q.Position.X.Offset,q.Position.Y.Scale,q.Position.Y.Offset) end) end)
  numberField(layout,"Y",p.Position.Y.Scale,function(v) edit(function(q) q.Position=UDim2.new(q.Position.X.Scale,q.Position.X.Offset,v,q.Position.Y.Offset) end) end)
  label(layout,"SIZE · SCALE",10,true)
  numberField(layout,"W",p.Size.X.Scale,function(v) edit(function(q) q.Size=UDim2.new(v,q.Size.X.Offset,q.Size.Y.Scale,q.Size.Y.Offset) end) end)
  numberField(layout,"H",p.Size.Y.Scale,function(v) edit(function(q) q.Size=UDim2.new(q.Size.X.Scale,q.Size.X.Offset,v,q.Size.Y.Offset) end) end)
  numberField(layout,"Anchor X",p.AnchorPoint.X,function(v) edit(function(q) q.AnchorPoint=Vector2.new(math.clamp(v,0,1),q.AnchorPoint.Y) end) end)
  numberField(layout,"Anchor Y",p.AnchorPoint.Y,function(v) edit(function(q) q.AnchorPoint=Vector2.new(q.AnchorPoint.X,math.clamp(v,0,1)) end) end)
  numberField(layout,tr("Поворот","Rotation"),p.Rotation,function(v) edit(function(q) q.Rotation=v end) end)
 end
 local app=inspectorSection(properties,"appearance",tr("Оформление","Appearance"))
 if app then
  textField(app,tr("Заливка HEX","Fill HEX"),toRGB(p.BackgroundColor3),function(v)
   local c=parseHex(v) if c then edit(function(q) q.BackgroundColor3=c end) else notice(tr("Нужен цвет вида #3A88DD","Use HEX like #3A88DD")) end
  end)
  numberField(app,tr("Прозрачность","Transparency"),p.BackgroundTransparency,function(v) edit(function(q) q.BackgroundTransparency=math.clamp(v,0,1) end) end)
  numberField(app,tr("Скругление","Corner radius"),p.CornerRadius and p.CornerRadius.Offset or 0,function(v) edit(function(q) q.CornerRadius=UDim.new(0,math.clamp(v,0,100)) end) end)
  if textClasses[n.class] then
   numberField(app,tr("Размер шрифта","Text size"),p.TextSize,function(v) edit(function(q) q.TextSize=math.clamp(v,1,100) end) end)
   textField(app,tr("Цвет текста HEX","Text HEX"),toRGB(p.TextColor3),function(v) local c=parseHex(v) if c then edit(function(q) q.TextColor3=c end) end end)
   numberField(app,tr("Прозрачность текста","Text transparency"),p.TextTransparency or 0,function(v) edit(function(q) q.TextTransparency=math.clamp(v,0,1) end) end)
  end
 end
 local stroke=inspectorSection(properties,"stroke",tr("Обводка","Stroke"))
 if stroke then
  numberField(stroke,tr("Толщина","Thickness"),p.StrokeThickness or 0,function(v) edit(function(q) q.StrokeThickness=math.clamp(v,0,20) if q.StrokeThickness&gt;0 and not q.StrokeColor then q.StrokeColor=ink.blue end end) end)
  textField(stroke,tr("Цвет HEX","Color HEX"),toRGB(p.StrokeColor or ink.blue),function(v) local c=parseHex(v) if c then edit(function(q) q.StrokeColor=c end) end end)
 end
 local actions=inspectorSection(properties,"actions",tr("Действия","Actions"))
 if actions then
  btn(actions,tr("Копировать","Duplicate"),duplicateSelected,196)
  btn(actions,tr("Удалить","Delete"),deleteSelected,196,ink.red)
  btn(actions,tr("Слой выше","Layer up"),function() moveLayer(-1) end,196)
  btn(actions,tr("Слой ниже","Layer down"),function() moveLayer(1) end,196)
 end
 if selectionChanged then animateInspectorPanel() end
end
-- FT-EDITOR-MOTION-002: a nested disclosure tree, with one height tween per
-- changed branch/ancestor. No full tree rebuild or per-row tweens on expand.
local function tweenRow(button,target)
 if not button or not button.Parent then return end
 if math.abs(button.BackgroundTransparency-target)&lt;.001 then return end
 local previous=layerSelectionTweens[button]
 if previous then previous:Cancel() end
 local tween=TweenService:Create(button,TweenInfo.new(.14,Enum.EasingStyle.Quad,Enum.EasingDirection.Out),{BackgroundTransparency=target})
 layerSelectionTweens[button]=tween
 tween:Play()
end
updateLayerSelection=function()
 for id,button in pairs(layerSelectButtons) do
  if button and button.Parent then
   local active=selectedIds and selectedIds[id]
   tweenRow(button,active and 0 or 1)
  else
   layerSelectButtons[id]=nil
  end
 end
end
renderLayers=function()
 if not layerList then return end
 layerAnimationGeneration+=1
 clear(layerList)
 layerSelectButtons={}
 layerSelectionTweens={}
 stack(layerList,1)
 if not nodes then return end
 local treeViews={}
 local childrenCache={}
 local function childIds(id)
  if not childrenCache[id] then childrenCache[id]=childrenOf(id) end
  return childrenCache[id]
 end
 local function subtreeHeight(id)
  local height=26
  if not collapsedLayers[id] then
   local children=childIds(id)
   for _,child in ipairs(children) do
    height+=subtreeHeight(child.id)+1
   end
  end
  return height
 end
 local function expandedChildrenHeight(id)
  local height=0
  for _,child in ipairs(childIds(id)) do height+=subtreeHeight(child.id)+1 end
  return height
 end
 local function entry(id,parent,depth,parentId)
  local n=nodes[id]
  if not n then return end
  local children=childIds(id)
  local hasChildren=#children&gt;0
  local open=not collapsedLayers[id]
  local height=subtreeHeight(id)
  local container=make("Frame",{
   Name="LayerEntry",Size=UDim2.new(1,-2,0,height),BackgroundTransparency=1,
   ClipsDescendants=true,
  },parent)
  stack(container,0)
  local line=make("Frame",{Size=UDim2.new(1,0,0,26),BackgroundTransparency=1},container)
  local expander=make("TextButton",{
   Name="LayerDisclosure",Text="",BackgroundTransparency=1,BorderSizePixel=0,
   AutoButtonColor=false,Active=hasChildren,
   Size=UDim2.fromOffset(19,26),ZIndex=9,
  },line)
  if hasChildren then
   make("TextLabel",{
    Name="Chevron",Text="›",Rotation=open and 90 or 0,
    Size=UDim2.fromScale(1,1),BackgroundTransparency=1,
    Font=Enum.Font.GothamMedium,TextSize=19,TextColor3=ink.muted,ZIndex=10,
   },expander)
  end
  local b=make("TextButton",{
   Name="LayerSelect",Text="",Font=Enum.Font.Gotham,
   TextSize=12,TextColor3=ink.text,BackgroundColor3=ink.card,
   BackgroundTransparency=(selectedIds and selectedIds[id]) and 0 or 1,
   BorderSizePixel=0,AutoButtonColor=false,Active=true,
   Position=UDim2.fromOffset(0,0),Size=UDim2.new(1,0,0,26),ZIndex=2,
  },line)
  make("UICorner",{CornerRadius=UDim.new(0,5)},b)
  layerSelectButtons[id]=b
  b.MouseButton1Click:Connect(function() choose(id) end)
  b.MouseEnter:Connect(function()
   if not (selectedIds and selectedIds[id]) then tweenRow(b,.25) end
  end)
  b.MouseLeave:Connect(function()
   tweenRow(b,(selectedIds and selectedIds[id]) and 0 or 1)
  end)
  local layerIcon=iconAsset(n.class=="ScreenGui" and "Frame" or n.class)
  if layerIcon then
   make("ImageLabel",{Name="ClassIcon",Image=layerIcon,Position=UDim2.fromOffset(18,4),Size=UDim2.fromOffset(18,18),BackgroundTransparency=1,ScaleType=Enum.ScaleType.Fit,ZIndex=3},b)
  else
   make("TextLabel",{Name="ClassGlyph",Text=n.class=="ScreenGui" and "▣" or "F",Position=UDim2.fromOffset(21,2),Size=UDim2.fromOffset(19,22),BackgroundTransparency=1,Font=Enum.Font.GothamBold,TextSize=15,TextColor3=ink.muted,ZIndex=3},b)
  end
  local layerName=make("TextLabel",{
   Name="LayerName",Text=n.props.Name or n.class,Position=UDim2.fromOffset(41,0),
   Size=UDim2.new(1,-41,1,0),BackgroundTransparency=1,TextColor3=ink.text,
   Font=Enum.Font.GothamMedium,TextSize=13,TextXAlignment=Enum.TextXAlignment.Left,
   TextTruncate=Enum.TextTruncate.AtEnd,ZIndex=3,
  },b)
  local nameMotion=TweenInfo.new(.17,Enum.EasingStyle.Quart,Enum.EasingDirection.Out)
  local nameTween
  local function animateName(offset)
   if not layerName.Parent then return end
   if nameTween then nameTween:Cancel() end
   nameTween=TweenService:Create(layerName,nameMotion,{Position=UDim2.fromOffset(45+offset,0)})
   nameTween:Play()
  end
  b.MouseEnter:Connect(function() animateName(3) end)
  b.MouseLeave:Connect(function() animateName(0) end)
  local view={container=container,parentId=parentId}
  treeViews[id]=view
  if hasChildren then
   local branchProps={
    Name="LayerChildren",Size=UDim2.new(1,0,0,open and expandedChildrenHeight(id) or 0),
    BackgroundTransparency=1,ClipsDescendants=true,
   }
   local fadeBranch=true
   if fadeBranch then branchProps.GroupTransparency=open and 0 or 1 end
   local branch=make(fadeBranch and "CanvasGroup" or "Frame",branchProps,container)
   local inner=make("Frame",{
    Name="LayerChildrenContent",Position=UDim2.fromOffset(3,0),Size=UDim2.new(1,-3,0,0),
    AutomaticSize=Enum.AutomaticSize.Y,BackgroundTransparency=1,
   },branch)
   stack(inner,1)
   view.branch=branch
   view.chevron=expander:FindFirstChild("Chevron")
   for _,child in ipairs(children) do entry(child.id,inner,depth+1,id) end
   expander.MouseButton1Click:Connect(function()
    collapsedLayers[id]=not collapsedLayers[id] or nil
    local cursorId=id
    while cursorId do
     local item=treeViews[cursorId]
     if not item or not item.container.Parent then break end
     local total=subtreeHeight(cursorId)
     local tween=TweenService:Create(item.container,motionInfo,{Size=UDim2.new(1,-2,0,total)})
     tween:Play()
     if item.branch then
      local target=collapsedLayers[cursorId] and 0 or expandedChildrenHeight(cursorId)
      local targetProps={Size=UDim2.new(1,0,0,target)}
      if item.branch:IsA("CanvasGroup") then
       targetProps.GroupTransparency=collapsedLayers[cursorId] and 1 or 0
      end
      TweenService:Create(item.branch,motionInfo,targetProps):Play()
     end
     cursorId=item.parentId
    end
    if view.chevron and view.chevron.Parent then
     TweenService:Create(view.chevron,motionInfo,{Rotation=collapsedLayers[id] and 0 or 90}):Play()
    end
   end)
  end
 end
 for id,n in pairs(nodes) do if not n.parent then entry(id,layerList,0,nil) break end end
end
local function editorHitTest(point)
 local hitId,score=nil,-math.huge
 for id,proxy in pairs(proxyById) do
  local item=nodes and nodes[id]
  if item and item.parent and proxy and proxy.Parent and proxy.Visible then
   local origin,extent=proxy.AbsolutePosition,proxy.AbsoluteSize
   if extent.X&gt;0 and extent.Y&gt;0 and point.X&gt;=origin.X and point.Y&gt;=origin.Y and point.X&lt;=origin.X+extent.X and point.Y&lt;=origin.Y+extent.Y then
    local depth=0
    local cursor=item
    while cursor and cursor.parent and depth&lt;30 do
     depth+=1 cursor=nodes[cursor.parent]
    end
    -- Deepest visible GUI wins. The native relative ZIndex decides ties.
    local weight=depth*10000+(tonumber(proxy.ZIndex) or 1)*10+id/10000
    if weight&gt;score then score=weight hitId=id end
   end
  end
 end
 return hitId
end
local function captureInput(id,button,input,mode)
 if popupIsBlocking() then return end
 if moving and activeGestureMode==mode then return end
 if not input then input={UserInputType=Enum.UserInputType.MouseButton1} end
 if input.UserInputType~=Enum.UserInputType.MouseButton1 then return end
 -- Holding Space reserves LMB for viewport pan, never edit a real GUI object.
 if UIS:IsKeyDown(Enum.KeyCode.Space) then return end
 -- Nested GuiObjects can deliver one click through several listeners.
 if moving and input==activeGestureInput then
  -- Resize handles win even when an underlying preview got the press first.
  if mode:sub(1,7)=="resize:" and activeGestureMode=="move" then
   if cancelActiveGesture then cancelActiveGesture() end
  else
   return
  end
 end
 lastCanvasPressInput=input
 -- Multiple overlapping GuiObjects can report the same press. Ignore that duplicate,
 -- but release an orphaned previous gesture when a genuinely new press arrives.
 if moving then
  if input==activeGestureInput then return end
  if cancelActiveGesture then cancelActiveGesture() end
  if moving then return end
 end
 if activeTool~="Select" then
  if beginCanvasDraw then beginCanvasDraw(input) end
  return
 end
 if mode=="move" then
  id=editorHitTest(mousePointer()) or id
 end
 local n=nodes and nodes[id]
 if not n or n.parent==nil then return end
 
 if not (selectedIds and selectedIds[id]) then
  selectedId=id
  selectedIds={[id]=true}
  if updateSelectionDecorations then updateSelectionDecorations() end
  if updateLayerSelection then updateLayerSelection() end
  renderInspector()
 end
 moving=true
 local start=mousePointer()
 if mode=="move" then setCursorIcon(cursorIcons.move) elseif mode:match("^resize:") then setCursorIcon(cursorForHandle(mode:match("^resize:(.+)$") or "se")) end
 local pressedAt=os.clock()
 local originalPos=n.props.Position
 local originalSize=n.props.Size
 local participants={}
 if mode=="move" and selectedIds then
  for otherId in pairs(selectedIds) do
   local other=nodes[otherId]
   if other and other.parent then participants[otherId]=other.props.Position end
  end
 end
 if next(participants)==nil and mode=="move" then participants[id]=originalPos end
 local parentNode=nodes[n.parent]
 local parentSize=parentNode and parentNode._renderSize or viewportSize
 local startRect,startExtent=nodeRect(n,parentSize)
 local didMove=false
 local tracker,finisher,focusFinisher,localFinisher,inputFinisher
 local released=false
 local trackGesture
 local function release()
  if released then return end
  released=true
  if activeGestureMove==trackGesture then activeGestureMove=nil end
  if tracker then tracker:Disconnect() tracker=nil end
  if finisher then finisher:Disconnect() finisher=nil end
  if focusFinisher then focusFinisher:Disconnect() focusFinisher=nil end
  if localFinisher then localFinisher:Disconnect() localFinisher=nil end
  if inputFinisher then inputFinisher:Disconnect() inputFinisher=nil end
  if cancelActiveGesture==release then cancelActiveGesture=nil end
  if activeGestureUp==release then activeGestureUp=nil end
  if activeGestureInput==input then activeGestureInput=nil activeGestureMode=nil end
  if lastCanvasPressInput==input then lastCanvasPressInput=nil end
  moving=false
  setCursorIcon(activeTool=="Select" and cursorIcons.default or cursorIcons.cross)
  if didMove then
   changed()
   repaint()
   scheduleSave()
  else
   -- A click is not a document mutation; keep the preview and its connections alive.
   if updateSelectionDecorations then updateSelectionDecorations() end
  end
 end
 trackGesture=function(ev)
  if ev and ev.UserInputType~=Enum.UserInputType.MouseMovement then return end
  if not nodes or not nodes[id] then return end
  -- PluginGui button state is not reliably reflected by global UIS;
  -- finish on InputEnded / InputObject.End / WindowFocusReleased instead.
  local pointer=mousePointer()
  if not dock or not dock.Enabled or not viewportController or not viewportController:contains(pointer) then return end
  local delta=pointer-start
  local dx=math.floor(delta.X/math.max(zoom,0.05)+0.5)
  local dy=math.floor(delta.Y/math.max(zoom,0.05)+0.5)
  if UIS:IsKeyDown(Enum.KeyCode.LeftShift) or UIS:IsKeyDown(Enum.KeyCode.RightShift) then
   dx=math.floor(dx/8+.5)*8
   dy=math.floor(dy/8+.5)*8
  end
  if not didMove and (math.abs(dx)&gt;2 or math.abs(dy)&gt;2) then saveUndo() didMove=true end
  if not didMove then return end
  local current=nodes[id].props
  if mode=="move" then
   for otherId,original in pairs(participants) do
    local q=nodes[otherId]
    if q then q.props.Position=UDim2.new(original.X.Scale,original.X.Offset+dx,original.Y.Scale,original.Y.Offset+dy) end
   end
  else
   local direction=mode:match("^resize:(.+)$") or "se"
   local left=direction:find("w",1,true)~=nil
   local right=direction:find("e",1,true)~=nil
   local top=direction:find("n",1,true)~=nil
   local bottom=direction:find("s",1,true)~=nil
   local x1,y1=startRect.X,startRect.Y
   local x2,y2=startRect.X+startExtent.X,startRect.Y+startExtent.Y
   if left then x1=math.min(x2-12,x1+dx) end
   if right then x2=math.max(x1+12,x2+dx) end
   if top then y1=math.min(y2-12,y1+dy) end
   if bottom then y2=math.max(y1+12,y2+dy) end
   local w,h=x2-x1,y2-y1
   local anchor=originalPos
   local ap=current.AnchorPoint or Vector2.zero
   
   current.Size=UDim2.new(originalSize.X.Scale,originalSize.X.Offset+w-startExtent.X,originalSize.Y.Scale,originalSize.Y.Offset+h-startExtent.Y)
   current.Position=UDim2.new(anchor.X.Scale,anchor.X.Offset+x1-startRect.X+(w-startExtent.X)*ap.X,
    anchor.Y.Scale,anchor.Y.Offset+y1-startRect.Y+(h-startExtent.Y)*ap.Y)
  end
  for affectedId in pairs(mode=="move" and participants or {[id]=true}) do
   local affected=nodes[affectedId]
   local proxy=proxyById[affectedId]
   if affected and proxy then
    local pn=nodes[affected.parent]
    local psz=pn and pn._renderSize or viewportSize
    local position,size=nodeRect(affected,psz)
    affected._renderSize=size
    proxy.Position=affected.props.Position
    proxy.Size=affected.props.Size
    queueOverlayUpdate(affectedId)
   end
  end
 end
 activeGestureMove=trackGesture
 tracker=UIS.InputChanged:Connect(trackGesture)
 local localMove=workScroll and workScroll.InputChanged:Connect(trackGesture)
 local sceneMove=scene and scene.InputChanged:Connect(trackGesture)
 local buttonMove=button and button.Parent and button.InputChanged:Connect(trackGesture)
 local originalRelease=release
 release=function()
  if localMove then localMove:Disconnect() localMove=nil end
  if sceneMove then sceneMove:Disconnect() sceneMove=nil end
  if buttonMove then buttonMove:Disconnect() buttonMove=nil end
  originalRelease()
 end
 cancelActiveGesture=release
 activeGestureUp=release
 activeGestureInput=input
 activeGestureMode=mode
 finisher=UIS.InputEnded:Connect(function(ev)
  if ev.UserInputType==Enum.UserInputType.MouseButton1 then release() end
 end)
 -- PluginGui input is not always forwarded to the global input service.
 if button and button.Parent then
  localFinisher=button.InputEnded:Connect(function(ev)
   if ev.UserInputType==Enum.UserInputType.MouseButton1 then release() end
  end)
 end
if input.Changed then inputFinisher=input.Changed:Connect(function()
  if input.UserInputState==Enum.UserInputState.End or input.UserInputState==Enum.UserInputState.Cancel then
   -- The actual pointer-release event is authoritative for PluginGui gestures.
   -- Never terminate a live gesture just because Studio recycled an InputObject.
   if not (dock and dock.Enabled and UIS:IsMouseButtonPressed(Enum.UserInputType.MouseButton1)) then
    release()
   end
  end
 end) end
 focusFinisher=(dock or UIS).WindowFocusReleased:Connect(release)
end
-- Real Roblox UI preview. No scripts are cloned or executed in the editor.
-- The canvas uses real GuiObject classes and Roblox layout/decorator instances.
local previewComponents={
 UICorner=true,UIStroke=true,UIGradient=true,UIPadding=true,UIScale=true,
 UIListLayout=true,UIGridLayout=true,UITableLayout=true,UIAspectRatioConstraint=true,
 UISizeConstraint=true,UITextSizeConstraint=true,UIFlexItem=true,UIPageLayout=true,
}
local function copyPreviewComponents(original,preview)
 if not original then return end
 for _,child in ipairs(original:GetChildren()) do
  if previewComponents[child.ClassName] then
   -- No Scripts/LocalScripts/ModuleScripts, no arbitrary executable descendants.
   local ok,clone=pcall(function() return child:Clone() end)
   if ok and clone then
    for _,nested in ipairs(clone:GetDescendants()) do
     if nested:IsA("LuaSourceContainer") then nested:Destroy() end
    end
    clone.Parent=preview
   end
  end
 end
end
local function makeSelectionHandles(id,overlay,extent)
  for _,h in ipairs({{"nw",0,0},{"n",.5,0},{"ne",1,0},{"w",0,.5},{"e",1,.5},{"sw",0,1},{"s",.5,1},{"se",1,1}}) do
   local knob=Instance.new("TextButton")
   knob.Name="FT_Resize_"..h[1] knob.Text="" knob.AutoButtonColor=false
   knob.Size=UDim2.fromOffset(8,8) knob.AnchorPoint=Vector2.new(.5,.5)
   -- Tiny controls only need corner handles; side handles obscure the content.
   knob.Visible=(h[1]=="nw" or h[1]=="ne" or h[1]=="sw" or h[1]=="se") or (extent.X*zoom&gt;=72 and extent.Y*zoom&gt;=54)
   knob.Position=UDim2.fromScale(h[2],h[3]) knob.BackgroundColor3=Color3.fromRGB(245,248,255)
   knob.BorderSizePixel=0 knob.ZIndex=1002 knob.Active=true knob.Parent=overlay
   local knobScale=Instance.new("UIScale") knobScale.Scale=math.clamp(1/zoom,1,5) knobScale.Parent=knob
   local corner=Instance.new("UICorner") corner.CornerRadius=UDim.new(0,2) corner.Parent=knob
   local border=Instance.new("UIStroke") border.Color=Color3.fromRGB(93,155,245) border.Thickness=1.5 border.Parent=knob
   knob.MouseEnter:Connect(function() if activeTool=="Select" then setCursorIcon(cursorForHandle(h[1])) end end)
   knob.MouseLeave:Connect(function() if not moving then setCursorIcon(activeTool=="Select" and cursorIcons.default or cursorIcons.cross) end end)
   knob.InputBegan:Connect(function(input) captureInput(id,knob,input,"resize:"..h[1]) end)
   knob.MouseButton1Down:Connect(function() captureInput(id,knob,nil,"resize:"..h[1]) end)
   knob.MouseMoved:Connect(function() if activeGestureMove then activeGestureMove() end end)
   knob.MouseButton1Up:Connect(function() if activeGestureUp then activeGestureUp() end end)
  end
  -- Size readout belongs to the non-destructive overlay, not to the user's UI tree.
  local sizeInfo=Instance.new("TextLabel")
  sizeInfo.Name="FT_SelectionDimensions"
  sizeInfo.Text=tostring(math.floor(extent.X+0.5)).." × "..tostring(math.floor(extent.Y+0.5))
  sizeInfo.Font=Enum.Font.GothamMedium sizeInfo.TextSize=12
  sizeInfo.TextColor3=Color3.fromRGB(24,33,49)
  sizeInfo.BackgroundColor3=Color3.fromRGB(172,202,255)
  sizeInfo.BorderSizePixel=0 sizeInfo.ZIndex=1004
  sizeInfo.AnchorPoint=Vector2.new(.5,0)
  sizeInfo.Position=UDim2.new(.5,0,1,12)
  sizeInfo.Size=UDim2.fromOffset(78,18)
  sizeInfo.TextSize=10
  -- Never cover small controls with the dimensions tooltip.
  sizeInfo.Visible=(extent.X*zoom&gt;=105 and extent.Y*zoom&gt;=62)
  sizeInfo.Parent=overlay
  local sizeScale=Instance.new("UIScale") sizeScale.Scale=math.clamp(1/zoom,1,5) sizeScale.Parent=sizeInfo
  local sizeCorner=Instance.new("UICorner") sizeCorner.CornerRadius=UDim.new(0,4) sizeCorner.Parent=sizeInfo
end
updateSelectionDecorations=function()
 if not nodes then return end
 for id,overlay in pairs(overlayById) do
  if overlay and overlay.Parent then
   local on=selectedIds ~= nil and selectedIds[id] == true
   local previous=decoratedSelection[id] == true
   if on ~= previous then
    decoratedSelection[id]=on or nil
    local stroke=overlay:FindFirstChild("FT_Selection")
    if stroke then stroke.Transparency=on and 0 or 1 end
    if on then
     local proxy=proxyById[id]
     local target=nodes[id]
     local parent=target and target.parent and nodes[target.parent]
     if proxy and proxy.Parent and target then
      local _,extent=nodeRect(target,parent and parent._renderSize or viewportSize)
      makeSelectionHandles(id,overlay,extent)
     end
    else
     for _,child in ipairs(overlay:GetChildren()) do
      if child.Name=="FT_SelectionDimensions" or child.Name:sub(1,10)=="FT_Resize_" then
       child:Destroy()
      end
     end
    end
   end
  end
 end
end

local function renderNode(id,parent,size,depth)
 local n=nodes[id]
 if not n or depth&gt;24 or n.props.Visible==false then return end
 local p=n.props
 local ok,gui=pcall(Instance.new,n.class)
 if not ok or not gui or not gui:IsA("GuiObject") then return end
 gui.Name="Preview_"..(p.Name or n.class)
 gui.Parent=parent
 -- Do not reconstruct layout by hand: keep native UDim2 and AnchorPoint.
 for _,key in ipairs(copyKeys) do
  if p[key]~=nil then pcall(function() gui[key]=p[key] end) end
 end
 -- FT-EDITOR-007: PluginGui layers are not guaranteed to use the same sibling ZIndex
 -- behavior as the original ScreenGui. A parent with ZIndex=10 and a TextLabel
 -- child with ZIndex=1 otherwise hides all of the child's text below the frame.
 -- Reserve one band per tree depth; preserve relative ZIndex among siblings.
 gui.ZIndex=math.clamp(depth*32+math.clamp(tonumber(p.ZIndex) or 1,1,31),1,900)
 gui.Active=true
 if gui:IsA("GuiButton") then gui.AutoButtonColor=false end
 local componentSource=n.original or (n.componentSourceId and nodes[n.componentSourceId] and nodes[n.componentSourceId].original)
 copyPreviewComponents(componentSource,gui)
 if p.CornerRadius then
  local corner=gui:FindFirstChildOfClass("UICorner")
  if not corner then corner=Instance.new("UICorner") corner.Parent=gui end
  corner.CornerRadius=p.CornerRadius
 end
 if p.StrokeColor then
  local stroke=gui:FindFirstChildOfClass("UIStroke")
  if not stroke then stroke=Instance.new("UIStroke") stroke.Parent=gui end
  stroke.Color=p.StrokeColor stroke.Thickness=p.StrokeThickness or 1
 end
 proxyById[id]=gui
  -- Every preview class is a GuiObject, not necessarily a GuiButton.
  -- Frame / TextLabel / ImageLabel do NOT expose MouseButton1Down/Up.
  -- Use GuiObject input events consistently to keep rendering alive.
  gui.InputEnded:Connect(function(input)
   if input.UserInputType==Enum.UserInputType.MouseButton1 and activeGestureUp then
    activeGestureUp()
   end
  end)
 gui.InputBegan:Connect(function(input)
  if input.UserInputType==Enum.UserInputType.MouseButton1 and UIS:IsKeyDown(Enum.KeyCode.Space) then
   if panInputHandler then panInputHandler(input) end
   return
  end
  if input.UserInputType==Enum.UserInputType.MouseButton1 then
   captureInput(id,gui,input,"move")
  elseif input.UserInputType==Enum.UserInputType.MouseButton2 and openEditorContextForPoint then
   openEditorContextForPoint(mousePointer())
  end
 end)
 gui.MouseMoved:Connect(function()
  if activeGestureMove then activeGestureMove() end
  if canvasMouseMotion then canvasMouseMotion() end
  if panMouseMotion then panMouseMotion() end
 end)
 gui.InputChanged:Connect(function(input)
  if input.UserInputType==Enum.UserInputType.MouseWheel and wheelHandler then
   wheelHandler(input)
  end
 end)
 local _,extent=nodeRect(n,size)
 n._renderSize=extent
 -- Actual UI children are the original supported classes; component layouts work natively.
 for _,child in ipairs(childrenOf(id)) do renderNode(child.id,gui,extent,depth+1) end
 local overlay=Instance.new("Frame")
 overlay.Name="FT_SelectionOverlay"
 overlay.BackgroundTransparency=1 overlay.BorderSizePixel=0
 overlay.Size=UDim2.fromOffset(1,1) overlay.ZIndex=1000 overlay.Active=false
 overlay.Parent=scene
 overlayById[id]=overlay
 queueOverlayUpdate(id)
 -- Overlay only reacts to selection; there is no gameplay execution in the preview.
 local outline=Instance.new("UIStroke")
 outline.Name="FT_Selection" outline.Color=ink.blue
 outline.Thickness=2 outline.Transparency=(selectedIds and selectedIds[id]) and 0 or 1
 outline.ApplyStrokeMode=Enum.ApplyStrokeMode.Border outline.Parent=overlay
 -- Overlay never handles object selection or wheel input. Those events belong
 -- to the underlying preview; only visible resize knobs accept pointer input.
 if selectedIds and selectedIds[id] then
  decoratedSelection[id]=true
  makeSelectionHandles(id,overlay,extent)
 end
end
repaint=function()
 if not scene or not scene.Parent then return end
 previewGeneration+=1
 overlayUpdateQueue={}
 overlayUpdatePending=false
 -- FT-EDITOR-004: Never destroy the persistent UIScale when rebuilding previews.
 -- Before this fix every edit/load destroyed zoomScale; changing zoom afterwards had no visual effect.
 for _,child in ipairs(scene:GetChildren()) do
  if child~=zoomScale and not child:IsA("UIStroke") then child:Destroy() end
 end
 if zoomScale and zoomScale.Parent==scene then zoomScale.Scale=zoom end
 proxyById={}
 overlayById={}
 decoratedSelection={}
 local rootNode
 for _,n in pairs(nodes or {}) do if not n.parent then rootNode=n break end end
 if not rootNode then
  if emptyHint then emptyHint.Visible=true end
  if renderLayers then renderLayers() end
  if renderInspector then renderInspector() end
  return
 end
 if emptyHint then emptyHint.Visible=false end
 local backdrop=make("Frame",{Name="FT_CanvasBackdrop",Size=UDim2.fromScale(1,1),BackgroundColor3=ink.bg,BorderSizePixel=0,Active=true},scene)
 backdrop.InputBegan:Connect(function(input)
  if beginCanvasDraw then beginCanvasDraw(input) end
 end)
 for _,child in ipairs(childrenOf(rootNode.id)) do renderNode(child.id,scene,viewportSize,0) end
 if renderLayers then renderLayers() end
 if renderInspector then renderInspector() end
end
local function apply()
 if not currentRoot or not currentRoot.Parent or not nodes then return end
 if not isDirty() then notice(tr("Изменений нет","No changes to apply")) return end
 
 for id,originalProps in pairs(baseline) do
  local n=nodes[id]
  local obj=(n and n.original) or originalRefs[id]
  if obj then
   if not obj.Parent or (originalParents[id] and obj.Parent~=originalParents[id]) or not sameProps(readProps(obj),originalProps) then
    notice(tr("Объект изменён в Studio. Нажми «Сбросить» и повтори правки.","Object changed in Studio. Reset and edit again."))
    return
   end
  end
 end
 local count=0
 local function applyProps(obj,props)
  props=supportedProps(obj.ClassName,props)
  for _,key in ipairs(copyKeys) do
   local v=props[key]
   if v~=nil then
    local ok,problem=pcall(function() obj[key]=v end)
    if not ok then error("Property apply failed on "..obj:GetFullName().." ["..key.."]: "..tostring(problem)) end
   end
  end
  if props.CornerRadius then
   local corner=obj:FindFirstChildOfClass("UICorner") or Instance.new("UICorner")
   corner.CornerRadius=props.CornerRadius corner.Parent=obj
  end
  if props.StrokeColor then
   local stroke=obj:FindFirstChildOfClass("UIStroke") or Instance.new("UIStroke")
   stroke.Color=props.StrokeColor stroke.Thickness=props.StrokeThickness or 1 stroke.Parent=obj
  end
 end
 -- Validate every removed node as part of an explicit modelled subtree.
 -- Only top-level removed roots are destroyed; never delete descendants twice.
 local removed={}
 for id in pairs(baseline) do if not nodes[id] then removed[id]=true end end
 for id in pairs(removed) do
  local original=originalRefs[id]
  if original and original.Parent then
   for _,child in ipairs(original:GetChildren()) do
    if not (child:IsA("UICorner") or child:IsA("UIStroke") or child:IsA("UIGradient")) then
     local known=false
     for childId in pairs(removed) do
      if originalRefs[childId]==child then known=true break end
     end
     if not known then
      notice("Apply blocked: unmodelled child "..child.ClassName.." ("..child.Name..").")
      return
     end
    end
   end
  end
 end
 -- Preflight setters on detached instances before touching StarterGui.
 -- An error here cannot leave a partly written live GUI.
 for id,n in pairs(nodes) do
  if n.parent then
   local candidate=Instance.new(n.class)
   n.props=supportedProps(n.class,n.props)
   for _,key in ipairs(copyKeys) do
    local value=n.props[key]
    if value~=nil then
     local ok,problem=pcall(function() candidate[key]=value end)
     if not ok then
      candidate:Destroy()
      warn("ForgeTools GUI Editor preflight "..tostring(n.props.Name).." ["..key.."]: "..tostring(problem))
      notice(tr("Проверка свойств не пройдена. См. Output.","Property validation failed. See Output."))
      return
     end
    end
   end
   candidate:Destroy()
  end
 end
 -- Studio undo/redo: use the modern recording API. Any unexpected Apply error is reported.
 local recording=History:TryBeginRecording("ForgeToolsGUIEditorApply","ForgeTools · Apply GUI edits")
 if not recording then
  notice(tr("Studio занята другой записью или запущен Play Test. Применение отменено.","Studio is busy or in Play Test. Apply cancelled."))
  return
 end
 local success,problem=xpcall(function()
  local created={}
  local function getOrCreate(id)
   local n=nodes[id]
   if not n then return nil end
   if n.original then
    local expectedParent=n.parent and getOrCreate(n.parent)
    if expectedParent and n.original.Parent~=expectedParent then n.original.Parent=expectedParent end
    return n.original
   end
   if created[id] then return created[id] end
   local parent=n.parent and getOrCreate(n.parent)
   if not parent then error("Missing parent for node "..tostring(id)) end
   local obj=Instance.new(n.class)
   local source=n.componentSourceId and nodes[n.componentSourceId]
   if source and source.original then
    -- Clone only approved UI decorators; never clone scripts or user GuiObjects.
    copyPreviewComponents(source.original,obj)
   end
   obj.Parent=parent
   created[id]=obj
   return obj
  end
  local ids={}
  for id,n in pairs(nodes) do if n.parent then table.insert(ids,id) end end
  table.sort(ids)
  for _,id in ipairs(ids) do
   local n=nodes[id]
   local obj=getOrCreate(id)
   if not obj then error("Cannot construct node "..tostring(id)) end
   applyProps(obj,n.props)
   count+=1
  end
  for id in pairs(removed) do
   local object=originalRefs[id]
   local ancestorRemoved=false
   local ancestor=object and object.Parent
   while ancestor do
    for otherId in pairs(removed) do
     if originalRefs[otherId]==ancestor then ancestorRemoved=true break end
    end
    if ancestorRemoved then break end
    ancestor=ancestor.Parent
   end
   if object and object.Parent and not ancestorRemoved then object:Destroy() end
  end
 end,debug.traceback)
 if not success then
  History:FinishRecording(recording,Enum.FinishRecordingOperation.Cancel)
  warn("ForgeTools GUI Editor Apply aborted: "..tostring(problem))
  notice(tr("Ошибка применения. Проверь Output и исходный GUI: возможны частичные изменения.","Apply failed. Check Output and source GUI for partial changes."))
  return
 end
 History:FinishRecording(recording,Enum.FinishRecordingOperation.Commit)
 local newRoot=currentRoot
 importTree(newRoot)
 originalRefs={} originalParents={}
 for id,n in pairs(nodes) do
  if n.original then originalRefs[id]=n.original originalParents[id]=n.original.Parent end
 end
 changed() repaint()
 refreshGuiLinkState()
 clearDraft()
 notice(tr("Изменения сохранены в Roblox Studio. Объектов обработано: ","Applied to Roblox Studio. Objects updated: ")..count)
end

local function load(root)
 importTree(root)
 originalRefs={} originalParents={}
 for id,n in pairs(nodes) do if n.original then originalRefs[id]=n.original originalParents[id]=n.original.Parent end end
 changed() repaint()
 notice(tr("Черновик готов. Все правки сохраняются только по кнопке «Применить».","Draft ready. Click Apply to update Roblox Studio."))
 promptDraft()
end
local function reset()
 if not currentRoot or not currentRoot.Parent then return end
 clearDraft()
 load(currentRoot)
 notice(tr("Черновик сброшен. Оригиналы не менялись.","Draft discarded. Originals unchanged."))
end
local function alignSelection(direction)
 local list=multiNodes()
 if #list&lt;2 then notice(tr("Выдели хотя бы 2 слоя через Ctrl + клик","Select at least two layers with Ctrl + click")) return end
 local parentId=list[1].parent
 for _,item in ipairs(list) do
  if item.parent~=parentId then notice(tr("Выравнивать можно только элементы одного родителя","Alignment requires the same parent")) return end
 end
 local container=nodes[parentId]
 local containerSize=container and container._renderSize or viewportSize
 local loX,loY,hiX,hiY=math.huge,math.huge,-math.huge,-math.huge
 for _,item in ipairs(list) do
  local pos,size=nodeRect(item,containerSize)
  loX=math.min(loX,pos.X) loY=math.min(loY,pos.Y)
  hiX=math.max(hiX,pos.X+size.X) hiY=math.max(hiY,pos.Y+size.Y)
 end
 mutate(function()
  for _,item in ipairs(list) do
   local pos,size=nodeRect(item,containerSize)
   local x,y=pos.X,pos.Y
   if direction=="left" then x=loX end
   if direction=="center" then x=(loX+hiX-size.X)/2 end
   if direction=="right" then x=hiX-size.X end
   if direction=="top" then y=loY end
   if direction=="middle" then y=(loY+hiY-size.Y)/2 end
   if direction=="bottom" then y=hiY-size.Y end
   local p=item.props
   p.Position=UDim2.new(p.Position.X.Scale,math.floor(x+size.X*p.AnchorPoint.X-containerSize.X*p.Position.X.Scale+.5),p.Position.Y.Scale,math.floor(y+size.Y*p.AnchorPoint.Y-containerSize.Y*p.Position.Y.Scale+.5))
  end
 end)
 notice(tr("Элементы выровнены в черновике","Aligned in draft"))
end
local function distributeVertical()
 local list=multiNodes()
 if #list&lt;3 then notice(tr("Выдели минимум 3 элемента","Select at least three elements")) return end
 local parentId=list[1].parent
 for _,item in ipairs(list) do if item.parent~=parentId then notice(tr("Нужен один родитель","Elements must share a parent")) return end end
 local parent=nodes[parentId]
 local sz=parent and parent._renderSize or viewportSize
 table.sort(list,function(a,b) local pa=nodeRect(a,sz) local pb=nodeRect(b,sz) return pa.Y&lt;pb.Y end)
 local top=nodeRect(list[1],sz)
 local bottom,bottomSize=nodeRect(list[#list],sz)
 local total=0
 for _,item in ipairs(list) do local _,extent=nodeRect(item,sz) total+=extent.Y end
 local gap=(bottom.Y+bottomSize.Y-top.Y-total)/(#list-1)
 if gap&lt;0 then notice(tr("Для распределения не хватает места","Not enough room to distribute")) return end
 mutate(function()
  local cursor=top.Y
  for _,item in ipairs(list) do
   local p=item.props
   local _,extent=nodeRect(item,sz)
   local offset=cursor+extent.Y*p.AnchorPoint.Y-sz.Y*p.Position.Y.Scale
   p.Position=UDim2.new(p.Position.X.Scale,p.Position.X.Offset,p.Position.Y.Scale,math.floor(offset+.5))
   cursor+=extent.Y+gap
  end
 end)
end
local function nudgeSelection(dx,dy)
 local list=multiNodes()
 if #list==0 then return end
 mutate(function()
  for _,item in ipairs(list) do
   local p=item.props
   p.Position=UDim2.new(p.Position.X.Scale,p.Position.X.Offset+dx,p.Position.Y.Scale,p.Position.Y.Offset+dy)
  end
 end)
end
local function newScreenGui()
 if dirty then notice(tr("Сначала Применить или Сбросить","Apply or Discard first")) return end
 local starterGui=game:GetService("StarterGui")
 local recording=History:TryBeginRecording("ForgeToolsNewScreenGui","ForgeTools · New Screen GUI")
 if not recording then notice(tr("Невозможно создать GUI во время Play Test или другой записи.","Cannot create GUI during Play Test or another recording.")) return end
 local success,err=pcall(function()
  local root=Instance.new("ScreenGui")
  root.Name="ForgeToolsScreenGui"
  root.ResetOnSpawn=false
  root.Parent=starterGui
  History:FinishRecording(recording,Enum.FinishRecordingOperation.Commit)
  Selection:Set({root})
  load(root)
 end)
 if not success then
  if History:IsRecordingInProgress(recording) then History:FinishRecording(recording,Enum.FinishRecordingOperation.Cancel) end
  notice(tr("Не удалось создать GUI. См. Output.","Could not create GUI; see Output."))
  warn("ForgeTools New ScreenGui: "..tostring(err))
 end
end
local openGuiPicker
local function loadSelection()
 if openGuiPicker then openGuiPicker() end
end
local function sectionTitle(parent,text)
 local h=label(parent,text,11,true)
 h.Size=UDim2.new(1,-18,0,25)
 h.TextColor3=ink.blue
 h.ZIndex=43
 return h
end
local function menuGroup(parent,name,items)
 sectionTitle(parent,name)
 local r
 for i,entry in ipairs(items) do
  if i%2==1 then r=row(parent,33) end
  local b=btn(r,entry[1],entry[2],124)
  b.ZIndex=43
  b.Size=UDim2.new(.5,-5,0,29)
 end
end
local function createToolsMenu(parent)
 local overlay=make("CanvasGroup",{Name="AdvancedTools",Visible=false,
  AnchorPoint=Vector2.new(0,1),Size=UDim2.fromOffset(202,0),
  BackgroundColor3=ink.pane,BorderSizePixel=0,
  GroupTransparency=1,ZIndex=1600,ClipsDescendants=true},parent)
 make("UICorner",{CornerRadius=UDim.new(0,8)},overlay)
 make("UIStroke",{Color=Color3.fromRGB(81,85,96),Thickness=1},overlay)
 local entries={
  {"ScrollingFrame",function() stageCreate("ScrollingFrame") end},
  {"ViewportFrame",function() stageCreate("ViewportFrame") end},
  {"CanvasGroup",function() stageCreate("CanvasGroup") end},
  {"Choose GUI",loadSelection},
 }
 local expanded=8+#entries*34
 local anim
 local function close()
  if not overlay.Visible then return end
  if anim then anim:Cancel() end
  anim=TweenService:Create(overlay,TweenInfo.new(.15,Enum.EasingStyle.Quad,Enum.EasingDirection.Out),{Size=UDim2.fromOffset(202,0),GroupTransparency=1})
  anim:Play()
  local existing=anim
  existing.Completed:Connect(function() if anim==existing then overlay.Visible=false end end)
 end
 local function open()
  if anim then anim:Cancel() end
  overlay.Size=UDim2.fromOffset(202,0)
  overlay.GroupTransparency=1
  overlay.Visible=true
  anim=TweenService:Create(overlay,TweenInfo.new(.18,Enum.EasingStyle.Quart,Enum.EasingDirection.Out),{Size=UDim2.fromOffset(202,expanded),GroupTransparency=0})
  anim:Play()
 end
 for i,entry in ipairs(entries) do
  local b=make("TextButton",{Name="Create_"..entry[1],Text=entry[1],
   Position=UDim2.fromOffset(8,5+(i-1)*34),Size=UDim2.new(1,-16,0,32),
   BackgroundTransparency=1,TextXAlignment=Enum.TextXAlignment.Left,
   TextColor3=ink.text,TextSize=12,Font=Enum.Font.Gotham,
   AutoButtonColor=false,BorderSizePixel=0,ZIndex=1602},overlay)
  make("UICorner",{CornerRadius=UDim.new(0,5)},b)
  b.MouseEnter:Connect(function() TweenService:Create(b,TweenInfo.new(.12),{BackgroundTransparency=.72}):Play() end)
  b.MouseLeave:Connect(function() TweenService:Create(b,TweenInfo.new(.14),{BackgroundTransparency=1}):Play() end)
  b.MouseButton1Click:Connect(function() close() entry[2]() end)
 end
 local function toggle() if overlay.Visible then close() else open() end end
 return toggle,overlay,close,open
end
function M.refreshCanvas()
 if not scene or not scene.Parent then return end
 scene.Size=UDim2.fromOffset(viewportSize.X,viewportSize.Y)
 if viewportController then
  viewportController.size=viewportSize
  zoom=viewportController:zoomTo(zoom)
 elseif zoomScale then zoomScale.Scale=zoom end
 if zoomReadout then zoomReadout.Text=formatPercent() end
 if viewportReadout then viewportReadout.Text=tostring(math.floor(viewportSize.X)).." × "..tostring(math.floor(viewportSize.Y)) end
 repaint()
end
setZoom=function(value)
 if viewportController then
  zoom=viewportController:zoomTo(value)
 else zoom=math.clamp(value,0.1,2.5) end
 M.refreshCanvas()
end
fitCanvas=function()
 if not viewportController then return end
 zoom=viewportController:fit(64)
 M.refreshCanvas()
end
setViewport=function(w,h)
 w=tonumber(w) h=tonumber(h)
 if not w or not h or w&lt;200 or h&lt;200 or w&gt;7680 or h&gt;4320 then
  notice(tr("Размер экрана: от 200×200 до 7680×4320","Screen size: 200×200 to 7680×4320")) return
 end
 viewportSize=Vector2.new(math.floor(w),math.floor(h))
 if viewportController then zoom=viewportController:setSize(viewportSize.X,viewportSize.Y) end
 M.refreshCanvas()
end
function M.open(info)
 context=info or {}
 if dock and dock.Parent then
  dock.Enabled=not dock.Enabled
  if dock.Enabled and not dirty then
   local root=findRoot()
   if root and root~=currentRoot then load(root) else repaint() end
   promptDraft()
  end
  return
 end
 local plugin=context.plugin
 editorCustom=loadCustomShell(plugin)
 local okTheme,savedTheme=pcall(function() return plugin:GetSetting(EDITOR_THEME_KEY) end)
 if okTheme and type(savedTheme)=="string" and (editorThemePresets[savedTheme] or (savedTheme=="custom" and editorCustom)) then
  setEditorShellTheme(savedTheme,false)
 else
  setEditorShellTheme("forge",false)
 end
 if not plugin then return end
 pluginMouse=plugin:GetMouse()
 setCursorIcon(cursorIcons.default)
 dock=plugin:CreateDockWidgetPluginGui("UIToolsGUIEditorDraft",DockWidgetPluginGuiInfo.new(Enum.InitialDockState.Float,true,false,1250,850,940,680))
 dock.Title=tr("ForgeTools · UI Editor","ForgeTools · UI Editor")
 local background=make("Frame",{Size=UDim2.fromScale(1,1),BackgroundColor3=ink.bg,BorderSizePixel=0},dock)
 canvas=background
 -- Intentional breathing room: header is 46px, canvas occupies nearly all available space.
 local header=make("Frame",{Size=UDim2.new(1,0,0,47),BackgroundColor3=ink.pane,BorderSizePixel=0},background)
 make("Frame",{Position=UDim2.new(0,0,1,-1),Size=UDim2.new(1,0,0,1),BackgroundColor3=ink.border,BorderSizePixel=0},header)
 local brand=label(header,"◈  ForgeTools  /  UI Editor",14)
 brand.Font=Enum.Font.GothamMedium
 brand.Position=UDim2.fromOffset(16,10)
 brand.Size=UDim2.fromOffset(310,28)
 local topRight=make("Frame",{AnchorPoint=Vector2.new(1,.5),Position=UDim2.new(1,-14,.5,0),Size=UDim2.fromOffset(274,36),BackgroundTransparency=1},header)
 make("UIListLayout",{FillDirection=Enum.FillDirection.Horizontal,HorizontalAlignment=Enum.HorizontalAlignment.Right,VerticalAlignment=Enum.VerticalAlignment.Center,Padding=UDim.new(0,6)},topRight)
 zoomReadout=btn(topRight,formatPercent(),function() fitCanvas() end,64)
 zoomReadout.Name="ZoomReadoutFit"
 zoomReadout:SetAttribute("Hint","Wheel zoom / click to fit")
 viewportReadout=label(topRight,"",11,true)
 viewportReadout.Size=UDim2.fromOffset(125,28)
 local helpDialog=make("Frame",{Name="UIEditorHelp",Visible=false,AnchorPoint=Vector2.new(.5,.5),Position=UDim2.fromScale(.5,.5),Size=UDim2.fromOffset(475,284),BackgroundColor3=ink.pane,BorderSizePixel=0,ZIndex=1800},background)
 make("UICorner",{CornerRadius=UDim.new(0,12)},helpDialog)
 local helpCopy=make("TextLabel",{Text=tr("УПРАВЛЕНИЕ UI РЕДАКТОРОМ\n\nЛКМ — выбрать объект\nЛКМ по маркеру — изменить размер\nПробел + ЛКМ — перемещать холст\nСКМ — перемещать холст\nКолесо — масштаб\nПКМ — дополнительные действия\nCtrl+Z / Ctrl+Y — отмена / повтор\nDelete — удалить\nEsc — закрыть меню", "UI EDITOR CONTROLS\n\nLMB — select object\nLMB on handle — resize\nSpace + LMB — pan canvas\nMMB — pan canvas\nWheel — zoom\nRMB — actions\nCtrl+Z / Ctrl+Y — undo / redo\nDelete — delete\nEsc — close popup"),Position=UDim2.fromOffset(20,16),Size=UDim2.new(1,-40,1,-65),BackgroundTransparency=1,TextWrapped=true,TextXAlignment=Enum.TextXAlignment.Left,TextYAlignment=Enum.TextYAlignment.Top,Font=Enum.Font.Gotham,TextSize=14,TextColor3=ink.text,ZIndex=1801},helpDialog)
 local helpClose=btn(helpDialog,tr("Закрыть","Close"),function() helpDialog.Visible=false end,100)
 helpClose.Position=UDim2.new(1,-116,1,-40) helpClose.BackgroundColor3=ink.card helpClose.ZIndex=1801
  -- Recolor only editor chrome at runtime. The canvas and document GUI are excluded.
  editorShellApply=function(_before)
   if not dock or not dock.Parent then return end
   for _,obj in ipairs(dock:GetDescendants()) do
    -- Do not touch the canvas or any cloned / imported user GUI.
    if not (workScroll and obj:IsDescendantOf(workScroll))
     and not (scene and obj:IsDescendantOf(scene)) then
     for _,property in ipairs({"BackgroundColor3","TextColor3","ImageColor3","BorderColor3","Color"}) do
      local role=obj:GetAttribute("FTShellRole_"..property)
      if role and ink[role] then
       pcall(function() obj[property]=ink[role] end)
      end
     end
    end
   end
  end
 local showTooltips=true
 local iconTip
 local settingsDialog=make("Frame",{Name="UIEditorSettings",Visible=false,AnchorPoint=Vector2.new(.5,.5),Position=UDim2.fromScale(.5,.5),Size=UDim2.fromOffset(350,328),BackgroundColor3=ink.pane,BorderSizePixel=0,ZIndex=1800},background)
 make("UICorner",{CornerRadius=UDim.new(0,10)},settingsDialog)
 make("UIStroke",{Color=ink.border,Thickness=1},settingsDialog)
 local settingsHeading=label(settingsDialog,"EDITOR SETTINGS",14)
 settingsHeading.Position=UDim2.fromOffset(15,10) settingsHeading.ZIndex=1801
 local settingsTips
 settingsTips=btn(settingsDialog,"Tooltips: On",function()
  showTooltips=not showTooltips
  settingsTips.Text=showTooltips and "Tooltips: On" or "Tooltips: Off"
  if not showTooltips and iconTip then iconTip.Visible=false end
 end,155,ink.card)
 settingsTips.Position=UDim2.fromOffset(16,49) settingsTips.ZIndex=1801
 local settingsFit=btn(settingsDialog,"Fit canvas",function() fitCanvas() end,155,ink.card)
 settingsFit.Position=UDim2.fromOffset(177,49) settingsFit.ZIndex=1801
 local settingsZoom=btn(settingsDialog,"Zoom 100%",function() setZoom(1) end,155,ink.card)
 settingsZoom.Position=UDim2.fromOffset(16,86) settingsZoom.ZIndex=1801
 local settingsClose=btn(settingsDialog,"Close",function() settingsDialog.Visible=false end,100,ink.card)
 local settingsPan=btn(settingsDialog,"Zoom 50%",function() setZoom(.5) end,155,ink.card)
 settingsPan.Position=UDim2.fromOffset(177,86) settingsPan.ZIndex=1801
 local settingsReset=btn(settingsDialog,"Zoom 75%",function() setZoom(.75) end,155,ink.card)
 settingsReset.Position=UDim2.fromOffset(16,124) settingsReset.ZIndex=1801
 local settingsHelp=btn(settingsDialog,"Keyboard shortcuts",function() settingsDialog.Visible=false helpDialog.Visible=true end,155,ink.card)
 settingsHelp.Position=UDim2.fromOffset(177,124) settingsHelp.ZIndex=1801
  local themeHeading=label(settingsDialog,"SHELL THEME  ·  LIVE PREVIEW",11,true)
  themeHeading.Position=UDim2.fromOffset(16,162) themeHeading.ZIndex=1801
  local presetNames={{"Forge", "forge"},{"Steel", "steel"},{"Emerald", "emerald"},{"Violet", "violet"}}
  local presetButtons={}
  local function refreshPresetButtons()
   for _,entry in ipairs(presetButtons) do
    local active=entry.name==editorThemeName
    entry.button.BackgroundColor3=active and ink.blue or ink.card
    entry.button:SetAttribute("SelectedBaseColor",active and ink.blue or ink.card)
    entry.button.TextColor3=ink.text
   end
  end
  for index,entry in ipairs(presetNames) do
   local themeBtn=btn(settingsDialog,entry[1],function()
    setEditorShellTheme(entry[2],true)
    refreshPresetButtons()
   end,76,ink.card)
   themeBtn.Position=UDim2.fromOffset(16+(index-1)*80,187)
   themeBtn.Size=UDim2.fromOffset(76,30)
   themeBtn.ZIndex=1801
   -- Small, honest palette swatch: discrete colors, not a fake gradient.
   local palette=editorThemePresets[entry[2]]
   if palette then
    for slot,role in ipairs({"bg","pane","card","blue"}) do
     local swatch=make("Frame",{Name="ThemeSwatch"..slot,Size=UDim2.new(.25,-2,0,3),Position=UDim2.new((slot-1)*.25,1,1,-5),BackgroundColor3=palette[role],BorderSizePixel=0,ZIndex=1803},themeBtn)
     swatch:SetAttribute("FTShellRole_BackgroundColor3",nil)
    end
   end
   table.insert(presetButtons,{button=themeBtn,name=entry[2]})
  end
  local themeReset=btn(settingsDialog,"Reset to Forge",function()
   setEditorShellTheme("forge",true)
   refreshPresetButtons()
  end,155,ink.card)
  themeReset.Position=UDim2.fromOffset(16,228) themeReset.ZIndex=1801
  -- Advanced shell theme: five RGB hex tokens; input affects editor chrome only.
  settingsDialog.Size=UDim2.fromOffset(370,478)
  local colorNames={{"Accent","blue"},{"Background","bg"},{"Panels","pane"},{"Cards","card"},{"Borders","border"}}
  local colorFields={}
  for index,entry in ipairs(colorNames) do
   local y=266+(index-1)*32
   local cap=label(settingsDialog,entry[1],11,true)
   cap.Position=UDim2.fromOffset(16,y) cap.Size=UDim2.fromOffset(132,25) cap.ZIndex=1801
   local field=make("TextBox",{Name="ThemeHex_"..entry[2],Size=UDim2.fromOffset(135,26),Position=UDim2.fromOffset(154,y),BackgroundColor3=ink.card,TextColor3=ink.text,PlaceholderColor3=ink.muted,ClearTextOnFocus=false,Text="#"..ink[entry[2]]:ToHex(),TextSize=12,Font=Enum.Font.Code,ZIndex=1801,BorderSizePixel=0},settingsDialog)
   make("UICorner",{CornerRadius=UDim.new(0,5)},field)
   colorFields[entry[2]]=field
  end
  local applyCustom=btn(settingsDialog,"Apply custom colors",function()
   local newColors={}
   local saved={}
   for _,entry in ipairs(colorNames) do
    local key=entry[2] local value=colorFields[key].Text
    local parsed=fromHex(value)
    if not parsed then
     colorFields[key].Text="#"..ink[key]:ToHex()
     return
    end
    newColors[key]=parsed
    saved[key]="#"..parsed:ToHex()
   end
   editorCustom=newColors
   pcall(function() plugin:SetSetting(EDITOR_CUSTOM_KEY,saved) end)
   setEditorShellTheme("custom",true)
   refreshPresetButtons()
  end,170,ink.blue)
  applyCustom.Position=UDim2.fromOffset(16,433) applyCustom.ZIndex=1801
  local themeGradient=btn(settingsDialog,"Accent gradient",function()
   local current=editorThemeName
   -- Preview gradient is restricted to the editor Settings action button.
   local existing=applyCustom:FindFirstChild("FTThemeGradient")
   if existing then existing:Destroy() else
    local grad=Instance.new("UIGradient") grad.Name="FTThemeGradient"
    grad.Color=ColorSequence.new(ink.blue,ink.card)
    grad.Rotation=0 grad.Parent=applyCustom
   end
  end,152,ink.card)
  themeGradient.Position=UDim2.fromOffset(202,433) themeGradient.ZIndex=1801
  settingsClose.Position=UDim2.fromOffset(247,228)
  refreshPresetButtons()
 settingsClose.ZIndex=1801
 local settingsToggle=btn(topRight,"⚙",function() settingsDialog.Visible=not settingsDialog.Visible helpDialog.Visible=false end,30)
 settingsToggle.Size=UDim2.fromOffset(30,28) settingsToggle.LayoutOrder=-2
 local helpToggle=btn(topRight,"?",function() helpDialog.Visible=not helpDialog.Visible settingsDialog.Visible=false end,30)
 helpToggle.Size=UDim2.fromOffset(30,28)
 helpToggle.LayoutOrder=-1

 for _,modal in ipairs({helpDialog,settingsDialog}) do
  for _,child in ipairs(modal:GetDescendants()) do
   if child:IsA("GuiObject") then child.ZIndex=math.max(1801,child.ZIndex) end
  end
 end
 local content=make("Frame",{Position=UDim2.fromOffset(0,47),Size=UDim2.new(1,0,1,-76),BackgroundTransparency=1,ClipsDescendants=true},background)
 local left=make("Frame",{Size=UDim2.new(0,226,1,0),BackgroundColor3=ink.pane,BorderSizePixel=0},content)
 make("Frame",{Position=UDim2.new(1,-1,0,0),Size=UDim2.new(0,1,1,0),BackgroundColor3=ink.border,BorderSizePixel=0},left)
 local leftTitle=label(left,tr("Слои","Layers"),13)
 leftTitle.Font=Enum.Font.GothamMedium
 leftTitle.Position=UDim2.fromOffset(13,13)
 local sideHint=label(left,tr("Ctrl + клик · выделить несколько","Ctrl + click · multi-select"),10,true)
 sideHint.Position=UDim2.new(0,10,1,-42)
 layerList=make("ScrollingFrame",{Position=UDim2.fromOffset(7,45),Size=UDim2.new(1,-14,1,-100),BackgroundTransparency=1,ScrollBarThickness=3,CanvasSize=UDim2.fromOffset(0,0),AutomaticCanvasSize=Enum.AutomaticSize.Y},left)
 -- Link ScreenGui directly from StarterGui; no Explorer selection is required.
 local guiPicker=make("Frame",{Name="ForgeToolsGuiPicker",Visible=false,AnchorPoint=Vector2.new(0,1),Position=UDim2.new(0,8,1,-40),Size=UDim2.new(1,-16,0,218),BackgroundColor3=ink.card,BorderSizePixel=0,ZIndex=60},left)
 make("UICorner",{CornerRadius=UDim.new(0,7)},guiPicker)
 local pickerTitle=label(guiPicker,tr("Выбери интерфейс","Choose GUI"),12)
 pickerTitle.Position=UDim2.fromOffset(10,3)
 pickerTitle.ZIndex=61
 local pickerScroll=make("ScrollingFrame",{Position=UDim2.fromOffset(6,35),Size=UDim2.new(1,-12,1,-42),BackgroundTransparency=1,ScrollBarThickness=3,CanvasSize=UDim2.fromOffset(0,0),AutomaticCanvasSize=Enum.AutomaticSize.Y,ZIndex=61},guiPicker)
 stack(pickerScroll,4)
 local function toggleGuiPicker()
  if guiPicker.Visible then guiPicker.Visible=false return end
  pickerTitle.Text=currentRoot and "Linked GUI" or "Choose GUI"
  clear(pickerScroll)
  stack(pickerScroll,4)
  local roots={}
  -- Browse editable GUI assets without requiring Studio Explorer selection.
  -- Avoid CoreGui/PluginGui and runtime PlayerGui to prevent editing live instances.
  for _,serviceName in ipairs({"StarterGui","ReplicatedStorage","ReplicatedFirst","StarterPlayer","Workspace","ServerStorage"}) do
   local ok,container=pcall(function() return game:GetService(serviceName) end)
   if ok and container then
    for _,child in ipairs(container:GetDescendants()) do
     if child:IsA("ScreenGui") then table.insert(roots,child) end
    end
   end
  end
  table.sort(roots,function(a,b) return a:GetFullName()&lt;b:GetFullName() end)
  if #roots==0 then
   local empty=label(pickerScroll,tr("ScreenGui в StarterGui пока нет","No ScreenGui in StarterGui"),11,true)
   empty.Size=UDim2.new(1,-4,0,52)
   empty.TextWrapped=true empty.ZIndex=62
  end
  pickerTitle.Text=currentRoot and "Linked GUI" or "Choose GUI"
  for _,root in ipairs(roots) do
   local action=btn(pickerScroll,root:GetFullName(),function()
    if dirty then
     notice(tr("Сначала Применить или Сбросить текущие изменения","Apply or Discard current edits first"))
     return
    end
    if not root.Parent then return end
    guiPicker.Visible=false
    load(root)
   end,158)
   action.Name="Link_"..root.Name
   if root==currentRoot then
    action.BackgroundColor3=ink.blue
    action.TextColor3=ink.text
    action.Text="✓  "..root:GetFullName()
   end
   action.Size=UDim2.new(1,-6,0,30)
   action.ZIndex=62
   action.TextTruncate=Enum.TextTruncate.AtEnd
   if root==currentRoot then
    local selectedBlue=ink.blue
    action.BackgroundColor3=selectedBlue
    action:SetAttribute("SelectedBaseColor",selectedBlue)
    action.TextColor3=ink.text
   end
  end
  guiPicker.Visible=true
 end
 openGuiPicker=toggleGuiPicker
 local linked=btn(left,tr("Выбрать GUI","Choose GUI"),toggleGuiPicker,170,ink.card)
 refreshGuiLinkState=function()
  if linked and linked.Parent then linked.Text=(currentRoot and currentRoot.Parent) and ("Linked: "..currentRoot.Name) or "Choose GUI" end
  if pickerTitle and pickerTitle.Parent then pickerTitle.Text=(currentRoot and currentRoot.Parent) and "Linked GUI" or "Choose GUI" end
 end
 task.defer(refreshGuiLinkState)
 linked.Position=UDim2.new(0,10,1,-33)
 linked.Size=UDim2.new(1,-20,0,26)
 local right=make("Frame",{Position=UDim2.new(1,-246,0,0),Size=UDim2.new(0,246,1,0),BackgroundColor3=ink.pane,BorderSizePixel=0},content)
 make("Frame",{Size=UDim2.new(0,1,1,0),BackgroundColor3=ink.border,BorderSizePixel=0},right)
 local rightTitle=label(right,tr("Свойства","Properties"),13)
 rightTitle.Font=Enum.Font.GothamMedium
 rightTitle.Position=UDim2.fromOffset(13,13)
 inspectorPanelGroup=make("CanvasGroup",{Name="InspectorPanelMotion",Position=UDim2.fromOffset(9,44),Size=UDim2.new(1,-18,1,-52),BackgroundTransparency=1,GroupTransparency=0,ClipsDescendants=true},right)
 properties=make("ScrollingFrame",{Position=UDim2.fromOffset(0,0),Size=UDim2.fromScale(1,1),BackgroundTransparency=1,ScrollBarThickness=3,CanvasSize=UDim2.fromOffset(0,0),AutomaticCanvasSize=Enum.AutomaticSize.Y},inspectorPanelGroup)
 local middle=make("Frame",{Position=UDim2.fromOffset(226,0),Size=UDim2.new(1,-472,1,0),BackgroundColor3=ink.bg,BorderSizePixel=0},content)
 workScroll=make("Frame",{Name="CanvasViewport",Size=UDim2.fromScale(1,1),BackgroundTransparency=1,BorderSizePixel=0,ClipsDescendants=true,Active=true},middle)
 local function pointerInCanvas(mouse)
  if not workScroll or not workScroll.Parent then return false end
  local pos,sz=workScroll.AbsolutePosition,workScroll.AbsoluteSize
  return mouse.X&gt;=pos.X and mouse.Y&gt;=pos.Y and mouse.X&lt;pos.X+sz.X and mouse.Y&lt;pos.Y+sz.Y
 end
 -- FT-EDITOR-008: consume wheel in the plugin viewport itself and via
 -- UserInputService fallback. Studio PluginGui focus can prevent global wheel events.
 -- Deduplicate when the same gesture reaches more than one listener.
 local lastWheelAt=-1
 local lastWheelInput=nil
 local function handleWheel(input)
  if popupIsBlocking() then return end
  if not dock or not dock.Enabled or not viewportController then return end
  if moving then
   -- Ignore wheel while a genuine drag is active; recover only a stale drag.
   if UIS:IsMouseButtonPressed(Enum.UserInputType.MouseButton1) then return end
   if cancelActiveGesture then cancelActiveGesture() end
  end
  local pointer=mousePointer()
  -- MouseWheel InputObject carries the pointer location in plugin GUI events.
  -- Fall back to global cursor when Studio reports (0,0).
  if input.Position.X~=0 or input.Position.Y~=0 then
   local eventPointer=Vector2.new(input.Position.X,input.Position.Y)
   if viewportController:contains(eventPointer) then pointer=eventPointer end
  end
  if not viewportController:contains(pointer) then return end
  -- After changing a property the inspector TextBox can retain keyboard focus.
  -- Do not gate mouse wheel over the canvas on that unrelated focus state.
  local magnitude=input.Position.Z
  if magnitude==0 then return end
  local now=os.clock()
  -- Studio may reuse InputObject references for successive wheel ticks.
  -- Deduplicate only *simultaneous* dispatches, never a later wheel movement.
  if now-lastWheelAt&lt;0.008 then return end
  lastWheelInput=input
  lastWheelAt=now
  local oldZoom=zoom
  zoom=viewportController:zoomTo(zoom*(magnitude&gt;0 and 1.13 or 1/1.13),pointer)
  if zoom==oldZoom then return end
  if zoomReadout then zoomReadout.Text=formatPercent() end
  -- These UIScale nodes belong exclusively to selection handles/readout.
  -- No repaint: destroying previews during a wheel gesture cancels interactions.
  for overlayId in pairs(selectedIds or {}) do
   local outline=overlayById[overlayId]
   if outline and outline.Parent then
    for _,handle in ipairs(outline:GetChildren()) do
     if handle.Name=="FT_SelectionDimensions" or handle.Name:sub(1,10)=="FT_Resize_" then
      local scale=handle:FindFirstChildOfClass("UIScale")
      if scale then scale.Scale=math.clamp(1/zoom,1,5) end
     end
    end
    queueOverlayUpdate(overlayId)
   end
  end
 end
 wheelHandler=handleWheel
 -- FT-EDITOR-015: unified pan gesture. All pan actions modify viewport position
 -- only; staged GUI Position/Size and the undo history remain untouched.
 local panGesture=nil
 local toolBar,morePanel
 local function onEditorChrome(gui,point)
  if not gui or not gui.Parent or not gui.Visible then return false end
  local pos,size=gui.AbsolutePosition,gui.AbsoluteSize
  return point.X&gt;=pos.X and point.Y&gt;=pos.Y and point.X&lt;pos.X+size.X and point.Y&lt;pos.Y+size.Y
 end
 local function stopPan(inputType)
  if not panGesture then return end
  if inputType and panGesture.button~=inputType then return end
  local gesture=panGesture
  panGesture=nil
  setCursorIcon(activeTool=="Select" and cursorIcons.default or cursorIcons.cross)
  if gesture.inputConnection then gesture.inputConnection:Disconnect() end
  if gesture.button==Enum.UserInputType.MouseButton1 and not gesture.dragged and
     gesture.clearOnClick and nodes then
   -- A click on empty background clears selection; only dragging pans.
   selectedId=nil
   selectedIds={}
   if updateSelectionDecorations then updateSelectionDecorations() end
   if updateLayerSelection then updateLayerSelection() end
   if renderInspector then renderInspector() end
  end
 end
 local function beginPan(input)
  if popupIsBlocking() then return end
  if panGesture or not dock or not dock.Enabled or not viewportController or not viewportController:valid() then return end
  local button=input.UserInputType
  if button~=Enum.UserInputType.MouseButton1 and button~=Enum.UserInputType.MouseButton3 then return end
  if UIS:GetFocusedTextBox() or moving then return end
  local point=mousePointer()
  if not viewportController:contains(point) then return end
  for selectedNode in pairs(selectedIds or {}) do
   local overlay=overlayById[selectedNode]
   if overlay and overlay.Parent then
    for _,knob in ipairs(overlay:GetChildren()) do
     if knob:IsA("GuiButton") and knob.Visible and knob.Name:sub(1,10)=="FT_Resize_" then
      local p,q=knob.AbsolutePosition,knob.AbsoluteSize
      if point.X&gt;=p.X-4 and point.Y&gt;=p.Y-4 and point.X&lt;=p.X+q.X+4 and point.Y&lt;=p.Y+q.Y+4 then return end
     end
    end
   end
  end
  if onEditorChrome(toolBar,point) or onEditorChrome(morePanel,point) or onEditorChrome(emptyHint,point) then return end
  if button==Enum.UserInputType.MouseButton1 then
   -- Ordinary LMB pans only from empty canvas while Select is active.
   -- Space+LMB also pans over objects (like Sketch).
   local space=UIS:IsKeyDown(Enum.KeyCode.Space)
   if not space then
    if activeTool~="Select" or editorHitTest(point)~=nil then return end
   end
  end
  local gesture={button=button,start=point,last=point,dragged=false,
   clearOnClick=button==Enum.UserInputType.MouseButton1 and not UIS:IsKeyDown(Enum.KeyCode.Space)}
  panGesture=gesture
  setCursorIcon(cursorIcons.move)
  gesture.inputConnection=input.Changed:Connect(function()
   if input.UserInputState==Enum.UserInputState.End or input.UserInputState==Enum.UserInputState.Cancel then
    if panGesture==gesture then stopPan(button) end
   end
  end)
 end
 -- PluginGui may consume mouse-down before UserInputService sees it.
 panInputHandler=beginPan
 addConn(workScroll.InputBegan:Connect(beginPan))
 addConn(UIS.InputBegan:Connect(beginPan))
 addConn(UIS.InputEnded:Connect(function(input)
  if input.UserInputType==Enum.UserInputType.MouseButton1 or
     input.UserInputType==Enum.UserInputType.MouseButton3 then
   stopPan(input.UserInputType)
  end
 end))
 addConn(dock.WindowFocusReleased:Connect(function() stopPan() end))
 addConn(UIS.WindowFocusReleased:Connect(function() stopPan() end))
 local function updatePan()
  if not dock or not dock.Enabled or not viewportController or not panGesture then return end
  if moving then stopPan() return end
  local gesture=panGesture
  local point=mousePointer()
  local delta=point-gesture.last
  if not gesture.dragged and (point-gesture.start).Magnitude&lt;4 then return end
  gesture.dragged=true
  viewportController:panBy(delta)
  gesture.last=point
  for selectedNode in pairs(selectedIds or {}) do queueOverlayUpdate(selectedNode) end
 end
 panMouseMotion=updatePan
 addConn(UIS.InputChanged:Connect(function(input)
  if not dock or not dock.Enabled or not viewportController then return end
  if input.UserInputType==Enum.UserInputType.MouseMovement and panGesture then
   updatePan()
  elseif input.UserInputType==Enum.UserInputType.MouseWheel then
   handleWheel(input)
  end
 end))
 addConn(workScroll.InputChanged:Connect(function(input)
  if input.UserInputType==Enum.UserInputType.MouseWheel then handleWheel(input) end
 end))
 scene=make("Frame",{Name="DocumentCanvas",Position=UDim2.fromOffset(0,0),Size=UDim2.fromOffset(viewportSize.X,viewportSize.Y),BackgroundColor3=Color3.fromRGB(28,32,40),BorderSizePixel=0,ClipsDescendants=true,Active=true},workScroll)
 zoomScale=make("UIScale",{Scale=zoom},scene)
 viewportController=Viewport.new(workScroll,scene,zoomScale)
  -- Scene is created above. Connecting input earlier crashed UI Editor startup.
  addConn(scene.InputBegan:Connect(beginPan))
 addConn(workScroll.MouseMoved:Connect(function()
  if activeGestureMove then activeGestureMove() end
  if canvasMouseMotion then canvasMouseMotion() end
  if panMouseMotion then panMouseMotion() end
 end))
 addConn(scene.MouseMoved:Connect(function()
  if activeGestureMove then activeGestureMove() end
  if canvasMouseMotion then canvasMouseMotion() end
  if panMouseMotion then panMouseMotion() end
 end))
 addConn(workScroll.InputEnded:Connect(function(input)
  if input.UserInputType==Enum.UserInputType.MouseButton1 and activeGestureUp then activeGestureUp() end
 end))
 make("UIStroke",{Color=Color3.fromRGB(88,96,111),Thickness=1},scene)
 -- Prominent recovery UI: autosave format is internal and not user-facing.
 recoveryBanner=make("Frame",{
  Name="UnsavedDraftRecovery",Visible=false,AnchorPoint=Vector2.new(.5,0),
  Position=UDim2.new(.5,0,0,68),Size=UDim2.fromOffset(560,122),
  BackgroundColor3=Color3.fromRGB(53,57,66),BorderSizePixel=0,ZIndex=55,
 },middle)
 make("UICorner",{CornerRadius=UDim.new(0,10)},recoveryBanner)
 make("UISizeConstraint",{MinSize=Vector2.new(520,112),MaxSize=Vector2.new(620,150)},recoveryBanner)
 local recoveryAccent=make("Frame",{Name="Accent",Visible=false,Position=UDim2.fromOffset(16,13),Size=UDim2.fromOffset(3,36),BackgroundColor3=ink.blue,BorderSizePixel=0,ZIndex=56},recoveryBanner)
 make("UIStroke",{Color=Color3.fromRGB(101,108,121),Transparency=.18,Thickness=1},recoveryBanner)
 local recoveryTitle=make("TextLabel",{
  Text=tr("Есть несохранённые изменения","Unsaved changes found"),
  Position=UDim2.fromOffset(20,12),Size=UDim2.new(1,-40,0,26),
  BackgroundTransparency=1,Font=Enum.Font.GothamBold,TextSize=14,
  TextXAlignment=Enum.TextXAlignment.Left,TextColor3=ink.text,ZIndex=56,
 },recoveryBanner)
 local recoveryDescription=make("TextLabel",{
  Text=tr("Можно вернуть предыдущий черновик редактора.","You can restore your previous editor draft."),
  Position=UDim2.fromOffset(20,40),Size=UDim2.new(1,-40,0,28),
  BackgroundTransparency=1,Font=Enum.Font.Gotham,TextSize=12,
  TextXAlignment=Enum.TextXAlignment.Left,TextWrapped=true,TextColor3=ink.muted,ZIndex=56,
 },recoveryBanner)
 local recoveryAction=btn(recoveryBanner,tr("Восстановить","Restore"),function()
  local data,sourceRoot=readSavedDraft()
  if not data or not sourceRoot then
   showRecoveryBanner(false)
   notice(tr("Сохранённый GUI больше не найден в этом проекте","Saved GUI is no longer available in this place"))
   return
  end
  if dirty then
   notice(tr("Сначала примени или сбрось текущие изменения","Apply or discard current changes first"))
   return
  end
  if currentRoot~=sourceRoot then load(sourceRoot) end
  recoveryDismissed=true
  showRecoveryBanner(false)
  restoreDraft()
 end,150,ink.blue)
 recoveryAction.Position=UDim2.fromOffset(20,78)
 recoveryAction.Size=UDim2.fromOffset(156,32)
 recoveryAction.ZIndex=56
 local recoveryDismiss=btn(recoveryBanner,tr("Не сейчас","Not now"),function() recoveryDismissed=true showRecoveryBanner(false) end,124,Color3.fromRGB(68,74,86))
 recoveryDismiss.Position=UDim2.fromOffset(188,78)
 recoveryDismiss.Size=UDim2.fromOffset(136,32)
 recoveryDismiss.ZIndex=56
 -- Recovery must be modal and above every element in the user preview.
 recoveryBanner.Parent=background
 recoveryBanner.Position=UDim2.new(.5,0,0,68)
 recoveryBanner.ZIndex=1700
 for _,desc in ipairs(recoveryBanner:GetDescendants()) do
  if desc:IsA("GuiObject") then desc.ZIndex=math.max(desc.ZIndex,1701) end
 end
 -- ForgeTools eight-slot toolbar, with project-provided icon assets.
 toolBar=make("Frame",{Name="ForgeToolsToolbar",AnchorPoint=Vector2.new(.5,1),Position=UDim2.new(.5,0,1,-16),Size=UDim2.fromOffset(439,54),BackgroundColor3=ink.pane,BorderSizePixel=0,ZIndex=25},middle)
 make("UICorner",{CornerRadius=UDim.new(0,10)},toolBar)
 make("UIStroke",{Color=ink.border,Thickness=1},toolBar)
 local tools=make("Frame",{Position=UDim2.fromOffset(12,6),Size=UDim2.new(1,-24,1,-12),BackgroundTransparency=1,ZIndex=26},toolBar)
 make("UIListLayout",{SortOrder=Enum.SortOrder.LayoutOrder,FillDirection=Enum.FillDirection.Horizontal,VerticalAlignment=Enum.VerticalAlignment.Center,HorizontalAlignment=Enum.HorizontalAlignment.Center,Padding=UDim.new(0,5)},tools)
 activeTool="Select"
 local toolButtons={}
 local toolOrderIndex=0
 iconTip=make("CanvasGroup",{Name="ForgeToolsToolTooltip",Visible=false,AnchorPoint=Vector2.new(.5,1),Position=UDim2.new(.5,0,1,-72),Size=UDim2.fromOffset(96,28),GroupTransparency=1,BackgroundColor3=ink.card,BorderSizePixel=0,ZIndex=40},middle)
 local iconTipText=make("TextLabel",{Name="Caption",BackgroundTransparency=1,Size=UDim2.fromScale(1,1),Text="",TextColor3=ink.text,Font=Enum.Font.GothamMedium,TextSize=12,ZIndex=41},iconTip)
 local tipTween
 local function hideToolTip()
  if tipTween then tipTween:Cancel() end
  tipTween=TweenService:Create(iconTip,TweenInfo.new(.12,Enum.EasingStyle.Quad,Enum.EasingDirection.Out),{GroupTransparency=1})
  tipTween:Play()
  local reference=tipTween
  reference.Completed:Connect(function() if reference==tipTween then iconTip.Visible=false end end)
 end
 local function showToolTip(button,display)
  if not showTooltips or not button.Parent then return end
  if tipTween then tipTween:Cancel() end
  iconTipText.Text=display
  local width=math.clamp(#display*7+24,72,150)
  iconTip.Size=UDim2.fromOffset(width,28)
  local cx=button.AbsolutePosition.X+button.AbsoluteSize.X*.5-middle.AbsolutePosition.X
  local y=button.AbsolutePosition.Y-middle.AbsolutePosition.Y-9
  iconTip.Position=UDim2.fromOffset(math.clamp(cx,width*.5+4,math.max(width*.5+4,middle.AbsoluteSize.X-width*.5-4)),y+5)
  iconTip.GroupTransparency=1
  iconTip.Visible=true
  tipTween=TweenService:Create(iconTip,TweenInfo.new(.18,Enum.EasingStyle.Quart,Enum.EasingDirection.Out),{GroupTransparency=0,Position=UDim2.fromOffset(math.clamp(cx,width*.5+4,math.max(width*.5+4,middle.AbsoluteSize.X-width*.5-4)),y)})
  tipTween:Play()
 end
 make("UICorner",{CornerRadius=UDim.new(0,6)},iconTip)
 local function setActiveTool(tool)
  activeTool=tool
  setCursorIcon(tool=="Select" and cursorIcons.default or cursorIcons.cross)
  -- Hiding old selection markers when switching from Select to insertion mode.
  for _,outline in pairs(overlayById) do
   if outline and outline.Parent then outline.Visible=(tool=="Select") end
  end
  for kind,b in pairs(toolButtons) do
   if b and b.Parent then
    TweenService:Create(b,TweenInfo.new(.17,Enum.EasingStyle.Quart,Enum.EasingDirection.Out),{BackgroundColor3=kind==tool and ink.blue or ink.pane}):Play()
   end
  end
 end
 local function toolButton(kind,ru,en,callback)
  toolOrderIndex+=1
  local b=make("TextButton",{Name="Tool_"..kind,LayoutOrder=toolOrderIndex,Text="",AutoButtonColor=false,Size=UDim2.fromOffset(46,42),BackgroundColor3=ink.pane,BorderSizePixel=0,ZIndex=27},tools)
  make("UICorner",{CornerRadius=UDim.new(0,7)},b)
  b:SetAttribute("ToolName",kind)
  b:SetAttribute("ToolDisplayName",tr(ru,en))
  b:SetAttribute("AssetId",TOOL_ICON_IDS[kind])
  -- Render the user's uploaded asset, not the previously hard-coded geometric placeholder.
  make("ImageLabel",{Name="Icon",Image=iconAsset(kind),Position=UDim2.fromOffset(7,5),Size=UDim2.fromOffset(32,32),BackgroundTransparency=1,ScaleType=Enum.ScaleType.Fit,ZIndex=28},b)
  toolButtons[kind]=b
  b.MouseEnter:Connect(function()
   showToolTip(b,en)
   TweenService:Create(b,TweenInfo.new(.15,Enum.EasingStyle.Quart,Enum.EasingDirection.Out),{BackgroundColor3=kind==activeTool and ink.blue or ink.card}):Play()
  end)
  b.MouseLeave:Connect(function()
   hideToolTip()
   TweenService:Create(b,TweenInfo.new(.18,Enum.EasingStyle.Quart,Enum.EasingDirection.Out),{BackgroundColor3=kind==activeTool and ink.blue or ink.pane}):Play()
  end)
  b.MouseButton1Click:Connect(function() hideToolTip() callback() end)
  return b
 end
 local contextMenu=make("Frame",{Name="EditorContextMenu",Visible=false,Size=UDim2.fromOffset(190,196),BackgroundColor3=ink.pane,BorderSizePixel=0,ZIndex=1900},background)
 make("UICorner",{CornerRadius=UDim.new(0,8)},contextMenu)
 local contextScale=make("UIScale",{Scale=.95},contextMenu)
 make("UIStroke",{Color=ink.border,Thickness=1},contextMenu)
 local contextInset=make("UIPadding",{PaddingTop=UDim.new(0,6),PaddingBottom=UDim.new(0,6),PaddingLeft=UDim.new(0,6),PaddingRight=UDim.new(0,6)},contextMenu)
 stack(contextMenu,3)
 local function contextAction(title,fn)
  local b=btn(contextMenu,title,function() contextMenu.Visible=false fn() end,174,ink.card)
  b.Size=UDim2.new(1,0,0,28) b.ZIndex=1901
 end
 contextAction("Undo",undo)
 contextAction("Redo",redo)
 contextAction("Duplicate",duplicateSelected)
 contextAction("Delete",deleteSelected)
 contextAction("Bring forward",function() moveLayer(-1) end)
 contextAction("Send backward",function() moveLayer(1) end)
 local toggleMore,morePanel,closeMore
 local function openContextMenu(point)
  if not dock or not dock.Enabled or not viewportController or not viewportController:contains(point) or recoveryBanner.Visible then return end
  closeMore()
  local candidate=editorHitTest(point)
  if candidate and not (selectedIds and selectedIds[candidate]) then choose(candidate) end
  contextMenu.Visible=true
  contextScale.Scale=.95
  TweenService:Create(contextScale,TweenInfo.new(.16,Enum.EasingStyle.Quart,Enum.EasingDirection.Out),{Scale=1}):Play()
  local rel=point-background.AbsolutePosition
  local bw,bh=background.AbsoluteSize.X,background.AbsoluteSize.Y
  contextMenu.Position=UDim2.fromOffset(math.clamp(rel.X,8,math.max(8,bw-202)),math.clamp(rel.Y,8,math.max(8,bh-208)))
 end
 local contextOpenAt=0
 openEditorContextForPoint=function(point)
  if os.clock()-contextOpenAt&gt;.10 and not popupIsBlocking() then
   contextOpenAt=os.clock()
   openContextMenu(point)
  end
 end
 toggleMore,morePanel,closeMore=createToolsMenu(background)
 -- Popup belongs to the editor root, outside clipped/zoomed preview content.
 morePanel.AnchorPoint=Vector2.new(0,1)
 morePanel.Position=UDim2.new(.5,230,1,-85)
 morePanel.ZIndex=1600
 for _,desc in ipairs(morePanel:GetDescendants()) do
  if desc:IsA("GuiObject") then desc.ZIndex=math.max(desc.ZIndex,1601) end
 end
 toolButton("Select","Выбор","Select",function() setActiveTool("Select") setCursorIcon(cursorIcons.default) notice(tr("Режим выделения","Selection mode")) end)
 local function createWithTool(kind)
  if not nodes then notice(tr("Выбери GUI через меню Choose GUI","Choose a GUI from the Choose GUI menu")) if openGuiPicker then openGuiPicker() end return end
  setActiveTool(kind)
  notice(tr("Нажми или протяни мышью на холсте, чтобы создать элемент.","Click or drag on canvas to create an element."))
 end
 local function separator()
  toolOrderIndex+=1
  make("Frame",{Name="ToolbarDivider",LayoutOrder=toolOrderIndex,Size=UDim2.fromOffset(1,27),BackgroundColor3=ink.border,BorderSizePixel=0,ZIndex=27},tools)
 end
 separator()
 toolButton("Frame","Фрейм","Frame",function() createWithTool("Frame") end)
 toolButton("TextLabel","Текст","Text label",function() createWithTool("TextLabel") end)
 toolButton("TextButton","Текстовая кнопка","Text button",function() createWithTool("TextButton") end)
 toolButton("TextBox","Поле ввода","TextBox",function() createWithTool("TextBox") end)
 toolButton("ImageLabel","Изображение","Image label",function() createWithTool("ImageLabel") end)
 toolButton("ImageButton","Кнопка с изображением","Image button",function() createWithTool("ImageButton") end)
 separator()
 toolButton("Insert","Добавить","More elements",function() setActiveTool("Select") contextMenu.Visible=false toggleMore() if morePanel.Visible then
  local x=toolBar.AbsolutePosition.X+toolBar.AbsoluteSize.X-background.AbsolutePosition.X+10
  local y=toolBar.AbsolutePosition.Y-background.AbsolutePosition.Y+8
  local maxX=background.AbsoluteSize.X-210
  local px=(x+202&lt;=background.AbsoluteSize.X-8) and x or (toolBar.AbsolutePosition.X-background.AbsolutePosition.X-210)
  morePanel.Position=UDim2.fromOffset(math.clamp(px,8,math.max(8,maxX)),math.max(160,y))
 end end)
 setActiveTool("Select")
 local drawStart,drawTool,drawGhost
 local function within(gui,point)
  if not gui or not gui.Parent then return false end
  local start,extent=gui.AbsolutePosition,gui.AbsoluteSize
  return point.X&gt;=start.X and point.Y&gt;=start.Y and point.X&lt;start.X+extent.X and point.Y&lt;start.Y+extent.Y
 end
 local function documentCoordinate(mouse,parentId)
  local relativeOrigin=scene.AbsolutePosition
  if parentId then
   local proxy=proxyById[parentId]
   if proxy and proxy.Parent then relativeOrigin=proxy.AbsolutePosition end
  end
  local localMouse=(mouse-relativeOrigin)/math.max(zoom,0.1)
  return Vector2.new(math.floor(localMouse.X+0.5),math.floor(localMouse.Y+0.5))
 end
 local function disposeGhost()
  if drawGhost then drawGhost:Destroy() drawGhost=nil end
 end
 addConn(UIS.WindowFocusReleased:Connect(function()
  drawStart=nil drawTool=nil
  disposeGhost()
 end))
 beginCanvasDraw=function(input)
  if popupIsBlocking() then return end
  if not dock or not dock.Enabled or activeTool=="Select" or drawStart then return end
  -- Space+LMB is reserved for panning, even if a creation tool is selected.
  if UIS:IsKeyDown(Enum.KeyCode.Space) then return end
  if input.UserInputType~=Enum.UserInputType.MouseButton1 then return end
  local pointer=mousePointer()
  if not viewportController or not viewportController:contains(pointer) or within(toolBar,pointer) or within(morePanel,pointer) and morePanel.Visible then return end
  local canvasOrigin,canvasExtent=scene.AbsolutePosition,scene.AbsoluteSize
  if pointer.X&lt;canvasOrigin.X or pointer.Y&lt;canvasOrigin.Y or pointer.X&gt;canvasOrigin.X+canvasExtent.X or pointer.Y&gt;canvasOrigin.Y+canvasExtent.Y then return end
  drawStart=pointer drawTool=activeTool
  disposeGhost()
  drawGhost=make("Frame",{Name="DragPreview",BackgroundColor3=ink.blue,BackgroundTransparency=0.86,BorderSizePixel=0,ZIndex=22,Size=UDim2.fromOffset(1,1)},workScroll)
  make("UIStroke",{Color=ink.blue,Thickness=1.5},drawGhost)
 end
 -- Some PluginGui instances do not dispatch InputBegan to a child TextButton
 -- if the pointer lies on a transparent overlay. A geometry-based fallback
 -- makes resize handles responsive without turning the whole overlay Active.
 local function beginResizeFromPointer(input)
  if popupIsBlocking() then return false end
  if input.UserInputType~=Enum.UserInputType.MouseButton1 or activeTool~="Select" or not nodes or not dock or not dock.Enabled then return false end
  if UIS:IsKeyDown(Enum.KeyCode.Space) then return false end
  local point=mousePointer()
  if not viewportController or not viewportController:contains(point) then return false end
  for selectedNode in pairs(selectedIds or {}) do
   local overlay=overlayById[selectedNode]
   if overlay and overlay.Parent then
    for _,knob in ipairs(overlay:GetChildren()) do
     if knob:IsA("GuiButton") and knob.Visible and knob.Name:sub(1,10)=="FT_Resize_" then
      local p,q=knob.AbsolutePosition,knob.AbsoluteSize
      if point.X&gt;=p.X-2 and point.Y&gt;=p.Y-2 and point.X&lt;=p.X+q.X+2 and point.Y&lt;=p.Y+q.Y+2 then
       captureInput(selectedNode,knob,input,"resize:"..knob.Name:sub(11))
       return true
      end
     end
    end
   end
  end
  return false
 end
 -- Studio may flag clicks inside PluginGui as processed. Route from GuiObjects first.
 addConn(workScroll.InputBegan:Connect(function(input)
  if not beginResizeFromPointer(input) then beginCanvasDraw(input) end
 end))
 addConn(scene.InputBegan:Connect(function(input)
  if not beginResizeFromPointer(input) then beginCanvasDraw(input) end
 end))
 addConn(UIS.InputBegan:Connect(function(input)
  if input.UserInputType==Enum.UserInputType.MouseButton1 and not beginResizeFromPointer(input) then beginCanvasDraw(input) end
 end))
 local function trackCanvasDraw(input)
  if not drawStart or not drawGhost or not drawGhost.Parent then return end
  if input and input.UserInputType~=Enum.UserInputType.MouseMovement then return end
  local current=mousePointer()
  local a=drawStart-workScroll.AbsolutePosition
  local b=current-workScroll.AbsolutePosition
  drawGhost.Position=UDim2.fromOffset(math.floor(math.min(a.X,b.X)),math.floor(math.min(a.Y,b.Y)))
  drawGhost.Size=UDim2.fromOffset(math.max(1,math.floor(math.abs(b.X-a.X))),math.max(1,math.floor(math.abs(b.Y-a.Y))))
 end
 canvasMouseMotion=trackCanvasDraw
 addConn(UIS.InputChanged:Connect(trackCanvasDraw))
 addConn(workScroll.InputChanged:Connect(trackCanvasDraw))
 addConn(scene.InputChanged:Connect(trackCanvasDraw))
 local function finishCanvasDraw(input)
  if input.UserInputType~=Enum.UserInputType.MouseButton1 or not drawStart then return end
  local first,tool=drawStart,drawTool
  drawStart=nil drawTool=nil disposeGhost()
  if not nodes or not tool or not allowed[tool] then setActiveTool("Select") return end
  local last=mousePointer()
  local parent=selected()
  local parentId=parent and parent.parent and parent.id or nil
  local a=documentCoordinate(first,parentId)
  local b=documentCoordinate(last,parentId)
  local position=UDim2.fromOffset(math.min(a.X,b.X),math.min(a.Y,b.Y))
  local width=math.abs(b.X-a.X)
  local height=math.abs(b.Y-a.Y)
  if width&lt;8 then width=170 end
  if height&lt;8 then height=70 end
  stageCreate(tool,position,UDim2.fromOffset(math.max(12,width),math.max(12,height)))
  -- Keep the insertion tool active for drawing multiple objects in a row.
  -- Creating objects should not silently switch back to selection mode.
  setActiveTool(tool)
 end
 addConn(UIS.InputEnded:Connect(finishCanvasDraw))
 addConn(workScroll.InputEnded:Connect(finishCanvasDraw))
 addConn(scene.InputEnded:Connect(finishCanvasDraw))
 -- Studio shortcuts scoped to the editor window; never consume typing in TextBoxes.
 addConn(UIS.InputBegan:Connect(function(input,processed)
  if processed or not dock or not dock.Enabled or not middle.Parent then return end
  if UIS:GetFocusedTextBox() then return end
  local point=mousePointer()
  if not viewportController or not viewportController:contains(point) then return end
  local ctrl=UIS:IsKeyDown(Enum.KeyCode.LeftControl) or UIS:IsKeyDown(Enum.KeyCode.RightControl)
  if ctrl and input.KeyCode==Enum.KeyCode.Z then undo() return end
  if ctrl and input.KeyCode==Enum.KeyCode.Y then redo() return end
  if input.KeyCode==Enum.KeyCode.Delete and selectedEditable() then deleteSelected() return end
  if ctrl then return end
  local hotkeys={V="Select",F="Frame",T="TextLabel",B="TextButton",X="TextBox",L="ImageLabel",G="ImageButton"}
  local kind=hotkeys[input.KeyCode.Name]
  if kind=="Select" then setActiveTool("Select")
  elseif kind then createWithTool(kind) end
 end))
 -- A compact scrolling/picture tool in the advanced menu, while the common ones stay visible.
 local footer=make("Frame",{Position=UDim2.new(0,0,1,-29),Size=UDim2.new(1,0,0,29),BackgroundColor3=ink.pane,BorderSizePixel=0},background)
 make("Frame",{Size=UDim2.new(1,0,0,1),BackgroundColor3=ink.border,BorderSizePixel=0},footer)
 local footLeft=make("Frame",{Position=UDim2.fromOffset(10,2),Size=UDim2.new(1,-195,1,-4),BackgroundTransparency=1},footer)
 make("UIListLayout",{FillDirection=Enum.FillDirection.Horizontal,Padding=UDim.new(0,5),VerticalAlignment=Enum.VerticalAlignment.Center},footLeft)
 local discardButton=btn(footLeft,tr("Сбросить","Discard"),reset,86)
 discardButton.Size=UDim2.fromOffset(86,25)
 footerInfo=label(footLeft,"",11,true)
 footerInfo.Size=UDim2.new(1,-94,0,25)
 footerInfo.TextTruncate=Enum.TextTruncate.None
 local footRight=make("Frame",{AnchorPoint=Vector2.new(1,0),Position=UDim2.new(1,-10,0,2),Size=UDim2.fromOffset(170,25),BackgroundTransparency=1},footer)
 make("UIListLayout",{FillDirection=Enum.FillDirection.Horizontal,HorizontalAlignment=Enum.HorizontalAlignment.Right,Padding=UDim.new(0,7),VerticalAlignment=Enum.VerticalAlignment.Center},footRight)
 local applyButton=btn(footRight,tr("Применить изменения","Apply changes"),apply,150,ink.green)
 applyButton.Size=UDim2.fromOffset(150,25)
 status=label(header,"",11,true)
 status.Position=UDim2.fromOffset(332,10)
 status.Size=UDim2.new(1,-660,0,26)
 status.TextTruncate=Enum.TextTruncate.AtEnd
 status.TextTransparency=.1
 addConn(Selection.SelectionChanged:Connect(function()
  if not dirty and not moving and dock and dock.Enabled then
   local selectedRoot=findRoot()
   if selectedRoot and selectedRoot~=currentRoot then load(selectedRoot) end
  end
 end))
 addConn(UIS.InputBegan:Connect(function(input,processed)
  if processed or not dock or not dock.Enabled or not nodes or moving then return end
  if UIS:GetFocusedTextBox() or not viewportController or not viewportController:contains(mousePointer()) then return end
  local key=input.KeyCode
  local dx,dy=0,0
  if key==Enum.KeyCode.Left then dx=-1
  elseif key==Enum.KeyCode.Right then dx=1
  elseif key==Enum.KeyCode.Up then dy=-1
  elseif key==Enum.KeyCode.Down then dy=1
  else return end
  local step=(UIS:IsKeyDown(Enum.KeyCode.LeftShift) or UIS:IsKeyDown(Enum.KeyCode.RightShift)) and 8 or 1
  nudgeSelection(dx*step,dy*step)
 end))
 -- One modal guard for all menus. A dismiss click is consumed by the popup,
 -- never reused as a gesture on the canvas.
 local dismissPressUntil=0
 local function isInside(gui,pt)
  if not gui or not gui.Parent or not gui.Visible then return false end
  local p,z=gui.AbsolutePosition,gui.AbsoluteSize
  return pt.X&gt;=p.X and pt.Y&gt;=p.Y and pt.X&lt;=p.X+z.X and pt.Y&lt;=p.Y+z.Y
 end
 popupIsBlocking=function()
  return (morePanel and morePanel.Visible) or (contextMenu and contextMenu.Visible)
   or (helpDialog and helpDialog.Visible) or (settingsDialog and settingsDialog.Visible)
   or (recoveryBanner and recoveryBanner.Visible) or (guiPicker and guiPicker.Visible)
   or os.clock()&lt;dismissPressUntil
 end
 popupConsumePress=function(point)
  if not popupIsBlocking() then return false end
  local didDismiss=false
  for _,menu in ipairs({morePanel,contextMenu}) do
   if menu and menu.Visible and not isInside(menu,point) then
    if menu==morePanel then closeMore() else menu.Visible=false end
    didDismiss=true
   end
  end
  if didDismiss then
   dismissPressUntil=os.clock()+.17
   if cancelActiveGesture then cancelActiveGesture() end
  end
  return didDismiss
 end
 -- One popup controller: right click on canvas opens actions; Esc/outside closes.
 addConn(UIS.InputBegan:Connect(function(input,processed)
  if not dock or not dock.Enabled then return end
  if input.KeyCode==Enum.KeyCode.Escape then
   closeMore()
   contextMenu.Visible=false
   helpDialog.Visible=false
   guiPicker.Visible=false
   return
  end
  if input.UserInputType==Enum.UserInputType.MouseButton2 then
   if os.clock()-contextOpenAt&gt;.10 and not popupIsBlocking() then
    contextOpenAt=os.clock()
    openContextMenu(mousePointer())
   end
  elseif input.UserInputType==Enum.UserInputType.MouseButton1 then
   local point=mousePointer()
   if guiPicker.Visible and workScroll and workScroll.Parent then
    local p,s=workScroll.AbsolutePosition,workScroll.AbsoluteSize
    if point.X&gt;=p.X and point.Y&gt;=p.Y and point.X&lt;p.X+s.X and point.Y&lt;p.Y+s.Y then
     guiPicker.Visible=false
     dismissPressUntil=os.clock()+.17
     if cancelActiveGesture then cancelActiveGesture() end
     return
    end
   end
   popupConsumePress(point)
  end
 end))
 addConn(workScroll.InputBegan:Connect(function(input)
  if input.UserInputType==Enum.UserInputType.MouseButton2 and os.clock()-contextOpenAt&gt;.10 and not popupIsBlocking() then
   contextOpenAt=os.clock()
   openContextMenu(mousePointer())
  end
 end))
 addConn(scene.InputBegan:Connect(function(input)
  if input.UserInputType==Enum.UserInputType.MouseButton1 and guiPicker.Visible then
   guiPicker.Visible=false
   dismissPressUntil=os.clock()+.17
   if cancelActiveGesture then cancelActiveGesture() end
   return
  end
  if input.UserInputType==Enum.UserInputType.MouseButton2 and os.clock()-contextOpenAt&gt;.10 and not popupIsBlocking() then
   contextOpenAt=os.clock()
   openContextMenu(mousePointer())
  elseif input.UserInputType==Enum.UserInputType.MouseButton1 then
   popupConsumePress(mousePointer())
  end
 end))
 local restorePreviewAfterFocus
 addConn(dock:GetPropertyChangedSignal("Enabled"):Connect(function()
  if dock and not dock.Enabled then
   setCursorIcon(cursorIcons.default)
   if cancelActiveGesture then cancelActiveGesture() end
   overlayRefreshGeneration+=1
   drawStart=nil drawTool=nil disposeGhost()
   setActiveTool("Select")
   if dirty then saveGeneration+=1 saveDraft() end
  elseif dock and dock.Enabled then
   restorePreviewAfterFocus()
  end
 end))
 restorePreviewAfterFocus=function()
  -- FT-EDITOR-009: Studio may suspend/recreate PluginGui render surfaces on Alt+Tab.
  -- Repaint ONLY preview instances; preserve staged nodes, history, dirty flag and zoom.
  overlayRefreshGeneration+=1
  local token=overlayRefreshGeneration
  task.defer(function()
   -- Let Studio restore plugin widget geometry before rebuilding the preview.
   task.wait()
   if token~=overlayRefreshGeneration or not dock or not dock.Parent or not dock.Enabled then return end
   -- Rebuilding while an active gesture owns the old proxies can break the drag.
   if moving or drawStart then return end
   if not workScroll or workScroll.AbsoluteSize.X&lt;100 or workScroll.AbsoluteSize.Y&lt;100 then
    task.wait()
    if token~=overlayRefreshGeneration or not workScroll or workScroll.AbsoluteSize.X&lt;100 or workScroll.AbsoluteSize.Y&lt;100 then return end
   end
   if moving or drawStart or not scene or not scene.Parent then return end
   -- Plugin focus is not a document change. Rebuild only if previews were actually lost.
   if nodes and next(nodes) and next(proxyById)==nil then repaint() end
   for overlayId in pairs(selectedIds or {}) do queueOverlayUpdate(overlayId) end
   task.defer(function()
    if token~=overlayRefreshGeneration or not dock or not dock.Enabled or moving then return end
    for overlayId in pairs(selectedIds or {}) do queueOverlayUpdate(overlayId) end
   end)
  end)
 end
 -- Both events exist on PluginGui; UIS fallback covers Studio application reactivation.
 addConn(dock.WindowFocused:Connect(restorePreviewAfterFocus))
 addConn(UIS.WindowFocused:Connect(restorePreviewAfterFocus))
 addConn(workScroll:GetPropertyChangedSignal("AbsoluteSize"):Connect(function()
  if viewportController and viewportController:valid() and workScroll.AbsoluteSize.X&gt;100 and workScroll.AbsoluteSize.Y&gt;100 then
   -- Keep the zoom selected by the user; recalculate geometry only after the dock is valid.
   -- Preserve manual pan when the plugin window changes size or regains focus.
   if dock and dock.Enabled then
    for overlayId in pairs(selectedIds or {}) do queueOverlayUpdate(overlayId) end
   end
  end
 end))
 dock.Destroying:Connect(function()
  stopPan()
  if cancelActiveGesture then cancelActiveGesture() end
  disconnect()
  dock=nil canvas=nil scene=nil properties=nil layerList=nil status=nil footerInfo=nil workScroll=nil
  zoomScale=nil zoomReadout=nil viewportReadout=nil emptyHint=nil
  nodes=nil baseline=nil currentRoot=nil dirty=false
  layerSelectButtons={}
 end)
 local selectedRoot=findRoot()
 if selectedRoot then load(selectedRoot) else
  if emptyHint then emptyHint.Visible=false end
  promptDraft()
 end
 M.refreshCanvas()
 task.defer(function()
  if not dock or not dock.Parent or not viewportController or not viewportController:valid() then return end
  -- Start with the selected GUI component, not a tiny preview of a 1920x1080 screen.
  -- Absolute geometry may need one engine frame to settle after Widget creation.
  task.wait()
  if not dock or not dock.Parent or not viewportController or not viewportController:valid() then return end
  fitCanvas()
  local chosen=selected()
  local proxy=chosen and chosen.parent and proxyById[chosen.id]
  if proxy and proxy.Parent and proxy.AbsoluteSize.X&gt;0 and proxy.AbsoluteSize.Y&gt;0 then
   local intrinsic=proxy.AbsoluteSize/math.max(zoom,0.1)
   local target=math.clamp(math.min(
    (workScroll.AbsoluteSize.X-96)/math.max(1,intrinsic.X),
    (workScroll.AbsoluteSize.Y-128)/math.max(1,intrinsic.Y)),0.1,1.25)
   local anchor=proxy.AbsolutePosition+proxy.AbsoluteSize/2
   zoom=viewportController:zoomTo(target,anchor)
   task.wait()
   if not dock or not dock.Parent or not proxy.Parent or not viewportController:valid() then return end
   local center=proxy.AbsolutePosition+proxy.AbsoluteSize/2
   viewportController:panBy(workScroll.AbsolutePosition+workScroll.AbsoluteSize/2-center)
   if zoomReadout then zoomReadout.Text=formatPercent() end
  end
 end)
end
return M
</ProtectedString>
        </Properties>
      </Item>
      <Item class="ModuleScript" referent="RBX7">
        <Properties>
          <string name="Name">RESPONSIVE_CONTROLLER</string>
          <ProtectedString name="Source">return [====[
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local runtime = ReplicatedStorage:WaitForChild("UIToolsResponsiveRuntime", 8)
if not runtime then
    warn("[UITools Responsive] UIToolsResponsiveRuntime is missing from ReplicatedStorage. Open UITools Studio plugin in Edit mode to repair it, save and publish the place again.")
elseif not runtime:IsA("ModuleScript") then
    warn("[UITools Responsive] UIToolsResponsiveRuntime is not a ModuleScript; responsive controller disabled.")
else
    local ok, responsive = pcall(require, runtime)
    if not ok then
        warn("[UITools Responsive] Runtime failed to load: " .. tostring(responsive))
    elseif type(responsive) ~= "table" or type(responsive.Attach) ~= "function" then
        warn("[UITools Responsive] Runtime does not provide Attach; controller disabled.")
    else
        local attached, err = pcall(responsive.Attach, script.Parent)
        if not attached then warn("[UITools Responsive] Attach failed: " .. tostring(err)) end
    end
end
]====]</ProtectedString>
        </Properties>
      </Item>
      <Item class="ModuleScript" referent="RBX8">
        <Properties>
          <string name="Name">RESPONSIVE_RUNTIME</string>
          <ProtectedString name="Source">return [====[
local Responsive={}
local RunService=game:GetService("RunService")
function Responsive.Attach(target)
    if not RunService:IsClient() or not target or not target:IsA("GuiObject") then return end
    local scale=target:FindFirstChild("UIToolsResponsiveScale")
    if scale and not scale:IsA("UIScale") then return end
    if not scale then
        scale=Instance.new("UIScale")
        scale.Name="UIToolsResponsiveScale"
        scale.Parent=target
    end
    local watchers={}
    local cameraWatcher
    local currentCamera
    local busy=false
    local function refresh()
        if busy or not target.Parent then return end
        local camera=workspace.CurrentCamera
        if not camera then return end
        local view=camera.ViewportSize
        if view.X&lt;1 or view.Y&lt;1 then return end
        local refX=math.max(1,tonumber(target:GetAttribute("UIToolsReferenceWidth")) or 390)
        local refY=math.max(1,tonumber(target:GetAttribute("UIToolsReferenceHeight")) or 844)
        local minimum=tonumber(target:GetAttribute("UIToolsMinScale")) or .6
        local maximum=tonumber(target:GetAttribute("UIToolsMaxScale")) or 1.8
        if minimum&gt;maximum then minimum,maximum=maximum,minimum end
        local newScale=math.clamp(math.min(view.X/refX,view.Y/refY),minimum,maximum)
        
        
        if math.abs(scale.Scale-newScale)&gt;.001 then
            busy=true
            scale.Scale=newScale
            busy=false
        end
    end
    local function connect(signal)
        local connection=signal:Connect(refresh)
        table.insert(watchers,connection)
    end
    local function watchCamera()
        if cameraWatcher then cameraWatcher:Disconnect() cameraWatcher=nil end
        currentCamera=workspace.CurrentCamera
        if currentCamera then cameraWatcher=currentCamera:GetPropertyChangedSignal("ViewportSize"):Connect(refresh) end
        refresh()
    end
    table.insert(watchers,workspace:GetPropertyChangedSignal("CurrentCamera"):Connect(watchCamera))
    for _,attr in ipairs({"UIToolsReferenceWidth","UIToolsReferenceHeight","UIToolsMinScale","UIToolsMaxScale"}) do
        connect(target:GetAttributeChangedSignal(attr))
    end
    watchCamera()
    local closing=false
    local function stop()
        if closing then return end
        closing=true
        if cameraWatcher then cameraWatcher:Disconnect() end
        for _,c in ipairs(watchers) do c:Disconnect() end
    end
    table.insert(watchers,target.Destroying:Connect(stop))
    return stop
end
return Responsive
]====]</ProtectedString>
        </Properties>
      </Item>
      <Item class="ModuleScript" referent="RBX_DIAG_01">
        <Properties>
          <string name="Name">GUI_DIAGNOSTICS</string>
          <ProtectedString name="Source">local Diagnostics = {}
local function overlaps(a,b)
    return a.left &lt; b.right and b.left &lt; a.right and a.top &lt; b.bottom and b.top &lt; a.bottom
end
local function isText(o) return o:IsA("TextLabel") or o:IsA("TextButton") or o:IsA("TextBox") end
local function contains(a,b)
    return a.left&lt;=b.left and a.top&lt;=b.top and a.right&gt;=b.right and a.bottom&gt;=b.bottom
end
function Diagnostics.Scan(roots, screenWidth, screenHeight)
    local findings, stats={}, {objects=0, gradients=0, animations=0, constraints=0, layouts=0}
    local seen={}
    local function flag(obj,kind,level,ru,en)
        local id=tostring(obj).."|"..kind
        if seen[id] then return end
        seen[id]=true
        table.insert(findings,{object=obj,kind=kind,level=level,ru=ru,en=en})
    end
    local visited={}
    local function scan(o, rect, depth)
        if depth&gt;100 or visited[o] then return end
        visited[o]=true
        if not o:IsA("GuiObject") then
            for _,child in ipairs(o:GetChildren()) do scan(child,rect,depth+1) end
            return
        end
        stats.objects+=1
        local width=math.max(0,rect.right-rect.left)
        local height=math.max(0,rect.bottom-rect.top)
        local sx=o.Size.X.Scale*width+o.Size.X.Offset
        local sy=o.Size.Y.Scale*height+o.Size.Y.Offset
        local px=rect.left+o.Position.X.Scale*width+o.Position.X.Offset-o.AnchorPoint.X*sx
        local py=rect.top+o.Position.Y.Scale*height+o.Position.Y.Offset-o.AnchorPoint.Y*sy
        local bounds={left=px,top=py,right=px+sx,bottom=py+sy}
        if sx&lt;=0 or sy&lt;=0 then flag(o,"empty",2,"Нулевой или отрицательный размер","Zero or negative size") end
        if not overlaps(bounds,{left=0,top=0,right=screenWidth,bottom=screenHeight}) then
            flag(o,"offscreen",3,"Полностью вне экрана","Entirely outside viewport")
        elseif not contains({left=0,top=0,right=screenWidth,bottom=screenHeight},bounds) then
            flag(o,"overflow",2,"Частично выходит за экран","Partly outside viewport")
        end
        if o.Parent and o.Parent:IsA("GuiObject") and o.Parent.ClipsDescendants and not overlaps(bounds,rect) then
            flag(o,"clipped",3,"Полностью обрезан родителем","Fully clipped by parent")
        end
        if isText(o) then
            if o.TextScaled and not o:FindFirstChildOfClass("UITextSizeConstraint") then
                flag(o,"textConstraint",2,"TextScaled без ограничения размера текста","TextScaled without size constraint")
            end
            if sx&gt;0 and sy&gt;0 and (sx&lt;44 or sy&lt;24) and (o:IsA("TextButton") or o:IsA("TextBox")) then
                flag(o,"touchTarget",1,"Маленькая область нажатия — проверь на телефоне","Small touch target — check on phone")
            end
        end
        local scales,animations=0,0
        local hasLayout=false
        for _,child in ipairs(o:GetChildren()) do
            if child:IsA("UIScale") then scales+=1 end
            if child:IsA("UIGradient") then stats.gradients+=1 end
            if child:IsA("LocalScript") and (child.Name:find("UITools") or child.Name:find("Animator")) then animations+=1 stats.animations+=1 end
            if child:IsA("UIListLayout") or child:IsA("UIGridLayout") or child:IsA("UIPageLayout") then hasLayout=true stats.layouts+=1 end
            if child:IsA("UISizeConstraint") or child:IsA("UIAspectRatioConstraint") then stats.constraints+=1 end
        end
        if scales&gt;1 then flag(o,"scales",2,"Несколько UIScale: проверь суммарный масштаб","Multiple UIScale: verify combined scale") end
        if animations&gt;2 then flag(o,"animations",1,"Несколько анимаций: возможна нагрузка или конфликт","Multiple animations: possible cost or conflict") end
        if hasLayout then flag(o,"layout",1,"Layout управляет размещением; координаты оценочные","Layout controls positions; geometry is approximate") end
        for _,child in ipairs(o:GetChildren()) do
            if child:IsA("GuiObject") or child:IsA("Folder") then scan(child,bounds,depth+1) end
        end
    end
    local screen={left=0,top=0,right=screenWidth,bottom=screenHeight}
    for _,root in ipairs(roots) do
        if not root:IsA("GuiObject") and not root:IsA("LayerCollector") then
            flag(root,"root",1,"Выбери ScreenGui или GUI-элемент","Select ScreenGui or GUI object")
        end
        scan(root,screen,0)
    end
    table.sort(findings,function(a,b) return a.level&gt;b.level end)
    return findings,stats
end
return Diagnostics
</ProtectedString>
        </Properties>
      </Item>
      <Item class="ModuleScript" referent="RBXFT108">
        <Properties>
          <string name="Name">FT_ANTICHEAT_AEGIS_SOURCE</string>
          <ProtectedString name="Source">return [====[











































local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local DataStoreService = game:GetService("DataStoreService")
local MemoryStoreService = game:GetService("MemoryStoreService")
local Workspace = game:GetService("Workspace")
local HttpService = game:GetService("HttpService")

local Aegis = {}



local Config = {
	kickOnDetect = false,
	flagThreshold = 3,
	discordWebhook = "",
	webhookEnabled = false,
	webhookVerbose = false,
	webhookMinInterval = 1.5,
	webhookEmbeds = true,
	webhookDigest = false,
	strikeDecaySeconds = 600,
	playerArgBinding = true,

	globalRate = { 150, 1 },

	
	
	crossServer = {
		enabled = false,
		mapName = "aegis_strikes_v1",
		expirySeconds = 86400,
	},

	
	
	
	
	escalation = {
		banAt = nil,
		banSeconds = 3600,
		permAt = nil,
	},

	honeypot = {
		enabled = false,
		names = { "GiveAdmin", "FreeRewards", "AddCoins", "GrantItem", "SetLevel" },
		items = {},
	},

	bans = {
		enabled = false,
		storeName = "aegis_bans_v1",
	},
	auditOnly = true,

	remoteDefaults = {
		rateLimit = { 20, 1 },
		maxArgSize = 2048,
	},

	remotes = {},

	movement = {
		enabled = true,
		baseSpeed = 16,
		tolerance = 1.3,
		checkInterval = 0.2,
		ignoreSeated = true,
		
		
		
		rollback = true,
		
		
		flySeconds = 3,
		
		
		
		flingSpeed = 120,
	},

	noclip = {
		enabled = true,
		checkInterval = 0.5,
		ignoreSeated = true,
	},

	aimbot = {
		enabled = true,
		maxSnapDegrees = 100,
		flagOnly = true,
	},

	session = {
		enabled = false,
		maxIdle = 900,
		checkInterval = 30,
	},

	combat = {
		enabled = true,
		consistencyWindow = 10,
		consistencyTolerance = 0.05,
	},

	behavior = {
		enabled = true,
		consistencyWindow = 20,
		consistencyTolerance = 0.05,
		marathonSeconds = 21600,
		marathonActions = 500,
		breakReset = 600,
		
		
		
		
		adaptiveWindow = 30,
		adaptiveMaxMean = 1.0,
		adaptiveMaxCV = 0.08,
	},
}



local Logger = {}
local strikes = {}




local BanGuard




local recentCalls = {}

local function recordCall(player, remoteName, args)
	local list = recentCalls[player.UserId]
	if not list then
		list = {}
		recentCalls[player.UserId] = list
	end
	local types = {}
	for i, v in ipairs(args) do
		types[i] = typeof(v)
	end
	table.insert(list, remoteName .. "(" .. table.concat(types, ", ") .. ")")
	if #list &gt; 10 then
		table.remove(list, 1)
	end
end

local function buildEvidence(player)
	local bits = {}
	local character = player.Character
	local hrp = character and character:FindFirstChild("HumanoidRootPart")
	if hrp then
		table.insert(bits, string.format(
			"pos (%.0f, %.0f, %.0f) vel %.0f",
			hrp.Position.X, hrp.Position.Y, hrp.Position.Z,
			hrp.AssemblyLinearVelocity.Magnitude
		))
	end
	local calls = recentCalls[player.UserId]
	if calls and #calls &gt; 0 then
		local tail = {}
		for i = math.max(1, #calls - 4), #calls do
			table.insert(tail, calls[i])
		end
		table.insert(bits, "recent: " .. table.concat(tail, ", "))
	end
	return table.concat(bits, " | ")
end

local webhookLastPost = 0
local webhookSuppressed = 0
local digestBuffer = {}

local function severityColor(message)
	if message:sub(1, 4) == "KICK" then
		return 0xE74C3C
	end
	if message:find("honeypot") then
		return 0x9B59B6
	end
	if message:sub(1, 4) == "FLAG" then
		return 0xE67E22
	end
	return 0xF1C40F
end

local function sendWebhook(message, evidence)
	if not Config.webhookEnabled or Config.discordWebhook == "" then
		return
	end
	
	
	if Config.webhookDigest then
		table.insert(digestBuffer, message)
		if #digestBuffer &gt; 50 then
			table.remove(digestBuffer, 1)
		end
		return
	end
	local now = os.clock()
	if now - webhookLastPost &lt; Config.webhookMinInterval then
		webhookSuppressed += 1
		return
	end
	webhookLastPost = now
	if webhookSuppressed &gt; 0 then
		message = message .. " (+" .. webhookSuppressed .. " more suppressed)"
		webhookSuppressed = 0
	end
	local payload
	if Config.webhookEmbeds then
		local embed = {
			title = "[Aegis] event",
			color = severityColor(message),
			description = message,
		}
		if evidence and evidence ~= "" then
			embed.fields = { { name = "Evidence", value = evidence } }
		end
		payload = { embeds = { embed } }
	else
		payload = {
			content = "[Aegis] " .. message
				.. (evidence and evidence ~= "" and ("\n" .. evidence) or ""),
		}
	end
	task.spawn(function()
		pcall(function()
			HttpService:PostAsync(
				Config.discordWebhook,
				HttpService:JSONEncode(payload)
			)
		end)
	end)
end

function Logger.flushDigest()
	if not Config.webhookEnabled or #digestBuffer == 0 or Config.discordWebhook == "" then
		return
	end
	local body = table.concat(digestBuffer, "\n")
	digestBuffer = {}
	if #body &gt; 1900 then
		body = body:sub(1, 1900)
	end
	task.spawn(function()
		pcall(function()
			HttpService:PostAsync(
				Config.discordWebhook,
				HttpService:JSONEncode({ content = "[Aegis] digest\n" .. body })
			)
		end)
	end)
end

function Logger.log(message)
	print("[Aegis] " .. message)
	if Config.webhookVerbose then
		sendWebhook(message)
	end
end

local function logEvent(message, evidence)
	print("[Aegis] " .. message)
	sendWebhook(message, evidence)
end





local function crossServerBump(userId)
	if not Config.crossServer.enabled then
		return nil
	end
	local ok, map = pcall(function()
		return MemoryStoreService:GetSortedMap(Config.crossServer.mapName)
	end)
	if not ok or not map then
		return nil
	end
	local ok2, total = pcall(function()
		return map:UpdateAsync("strike_" .. userId, function(old)
			local n = (typeof(old) == "number" and old or 0) + 1
			return n
		end, Config.crossServer.expirySeconds)
	end)
	if ok2 and typeof(total) == "number" then
		return total
	end
	return nil
end

function Logger.flag(player, category, detail)
	local key = player.UserId .. ":" .. category
	local entry = strikes[key]
	if not entry or os.clock() - entry.last &gt; Config.strikeDecaySeconds then
		entry = { n = 0, last = 0 }
	end
	entry.n += 1
	entry.last = os.clock()
	strikes[key] = entry
	local count = entry.n
	logEvent(string.format(
		"FLAG %s (%d) [%s] %s (strike %d)",
		player.Name,
		player.UserId,
		category,
		detail or "",
		count
	), buildEvidence(player))
	if Config.auditOnly then
		Logger.log("AUDIT (no action): " .. category .. " / " .. player.Name)
		return count
	end
	
	
	
	
	local kicked = false
	local crossTotal = crossServerBump(player.UserId)
	if crossTotal and crossTotal &gt;= Config.flagThreshold and Config.kickOnDetect then
		Logger.kick(player, "Aegis: " .. category .. " (cross-server strikes)")
		kicked = true
	end
	if not kicked and Config.kickOnDetect and count &gt;= Config.flagThreshold then
		Logger.kick(player, "Aegis: " .. category)
		kicked = true
	end
	if Config.bans.enabled then
		local esc = Config.escalation
		if esc.permAt and count &gt;= esc.permAt then
			BanGuard.ban(player.UserId, 315360000, "Aegis: " .. category .. " (permanent)")
		elseif esc.banAt and count &gt;= esc.banAt then
			BanGuard.ban(player.UserId, esc.banSeconds or 3600, "Aegis: " .. category)
		end
	end
	return count
end

function Logger.warn(player, category, detail)
	logEvent(string.format(
		"WARN %s (%d) [%s] %s",
		player.Name,
		player.UserId,
		category,
		detail or ""
	))
end

function Logger.kick(player, reason)
	logEvent("KICK " .. player.Name .. " (" .. player.UserId .. ") — " .. reason)
	pcall(function()
		player:Kick(reason)
	end)
end

function Logger.clear(player)
	local prefix = player.UserId .. ":"
	for k in pairs(strikes) do
		if k:sub(1, #prefix) == prefix then
			strikes[k] = nil
		end
	end
	recentCalls[player.UserId] = nil
end



local trusted = {}

local function isTrusted(player)
	return trusted[player.UserId] == true
end



local AimbotGuard = {}
local aimHistory = {}
local MAX_AIM_HISTORY = 30

local function angleBetween(a, b)
	return math.deg(math.acos(math.clamp(a:Dot(b), -1, 1)))
end

function AimbotGuard.trackShot(player, aimDir)
	if not Config.aimbot.enabled then
		return
	end
	if isTrusted(player) then
		return
	end
	if typeof(aimDir) ~= "Vector3" or aimDir.Magnitude &lt; 0.001 then
		return
	end

	local uid = player.UserId
	local h = aimHistory[uid]
	if not h then
		h = {}
		aimHistory[uid] = h
	end

	local now = os.clock()
	local dir = aimDir.Unit

	if #h &gt; 0 then
		local prev = h[#h]
		local snap = angleBetween(prev.dir, dir)
		if snap &gt; Config.aimbot.maxSnapDegrees and (now - prev.t) &lt; 1 then
			Logger.warn(
				player,
				"aimbot",
				string.format("snap %.0f deg in %.2fs", snap, now - prev.t)
			)
		end
	end

	table.insert(h, { dir = dir, t = now })
	if #h &gt; MAX_AIM_HISTORY then
		table.remove(h, 1)
	end

	if #h &gt;= 11 then
		local steady = 0
		for i = #h - 9, #h do
			if angleBetween(h[i - 1].dir, h[i].dir) &lt; 1.5 then
				steady += 1
			end
		end
		if steady &gt;= 10 then
			Logger.warn(player, "aimbot", "inhuman tracking consistency")
			aimHistory[uid] = {}
		end
	end
end



local SessionGuard = {}
local activity = {}

function SessionGuard.ping(player)
	activity[player.UserId] = os.clock()
end

function SessionGuard.start()
	local cfg = Config.session
	if not cfg.enabled then
		return
	end
	for _, player in ipairs(Players:GetPlayers()) do
		activity[player.UserId] = os.clock()
	end
	Players.PlayerAdded:Connect(function(player)
		activity[player.UserId] = os.clock()
	end)
	Players.PlayerRemoving:Connect(function(player)
		activity[player.UserId] = nil
	end)
	task.spawn(function()
		while true do
			task.wait(cfg.checkInterval)
			local now = os.clock()
			for _, player in ipairs(Players:GetPlayers()) do
				if not isTrusted(player) then
					local lastActive = activity[player.UserId] or now
					if now - lastActive &gt; cfg.maxIdle then
						Logger.kick(player, "Aegis: idle too long")
					end
				end
			end
		end
	end)
end



local RemoteValidator = {}
local rateBuckets = {}

local function typeOk(value, expected)
	if expected == "any" then
		return true
	end
	if expected == "WorkspaceInstance" then
		
		
		return typeof(value) == "Instance" and value:IsDescendantOf(Workspace)
	end
	return typeof(value) == expected
end






local function playerArgBound(player, args)
	if not Config.playerArgBinding then
		return true
	end
	for _, v in ipairs(args) do
		if typeof(v) == "Instance" and v:IsA("Player") and v ~= player then
			return false
		end
	end
	return true
end



local function validInstance(inst, className, mustBeInWorkspace)
	if typeof(inst) ~= "Instance" then
		return false
	end
	if className and not inst:IsA(className) then
		return false
	end
	if mustBeInWorkspace and not inst:IsDescendantOf(Workspace) then
		return false
	end
	return true
end







-- Bounded, fail-closed validation for untrusted remote payloads.
local MAX_REMOTE_DEPTH = 4
local MAX_REMOTE_NODES = 2048
local function walkPayload(value, limit, depth, budget, active)
    depth = depth or 0
    if depth &gt; MAX_REMOTE_DEPTH then return false end
    budget.nodes += 1
    if budget.nodes &gt; MAX_REMOTE_NODES then return false end
    local t = typeof(value)
    if t == "number" then
        return value == value and value ~= math.huge and value ~= -math.huge
    elseif t == "Vector3" then
        return walkPayload(value.X, limit, depth + 1, budget, active)
           and walkPayload(value.Y, limit, depth + 1, budget, active)
           and walkPayload(value.Z, limit, depth + 1, budget, active)
    elseif t == "CFrame" then
        for _, component in ipairs({value:GetComponents()}) do
            if not walkPayload(component, limit, depth + 1, budget, active) then return false end
        end
    elseif t == "string" then
        budget.bytes += #value
        if budget.bytes &gt; limit then return false end
    elseif t == "table" then
        if depth &gt;= MAX_REMOTE_DEPTH or active[value] then return false end
        active[value] = true
        for k, v in pairs(value) do
            if not walkPayload(k, limit, depth + 1, budget, active)
               or not walkPayload(v, limit, depth + 1, budget, active) then
                active[value] = nil
                return false
            end
        end
        active[value] = nil
    end
    return true
end
local function finiteOk(value, depth)
    return walkPayload(value, 1048576, depth or 0, {nodes=0, bytes=0}, {})
end
local function sizeOk(value, maxSize)
    if type(maxSize) ~= "number" or maxSize &lt; 1 then return false end
    local budget = {nodes=0, bytes=0}
    return walkPayload(value, maxSize, 0, budget, {}) and budget.nodes &lt;= maxSize
end

local function rateOk(player, remoteName, limit)
	local maxCalls, perSec = limit[1], limit[2]
	local key = player.UserId .. "\0" .. remoteName
	local now = os.clock()
	local kept = {}
	for _, t in ipairs(rateBuckets[key] or {}) do
		if now - t &lt; perSec then
			table.insert(kept, t)
		end
	end
	rateBuckets[key] = kept
	if #kept &gt;= maxCalls then
		return false
	end
	table.insert(kept, now)
	return true
end

Players.PlayerRemoving:Connect(function(player)
	local prefix = player.UserId .. "\0"
	for key in pairs(rateBuckets) do
		if key:sub(1, #prefix) == prefix then
			rateBuckets[key] = nil
		end
	end
	recentCalls[player.UserId] = nil
end)

local function globalRateOk(player)
	local limit = Config.globalRate
	if not limit or not limit[1] or limit[1] &lt;= 0 then
		return true
	end
	return rateOk(player, "__global", limit)
end

local function resolveSchema(remote, override)
	local schema = {
		args = {},
		rateLimit = Config.remoteDefaults.rateLimit,
		maxArgSize = Config.remoteDefaults.maxArgSize,
		trackAim = false,
		aimArg = 1,
	}
	local per = Config.remotes[remote.Name]
	if per then
		for k, v in pairs(per) do
			schema[k] = v
		end
	end
	if override then
		for k, v in pairs(override) do
			schema[k] = v
		end
	end
	return schema
end

function RemoteValidator.secure(remote, schemaOverride, handler)
	if typeof(schemaOverride) == "function" and handler == nil then
		handler = schemaOverride
		schemaOverride = nil
	end
	assert(typeof(handler) == "function", "Aegis.secure: handler must be a function")

	local schema = resolveSchema(remote, schemaOverride)

	remote.OnServerEvent:Connect(function(player, ...)
		if isTrusted(player) then
			local okT, errT = pcall(handler, player, ...)
			if not okT then
				Logger.log("handler error in " .. remote.Name .. ": " .. tostring(errT))
			end
			return
		end

		local args = { ... }
		recordCall(player, remote.Name, args)

		if not globalRateOk(player) then
			Logger.flag(player, "remote-spam", remote.Name .. " (global budget)")
			return
		end

		if not rateOk(player, remote.Name, schema.rateLimit) then
			Logger.flag(player, "remote-spam", remote.Name)
			return
		end

		if #args &gt; #schema.args then
			Logger.flag(player, "remote-args", remote.Name .. ": too many args")
			return
		end

		for i, expected in ipairs(schema.args) do
			local v = args[i]
			local optional = expected:sub(-1) == "?"
			if optional then
				expected = expected:sub(1, -2)
			end
			if v == nil then
				if optional or expected == "nil" then
					continue
				end
				Logger.flag(player, "remote-args", remote.Name .. ": missing arg " .. i)
				return
			end
			if not typeOk(v, expected) then
				Logger.flag(
					player,
					"remote-args",
					string.format(
						"%s: arg %d expected %s, got %s",
						remote.Name,
						i,
						expected,
						typeof(v)
					)
				)
				return
			end
			if not finiteOk(v) then
				Logger.flag(player, "remote-args", remote.Name .. ": non-finite arg " .. i)
				return
			end
			if not sizeOk(v, schema.maxArgSize) then
				Logger.flag(player, "remote-crasher", remote.Name .. ": oversized arg " .. i)
				return
			end
		end

		if not playerArgBound(player, args) then
			Logger.flag(player, "remote-args", remote.Name .. ": arg names another player")
			return
		end

		if schema.trackAim then
			local dir = args[schema.aimArg]
			if typeof(dir) == "Vector3" then
				AimbotGuard.trackShot(player, dir)
			end
		end

		SessionGuard.ping(player)

		local ok, err = pcall(handler, player, ...)
		if not ok then
			Logger.log("handler error in " .. remote.Name .. ": " .. tostring(err))
		end
	end)
end

function RemoteValidator.secureFunction(rf, schemaOverride, handler)
	if typeof(schemaOverride) == "function" and handler == nil then
		handler = schemaOverride
		schemaOverride = nil
	end
	assert(typeof(handler) == "function", "Aegis.secureFunction: handler must be a function")

	local schema = resolveSchema(rf, schemaOverride)

	rf.OnServerInvoke = function(player, ...)
		if isTrusted(player) then
			return handler(player, ...)
		end

		local args = { ... }
		recordCall(player, rf.Name, args)

		if not globalRateOk(player) then
			Logger.flag(player, "remote-spam", rf.Name .. " (global budget)")
			return nil
		end

		if not rateOk(player, rf.Name, schema.rateLimit) then
			Logger.flag(player, "remote-spam", rf.Name)
			return nil
		end

		if #args &gt; #schema.args then
			Logger.flag(player, "remote-args", rf.Name .. ": too many args")
			return nil
		end

		for i, expected in ipairs(schema.args) do
			local v = args[i]
			local optional = expected:sub(-1) == "?"
			if optional then
				expected = expected:sub(1, -2)
			end
			if v == nil then
				if optional or expected == "nil" then
					continue
				end
				Logger.flag(player, "remote-args", rf.Name .. ": missing arg " .. i)
				return nil
			end
			if not typeOk(v, expected) then
				Logger.flag(
					player,
					"remote-args",
					string.format(
						"%s: arg %d expected %s, got %s",
						rf.Name,
						i,
						expected,
						typeof(v)
					)
				)
				return nil
			end
			if not finiteOk(v) then
				Logger.flag(player, "remote-args", rf.Name .. ": non-finite arg " .. i)
				return nil
			end
			if not sizeOk(v, schema.maxArgSize) then
				Logger.flag(player, "remote-crasher", rf.Name .. ": oversized arg " .. i)
				return nil
			end
		end

		if not playerArgBound(player, args) then
			Logger.flag(player, "remote-args", rf.Name .. ": arg names another player")
			return nil
		end

		SessionGuard.ping(player)

		local results = { pcall(handler, player, ...) }
		if not results[1] then
			Logger.log("handler error in " .. rf.Name .. ": " .. tostring(results[2]))
			return nil
		end
		return table.unpack(results, 2)
	end
end



local MovementGuard = {}
local moveLast = {}
local moveExempt = {}
local flyAir = {}

function MovementGuard.exempt(player, cframe)
	moveExempt[player.UserId] = cframe.Position
end

function MovementGuard.start()
	local cfg = Config.movement
	if not cfg.enabled then
		return
	end
	task.spawn(function()
		while true do
			task.wait(cfg.checkInterval)
			MovementGuard.checkAll(cfg)
		end
	end)
	local function watchPlayer(player)
		player.CharacterAdded:Connect(function()
			moveLast[player.UserId] = nil
			moveExempt[player.UserId] = nil
			flyAir[player.UserId] = 0
		end)
	end
	Players.PlayerAdded:Connect(watchPlayer)
	for _, player in ipairs(Players:GetPlayers()) do
		watchPlayer(player)
	end
	Players.PlayerRemoving:Connect(function(player)
		moveLast[player.UserId] = nil
		moveExempt[player.UserId] = nil
		flyAir[player.UserId] = nil
	end)
end

function MovementGuard.checkAll(cfg)
	local dt = cfg.checkInterval
	for _, player in ipairs(Players:GetPlayers()) do
		local character = player.Character
		local hrp = character and character:FindFirstChild("HumanoidRootPart")
		local humanoid = character and character:FindFirstChildOfClass("Humanoid")
		if not isTrusted(player) and hrp and humanoid and humanoid.Health &gt; 0 then
			local uid = player.UserId
			local pos = hrp.Position

			if moveExempt[uid] then
				moveLast[uid] = moveExempt[uid]
				moveExempt[uid] = nil
			elseif cfg.ignoreSeated and humanoid.Seated then
				moveLast[uid] = pos
			else
				local state = humanoid:GetState()
				if
					state == Enum.HumanoidStateType.Physics
					or state == Enum.HumanoidStateType.Dead
				then
					moveLast[uid] = pos
				else
					local prev = moveLast[uid]
					moveLast[uid] = pos
					if prev then
						local delta = pos - prev
						local hDist = Vector3.new(delta.X, 0, delta.Z).Magnitude
						local vDist = math.abs(delta.Y)
						local speed = humanoid.WalkSpeed
						local hAllowed = (speed * cfg.tolerance) * dt + 2
						local vAllowed = (speed * cfg.tolerance) * dt + 30
						if hDist &gt; hAllowed or vDist &gt; vAllowed then
							Logger.flag(
								player,
								"movement",
								string.format(
									"displaced h=%.1f v=%.1f in %.2fs (allowed h=%.1f v=%.1f)",
									hDist,
									vDist,
									dt,
									hAllowed,
									vAllowed
								)
							)
							
							
							
							
							
							if cfg.rollback and not Config.auditOnly and prev then
								hrp.CFrame = CFrame.new(prev)
								hrp.AssemblyLinearVelocity = Vector3.zero
								moveLast[uid] = prev
							end
						end

						
						
						
						
						
						if state ~= Enum.HumanoidStateType.Swimming then
							local flyParams = RaycastParams.new()
							flyParams.FilterType = Enum.RaycastFilterType.Exclude
							flyParams.FilterDescendantsInstances = { character }
							local ground = Workspace:Raycast(pos, Vector3.new(0, -6, 0), flyParams)
							if not ground and math.abs(hrp.AssemblyLinearVelocity.Y) &lt; 2 then
								flyAir[uid] = (flyAir[uid] or 0) + dt
								if flyAir[uid] &gt; cfg.flySeconds then
									Logger.flag(player, "fly", string.format("hovering %.1fs", flyAir[uid]))
									flyAir[uid] = 0
								end
							else
								flyAir[uid] = 0
							end
						end

						
						
						
						
						if cfg.flingSpeed &gt; 0 then
							local hVel = Vector3.new(
								hrp.AssemblyLinearVelocity.X,
								0,
								hrp.AssemblyLinearVelocity.Z
							).Magnitude
							if hVel &gt; cfg.flingSpeed then
								local nearest, nearestD = nil, 30
								for _, other in ipairs(Players:GetPlayers()) do
									if other ~= player and other.Character then
										local oroot = other.Character:FindFirstChild("HumanoidRootPart")
										if oroot then
											local d = (oroot.Position - pos).Magnitude
											if d &lt; nearestD then
												nearest, nearestD = other, d
											end
										end
									end
								end
								Logger.flag(player, "fling", string.format(
									"h-vel %.0f (nearest %s)",
									hVel,
									nearest and nearest.Name or "none"
								))
							end
						end
					end
				end
			end
		end
	end
end



local NoclipGuard = {}
local noclipLast = {}
local noclipSkip = {}

function NoclipGuard.exempt(player)
	noclipSkip[player.UserId] = true
end

function NoclipGuard.start()
	local cfg = Config.noclip
	if not cfg.enabled then
		return
	end
	task.spawn(function()
		while true do
			task.wait(cfg.checkInterval)
			NoclipGuard.checkAll(cfg)
		end
	end)
	local function watchPlayer(player)
		player.CharacterAdded:Connect(function()
			noclipLast[player.UserId] = nil
			noclipSkip[player.UserId] = nil
		end)
	end
	Players.PlayerAdded:Connect(watchPlayer)
	for _, player in ipairs(Players:GetPlayers()) do
		watchPlayer(player)
	end
	Players.PlayerRemoving:Connect(function(player)
		noclipLast[player.UserId] = nil
		noclipSkip[player.UserId] = nil
	end)
end

function NoclipGuard.checkAll(cfg)
	for _, player in ipairs(Players:GetPlayers()) do
		local character = player.Character
		local hrp = character and character:FindFirstChild("HumanoidRootPart")
		local humanoid = character and character:FindFirstChildOfClass("Humanoid")
		if not isTrusted(player) and hrp and humanoid and humanoid.Health &gt; 0 then
			local uid = player.UserId
			local pos = hrp.Position

			if noclipSkip[uid] then
				noclipSkip[uid] = nil
				noclipLast[uid] = pos
			elseif cfg.ignoreSeated and humanoid.Seated then
				noclipLast[uid] = pos
			else
				local prev = noclipLast[uid]
				noclipLast[uid] = pos
				if prev and (pos - prev).Magnitude &gt; 1 then
					local params = RaycastParams.new()
					params.FilterType = Enum.RaycastFilterType.Exclude
					params.FilterDescendantsInstances = { character }

					local dir = pos - prev
					local hit = Workspace:Raycast(prev, dir, params)
					if hit and hit.Instance.CanCollide and hit.Normal.Y &lt; 0.7 then
						Logger.flag(player, "noclip", "crossed " .. hit.Instance:GetFullName())
					else
						local overlap = OverlapParams.new()
						overlap.FilterType = Enum.RaycastFilterType.Exclude
						overlap.FilterDescendantsInstances = { character }
						local parts =
							Workspace:GetPartBoundsInBox(hrp.CFrame, hrp.Size * 0.5, overlap)
						for _, part in ipairs(parts) do
							if part.CanCollide and part:IsDescendantOf(Workspace) then
								Logger.flag(player, "noclip", "inside " .. part:GetFullName())
								break
							end
						end
					end
				end
			end
		end
	end
end



local CombatGuard = {}
local loadouts = {}

function CombatGuard.start()
	Players.PlayerRemoving:Connect(function(player)
		loadouts[player.UserId] = nil
	end)
end

function CombatGuard.register(player, spec)
	assert(
		spec.magSize and spec.fireInterval and spec.reloadTime,
		"registerWeapon: spec needs magSize, fireInterval, reloadTime"
	)
	loadouts[player.UserId] = {
		ammo = spec.magSize,
		magSize = spec.magSize,
		fireInterval = spec.fireInterval,
		reloadTime = spec.reloadTime,
		lastShot = 0,
		reloadEnd = 0,
		reloading = false,
		intervals = {},
	}
end

function CombatGuard.tryFire(player)
	if not Config.combat.enabled then
		return true
	end
	if isTrusted(player) then
		return true
	end
	local w = loadouts[player.UserId]
	if not w then
		return true
	end
	local now = os.clock()
	if w.reloading then
		if now &gt;= w.reloadEnd then
			w.ammo = w.magSize
			w.reloading = false
		else
			return false
		end
	end
	if w.ammo &lt;= 0 then
		Logger.flag(player, "combat", "fired with empty mag")
		return false
	end
	local interval = now - w.lastShot
	if w.lastShot &gt; 0 and interval &lt; w.fireInterval * 0.9 then
		Logger.flag(
			player,
			"combat",
			string.format("fire-rate %.3fs &lt; %.3fs", interval, w.fireInterval)
		)
		return false
	end
	w.ammo -= 1
	if w.lastShot &gt; 0 then
		table.insert(w.intervals, interval)
		if #w.intervals &gt; Config.combat.consistencyWindow then
			table.remove(w.intervals, 1)
		end
		if #w.intervals &gt;= Config.combat.consistencyWindow then
			local avg = 0
			for _, v in ipairs(w.intervals) do
				avg += v
			end
			avg /= #w.intervals
			local consistent = avg &gt; 0.01
			if consistent then
				for _, v in ipairs(w.intervals) do
					if math.abs(v - avg) / avg &gt; Config.combat.consistencyTolerance then
						consistent = false
						break
					end
				end
			end
			if consistent then
				Logger.warn(player, "combat", "inhuman fire consistency")
				w.intervals = {}
			end
		end
	end
	w.lastShot = now
	return true
end

function CombatGuard.reload(player)
	if not Config.combat.enabled then
		return
	end
	if isTrusted(player) then
		return
	end
	local w = loadouts[player.UserId]
	if not w then
		return
	end
	if w.reloading then
		Logger.flag(player, "combat", "reload timer skipped")
		return
	end
	w.reloading = true
	w.reloadEnd = os.clock() + w.reloadTime
end



local HitValidator = {}

function HitValidator.validate(player, targetPosition, maxRange)
	if isTrusted(player) then
		return true
	end
	if typeof(targetPosition) ~= "Vector3" or typeof(maxRange) ~= "number" then
		return false
	end
	local character = player.Character
	local hrp = character and character:FindFirstChild("HumanoidRootPart")
	if not hrp then
		return false
	end
	local dist = (hrp.Position - targetPosition).Magnitude
	if dist &gt; maxRange then
		Logger.flag(
			player,
			"kill-aura",
			string.format("hit at %.1f (max %.1f)", dist, maxRange)
		)
		return false
	end
	return true
end



local InventoryGuard = {}
local inventories = {}
local invLocks = {}
local invStore = nil

function InventoryGuard.setDataStore(ds)
	invStore = ds
end

local function invPersist(player)
	if not invStore then
		return
	end
	local uid = player.UserId
	local data = inventories[uid] or {}
	local ok, err = pcall(function()
		invStore:UpdateAsync("aegis_inv_" .. uid, function()
			return data
		end)
	end)
	if not ok then
		Logger.log("inventory persist failed: " .. tostring(err))
	end
end

local function acquire(uids)
	local waited = 0
	while waited &lt; 5 do
		local free = true
		for _, uid in ipairs(uids) do
			if invLocks[uid] then
				free = false
				break
			end
		end
		if free then
			for _, uid in ipairs(uids) do
				invLocks[uid] = true
			end
			return true
		end
		task.wait(0.05)
		waited += 0.05
	end
	return false
end

local function release(uids)
	for _, uid in ipairs(uids) do
		invLocks[uid] = nil
	end
end

local function withLock(uids, fn)
	if not acquire(uids) then
		return false
	end
	local ok, result = pcall(fn)
	release(uids)
	if not ok then
		Logger.log("inventory transaction error: " .. tostring(result))
		return false
	end
	return result
end







local MAX_STACK = 1e12

local function cleanAmount(amount)
	if typeof(amount) ~= "number" or amount ~= amount
		or amount == math.huge or amount == -math.huge
	then
		return 1
	end
	return math.clamp(math.floor(amount), 1, MAX_STACK)
end

local function cleanStored(value)
	if typeof(value) ~= "number" or value ~= value
		or value == math.huge or value == -math.huge or value &lt; 0
	then
		return 0
	end
	return math.min(math.floor(value), MAX_STACK)
end

local function validItemId(itemId)
	return typeof(itemId) == "string" or typeof(itemId) == "number"
end

local function getInv(player)
	local inv = inventories[player.UserId]
	if not inv then
		inv = {}
		inventories[player.UserId] = inv
	end
	return inv
end





function InventoryGuard.addHoneypotItem(itemId)
	Config.honeypot.items[itemId] = true
end

local function isHoneypotItem(itemId)
	return Config.honeypot.items[itemId] == true
end

function InventoryGuard.load(player, data)
	local clean = {}
	if typeof(data) == "table" then
		for itemId, value in pairs(data) do
			if validItemId(itemId) then
				if isHoneypotItem(itemId) then
					
					
					Logger.flag(player, "honeypot-item", "loaded " .. tostring(itemId))
				else
					local n = cleanStored(value)
					if n &gt; 0 then
						clean[itemId] = n
					end
				end
			end
		end
	end
	inventories[player.UserId] = clean
end

function InventoryGuard.start()
	Players.PlayerRemoving:Connect(function(player)
		inventories[player.UserId] = nil
		invLocks[player.UserId] = nil
	end)
end

function InventoryGuard.get(player)
	local copy = {}
	for k, v in pairs(getInv(player)) do
		copy[k] = v
	end
	return copy
end

function InventoryGuard.has(player, itemId, amount)
	if not validItemId(itemId) then
		return false
	end
	amount = cleanAmount(amount or 1)
	return cleanStored(getInv(player)[itemId]) &gt;= amount
end

function InventoryGuard.give(player, itemId, amount)
	if not validItemId(itemId) then
		return false
	end
	if isHoneypotItem(itemId) then
		Logger.flag(player, "honeypot-item", "granted " .. tostring(itemId))
		return false
	end
	amount = cleanAmount(amount or 1)
	return withLock({ player.UserId }, function()
		local inv = getInv(player)
		inv[itemId] = math.min(cleanStored(inv[itemId]) + amount, MAX_STACK)
		invPersist(player)
		return true
	end)
end

function InventoryGuard.take(player, itemId, amount)
	if not validItemId(itemId) then
		return false
	end
	amount = cleanAmount(amount or 1)
	return withLock({ player.UserId }, function()
		local inv = getInv(player)
		if cleanStored(inv[itemId]) &lt; amount then
			return false
		end
		inv[itemId] = cleanStored(inv[itemId]) - amount
		if inv[itemId] &lt;= 0 then
			inv[itemId] = nil
		end
		invPersist(player)
		return true
	end)
end

function InventoryGuard.trade(fromPlayer, toPlayer, itemId, amount)
	if not validItemId(itemId) then
		return false
	end
	amount = cleanAmount(amount or 1)
	local first, second = fromPlayer, toPlayer
	if fromPlayer.UserId &gt; toPlayer.UserId then
		first, second = toPlayer, fromPlayer
	end
	return withLock({ first.UserId, second.UserId }, function()
		local fromInv = getInv(fromPlayer)
		if cleanStored(fromInv[itemId]) &lt; amount then
			Logger.flag(fromPlayer, "dupe", "trade without owning " .. tostring(itemId))
			return false
		end
		fromInv[itemId] = cleanStored(fromInv[itemId]) - amount
		if fromInv[itemId] &lt;= 0 then
			fromInv[itemId] = nil
		end
		local toInv = getInv(toPlayer)
		toInv[itemId] = math.min(cleanStored(toInv[itemId]) + amount, MAX_STACK)
		invPersist(fromPlayer)
		invPersist(toPlayer)
		return true
	end)
end



local ShopGuard = {}
local catalog = {}
local receipts = {}

function ShopGuard.start()
	Players.PlayerRemoving:Connect(function(player)
		receipts[player.UserId] = nil
	end)
end

function ShopGuard.setCatalog(c)
	local old = catalog
	catalog = c or {}
	return old
end






function ShopGuard.buy(player, itemId, receiptId)
	local entry = catalog[itemId]
	if not entry then
		Logger.flag(player, "shop", "buy unknown item: " .. tostring(itemId))
		return false
	end
	local seen = nil
	if receiptId ~= nil then
		seen = receipts[player.UserId]
		if not seen then
			seen = {}
			receipts[player.UserId] = seen
		end
		if seen[receiptId] then
			return false
		end
	end
	if not InventoryGuard.take(player, entry.currency or "coins", entry.price) then
		return false
	end
	InventoryGuard.give(player, itemId, 1)
	if seen then
		seen[receiptId] = os.clock()
		local n = 0
		for _ in pairs(seen) do
			n += 1
		end
		if n &gt; 64 then
			receipts[player.UserId] = { [receiptId] = os.clock() }
		end
	end
	return true
end



local BehaviorGuard = {}
local actionStreams = {}
local actionSessions = {}
local adaptiveStreams = {}

function BehaviorGuard.start()
	Players.PlayerRemoving:Connect(function(player)
		actionSessions[player.UserId] = nil
		local prefix = player.UserId .. "\0"
		for k in pairs(actionStreams) do
			if k:sub(1, #prefix) == prefix then
				actionStreams[k] = nil
			end
		end
		for k in pairs(adaptiveStreams) do
			if k:sub(1, #prefix) == prefix then
				adaptiveStreams[k] = nil
			end
		end
	end)
end

function BehaviorGuard.record(player, action)
	if not Config.behavior.enabled then
		return
	end
	if isTrusted(player) then
		return
	end
	local cfg = Config.behavior
	local now = os.clock()
	local uid = player.UserId

	local sess = actionSessions[uid]
	if not sess or now - sess.last &gt; cfg.breakReset then
		sess = { start = now, last = now, actions = 0 }
		actionSessions[uid] = sess
	end
	sess.last = now
	sess.actions += 1
	if sess.actions &gt;= cfg.marathonActions and now - sess.start &gt;= cfg.marathonSeconds then
		Logger.warn(player, "autofarm", "marathon: " .. sess.actions .. " actions")
		actionSessions[uid] = nil
	end

	local key = uid .. "\0" .. action
	local s = actionStreams[key]
	if not s then
		s = {}
		actionStreams[key] = s
	end
	table.insert(s, now)
	if #s &gt; 120 then
		table.remove(s, 1)
	end
	if #s &gt;= cfg.consistencyWindow + 1 then
		local intervals = {}
		for i = #s - cfg.consistencyWindow + 1, #s do
			table.insert(intervals, s[i] - s[i - 1])
		end
		local avg = 0
		for _, v in ipairs(intervals) do
			avg += v
		end
		avg /= #intervals
		if avg &gt; 0.05 then
			local consistent = true
			for _, v in ipairs(intervals) do
				if math.abs(v - avg) / avg &gt; cfg.consistencyTolerance then
					consistent = false
					break
				end
			end
			if consistent then
				Logger.warn(player, "autofarm", action .. ": metronome timing")
				actionStreams[key] = {}
			end
		end
	end

	
	
	
	
	
	local ast = adaptiveStreams[key]
	if not ast then
		ast = { last = 0, intervals = {} }
		adaptiveStreams[key] = ast
	end
	if ast.last &gt; 0 then
		table.insert(ast.intervals, now - ast.last)
		if #ast.intervals &gt; cfg.adaptiveWindow then
			table.remove(ast.intervals, 1)
		end
		if #ast.intervals &gt;= 20 then
			local mean = 0
			for _, v in ipairs(ast.intervals) do
				mean += v
			end
			mean /= #ast.intervals
			local variance = 0
			for _, v in ipairs(ast.intervals) do
				variance += (v - mean) * (v - mean)
			end
			variance /= #ast.intervals
			local cv = mean &gt; 0 and math.sqrt(variance) / mean or 0
			if mean &lt; cfg.adaptiveMaxMean and cv &lt; cfg.adaptiveMaxCV then
				Logger.warn(player, "autofarm", string.format(
					"%s: bot-like timing (CV %.3f)", action, cv
				))
				ast.intervals = {}
			end
		end
	end
	ast.last = now
end






local ClientCompanion = {}
local lastPing = {}

function ClientCompanion.start()
	local folder = ReplicatedStorage:FindFirstChild("FTAegisHoneypots")
	if not folder then
		folder = Instance.new("Folder")
		folder.Name = "FTAegisHoneypots"
		folder.Parent = ReplicatedStorage
	end
	if folder:FindFirstChild("AegisClientPing") then
		return
	end
	local ping = Instance.new("RemoteEvent")
	ping.Name = "AegisClientPing"
	ping.Parent = folder
	ping.OnServerEvent:Connect(function(player)
		SessionGuard.ping(player)
		lastPing[player.UserId] = os.clock()
	end)
	Players.PlayerRemoving:Connect(function(player)
		lastPing[player.UserId] = nil
	end)
end

function ClientCompanion.status(player)
	local t = lastPing[player.UserId]
	if not t then
		return nil
	end
	return os.clock() - t
end



local started = false

local function deepMerge(dst, src)
	for k, v in pairs(src) do
		if typeof(v) == "table" and typeof(dst[k]) == "table" then
			deepMerge(dst[k], v)
		else
			dst[k] = v
		end
	end
end







local HoneypotGuard = {}

function HoneypotGuard.start()
	if not Config.honeypot.enabled then
		return
	end
	local folder = ReplicatedStorage:FindFirstChild("Remotes")
	if not folder then
		folder = Instance.new("Folder")
		folder.Name = "Remotes"
		folder.Parent = ReplicatedStorage
	end
	if not folder:IsA("Folder") then return end
	for _, name in ipairs(Config.honeypot.names) do
		if not folder:FindFirstChild(name) then
			local decoy = Instance.new("RemoteEvent")
			decoy.Name = name
			decoy.Parent = folder
			decoy.OnServerEvent:Connect(function(player)
				Logger.flag(player, "honeypot", name)
			end)
		end
	end
end







BanGuard = {}
local banStore = nil

local function banStoreReady()
	if banStore then
		return true
	end
	local ok, store = pcall(function()
		return DataStoreService:GetDataStore(Config.bans.storeName)
	end)
	if ok then
		banStore = store
	end
	return banStore ~= nil
end

function BanGuard.ban(userId, durationSeconds, reason)
	if not banStoreReady() then
		return false
	end
	local record = {
		untilAt = os.time() + math.max(60, math.floor(durationSeconds or 3600)),
		reason = tostring(reason or "banned"),
	}
	local ok = pcall(function()
		banStore:SetAsync("ban_" .. userId, record)
	end)
	if ok then
		local player = Players:GetPlayerByUserId(userId)
		if player then
			pcall(Logger.kick, player, "Banned: " .. record.reason)
		end
	end
	return ok
end

function BanGuard.unban(userId)
	if not banStoreReady() then
		return false
	end
	return pcall(function()
		banStore:RemoveAsync("ban_" .. userId)
	end)
end

function BanGuard.check(player)
	if not banStoreReady() then
		return
	end
	local ok, record = pcall(function()
		return banStore:GetAsync("ban_" .. player.UserId)
	end)
	if ok and typeof(record) == "table" and typeof(record.untilAt) == "number" then
		if record.untilAt &gt; os.time() then
			Logger.kick(player, "Banned: " .. tostring(record.reason or ""))
		else
			BanGuard.unban(player.UserId)
		end
	end
end

local banStarted = false

function BanGuard.start()
	if banStarted then
		return
	end
	if not Config.bans.enabled then
		return
	end
	banStarted = true
	Players.PlayerAdded:Connect(BanGuard.check)
	for _, player in ipairs(Players:GetPlayers()) do
		task.spawn(BanGuard.check, player)
	end
end





local function sanitizeData(value, depth)
	depth = depth or 0
	local t = typeof(value)
	if t == "number" then
		if value ~= value or value == math.huge or value == -math.huge then
			return 0
		end
		return value
	elseif t == "string" or t == "boolean" then
		return value
	elseif t == "table" then
		if depth &gt;= 8 then
			return nil
		end
		local out = {}
		for k, v in pairs(value) do
			local keyOk = typeof(k) == "string" or typeof(k) == "number"
			local cleaned = sanitizeData(v, depth + 1)
			if keyOk and cleaned ~= nil then
				out[k] = cleaned
			end
		end
		return out
	end
	return nil
end




local presets = {
	audit = { auditOnly = true, kickOnDetect = false },
	casual = { auditOnly = false, kickOnDetect = true, flagThreshold = 3 },
	strict = {
		auditOnly = false,
		kickOnDetect = true,
		flagThreshold = 2,
		bans = { enabled = true },
		escalation = { banAt = 4, banSeconds = 3600, permAt = 8 },
	},
}

function Aegis.preset(name)
	local p = presets[name]
	assert(p, "Aegis.preset: unknown preset '" .. tostring(name) .. "' (audit/casual/strict)")
	Aegis.configure(p)
	if p.bans and p.bans.enabled then
		BanGuard.start()
	end
	return Aegis
end

function Aegis.configure(overrides)
	deepMerge(Config, overrides or {})
	return Aegis
end

function Aegis.init(options)
	if started then
		return Aegis
	end
	started = true
	Aegis.configure(options)
	MovementGuard.start()
	NoclipGuard.start()
	SessionGuard.start()
	CombatGuard.start()
	InventoryGuard.start()
	BehaviorGuard.start()
	HoneypotGuard.start()
	BanGuard.start()
	ShopGuard.start()
	if Config.webhookDigest then
		task.spawn(function()
			while true do
				task.wait(3600)
				Logger.flushDigest()
			end
		end)
	end
	Logger.log("Aegis v0.5 initialized")
	return Aegis
end

local function ensureStarted()
	if not started then
		Aegis.init()
	end
end

function Aegis.secure(remote, schema, handler)
	ensureStarted()
	return RemoteValidator.secure(remote, schema, handler)
end

function Aegis.secureFunction(rf, schema, handler)
	ensureStarted()
	return RemoteValidator.secureFunction(rf, schema, handler)
end

function Aegis.teleport(player, cframe)
	ensureStarted()
	MovementGuard.exempt(player, cframe)
	NoclipGuard.exempt(player)
	local hrp = player.Character and player.Character:FindFirstChild("HumanoidRootPart")
	if hrp then
		hrp.CFrame = cframe
	end
end

function Aegis.reportShot(player, aimDirection)
	ensureStarted()
	AimbotGuard.trackShot(player, aimDirection)
end

function Aegis.trust(player)
	trusted[player.UserId] = true
end

function Aegis.untrust(player)
	trusted[player.UserId] = nil
end

function Aegis.registerWeapon(player, spec)
	ensureStarted()
	CombatGuard.register(player, spec)
end

function Aegis.tryFire(player)
	ensureStarted()
	return CombatGuard.tryFire(player)
end

function Aegis.reloadWeapon(player)
	ensureStarted()
	CombatGuard.reload(player)
end

function Aegis.validateHit(player, targetPosition, maxRange)
	ensureStarted()
	return HitValidator.validate(player, targetPosition, maxRange)
end

function Aegis.ping(player)
	ensureStarted()
	SessionGuard.ping(player)
end

function Aegis.ban(userId, durationSeconds, reason)
	ensureStarted()
	return BanGuard.ban(userId, durationSeconds, reason)
end

function Aegis.unban(userId)
	ensureStarted()
	return BanGuard.unban(userId)
end

function Aegis.sanitizeData(value)
	return sanitizeData(value)
end

function Aegis.setDataStore(ds)
	InventoryGuard.setDataStore(ds)
end

function Aegis.loadInventory(player, data)
	ensureStarted()
	InventoryGuard.load(player, data)
end

function Aegis.getInventory(player)
	ensureStarted()
	return InventoryGuard.get(player)
end

function Aegis.hasItem(player, itemId, amount)
	ensureStarted()
	return InventoryGuard.has(player, itemId, amount)
end

function Aegis.giveItem(player, itemId, amount)
	ensureStarted()
	return InventoryGuard.give(player, itemId, amount)
end

function Aegis.takeItem(player, itemId, amount)
	ensureStarted()
	return InventoryGuard.take(player, itemId, amount)
end

function Aegis.tradeItems(fromPlayer, toPlayer, itemId, amount)
	ensureStarted()
	return InventoryGuard.trade(fromPlayer, toPlayer, itemId, amount)
end

function Aegis.setShop(catalog)
	ShopGuard.setCatalog(catalog)
end

function Aegis.buyItem(player, itemId, receiptId)
	ensureStarted()
	return ShopGuard.buy(player, itemId, receiptId)
end

function Aegis.recordAction(player, action)
	ensureStarted()
	BehaviorGuard.record(player, action)
end

function Aegis.validInstance(inst, className, mustBeInWorkspace)
	return validInstance(inst, className, mustBeInWorkspace)
end

function Aegis.addHoneypotItem(itemId)
	ensureStarted()
	return InventoryGuard.addHoneypotItem(itemId)
end

function Aegis.initClientCompanion()
	ensureStarted()
	return ClientCompanion.start()
end




function Aegis.getClientStatus(player)
	return ClientCompanion.status(player)
end

function Aegis.flushDigest()
	return Logger.flushDigest()
end







Aegis.Config = Config
Aegis.Logger = Logger

return Aegis
]====]</ProtectedString>
        </Properties>
      </Item>
      <Item class="ModuleScript" referent="RBXFT109">
        <Properties>
          <string name="Name">FT_ANTICHEAT_CONTROLLER_SOURCE</string>
          <ProtectedString name="Source">return [====[



local Players=game:GetService("Players")
local ReplicatedStorage=game:GetService("ReplicatedStorage")
local ServerStorage=game:GetService("ServerStorage")
local Workspace=game:GetService("Workspace")
local RunService=game:GetService("RunService")
-- ForgeTools 0.9.10: reject incompatible pre-existing bridge children before starting monitors.
local initialBridge=ReplicatedStorage:FindFirstChild("FTAntiCheatBridge")
if initialBridge then
    if not initialBridge:IsA("Folder") or initialBridge:GetAttribute("ForgeToolsManaged")~=true then
        warn("[FT AntiCheat] Unmanaged or invalid bridge; controller not started")
        return
    end
    local expected={Snapshot="RemoteFunction",GraphSnapshot="RemoteFunction",PlayerList="RemoteFunction",SetObserver="RemoteEvent"}
    for name,className in pairs(expected) do
        local remote=initialBridge:FindFirstChild(name)
        if remote and not remote:IsA(className) then
            warn("[FT AntiCheat] Incompatible bridge object "..name.."; controller not started")
            return
        end
    end
end
-- One active controller per installation folder. Prevent parallel sampling after duplicate launch.
local owner=script.Parent:FindFirstChild("ForgeToolsControllerOwner")
if owner and not owner:IsA("ObjectValue") then
    warn("[FT AntiCheat] Controller owner name conflict; controller not started")
    return
end
if not owner then
    owner=Instance.new("ObjectValue")
    owner.Name="ForgeToolsControllerOwner"
    owner.Parent=script.Parent
end
if owner.Value and owner.Value.Parent then
    warn("[FT AntiCheat] Another controller is active; duplicate skipped")
    return
end
owner.Value=script
local controllerActive=true
local function controllerRunning()
    return controllerActive and script.Parent~=nil and owner.Parent==script.Parent and owner.Value==script
end
script.Destroying:Connect(function()
    controllerActive=false
    if owner.Parent and owner.Value==script then owner.Value=nil end
end)
local Aegis=require(script.Parent:WaitForChild("Aegis"))
local GuardCore=require(script.Parent:WaitForChild("GuardCore"))
local guardCore=nil
local configModule=script.Parent:FindFirstChild("Config")
local config={}
if configModule and configModule:IsA("ModuleScript") then
    local ok,result=pcall(require,configModule)
    if ok and typeof(result)=="table" then config=result end
end
local function settingNumber(value,default,minimum,maximum)
    if typeof(value)~="number" or value~=value then return default end
    return math.clamp(value,minimum,maximum)
end
local function settingBool(value,default)
    if typeof(value)=="boolean" then return value end
    return default
end
local ADMIN_SETTING="AllowedAdminUserIds"
local MAX_EVENTS=300
local HISTORY_NAME="ForgeToolsAntiCheatEvents"
local entries=ServerStorage:FindFirstChild(HISTORY_NAME)
if not entries then
    entries=Instance.new("Folder")
    entries.Name=HISTORY_NAME
    entries.Parent=ServerStorage
end
local sequence=0
-- Keep at most MAX_EVENTS persisted records, one cleanup pass at startup.
local eventQueue={}
for _,child in ipairs(entries:GetChildren()) do
    if child:IsA("StringValue") then
        eventQueue[#eventQueue+1]=child
        local n=tonumber(child.Name:match("^(%d+)_"))
        if n then sequence=math.max(sequence,n) end
    end
end
table.sort(eventQueue,function(a,b) return a.Name&lt;b.Name end)
while #eventQueue&gt;MAX_EVENTS do
    local old=table.remove(eventQueue,1)
    if old.Parent==entries then old:Destroy() end
end
local function permitted(player)
    if not player then return false end
    local ids=tostring(script:GetAttribute(ADMIN_SETTING) or "")
    for id in ids:gmatch("%d+") do
        if tostring(player.UserId)==id then return true end
    end
    
    if game.CreatorType==Enum.CreatorType.User and game.CreatorId&gt;0 and player.UserId==game.CreatorId then
        return true
    end
    return false
end
local function addRecord(kind,player,detail)
    sequence+=1
    local uid=player and player.UserId or 0
    local username=player and player.Name or "Server"
    local record=Instance.new("StringValue")
    record.Name=string.format("%06d_%s",sequence,kind)
    record.Value=string.format("%s | %s (%d) | %s | %s",os.date("!%Y-%m-%d %H:%M:%S UTC"),username,uid,kind,string.sub(tostring(detail or ""),1,400))
    record.Parent=entries
    eventQueue[#eventQueue+1]=record
    if #eventQueue&gt;MAX_EVENTS then
        local oldest=table.remove(eventQueue,1)
        if oldest.Parent==entries then oldest:Destroy() end
    end
    
end


-- Guard adapters default disabled. Games must register trusted server-only adapters.
guardCore=GuardCore.init({eventSink=function(kind,player,detail)
    addRecord(kind,player,detail)
end})
script.Parent:SetAttribute("GuardCoreVersion","0.9.2")
script.Parent:SetAttribute("GuardMode","MonitorOnly")
script.Parent:SetAttribute("RemoteMonitoringMode","ObservedNotBlocked")
script.Parent:SetAttribute("AutomaticPunishmentsEnabled",false)
local localStrikeCounts={}
Aegis.Logger.log=function() end
Aegis.Logger.flag=function(player,category,detail)
    if not player then return 0 end
    local key=tostring(player.UserId)..":"..tostring(category)
    localStrikeCounts[key]=(localStrikeCounts[key] or 0)+1
    addRecord("FLAG/"..tostring(category),player,detail)
    return localStrikeCounts[key]
end
Aegis.Logger.warn=function(player,category,detail)
    addRecord("WARN/"..tostring(category),player,detail)
end
Aegis.Logger.kick=function(player,reason)
    
    addRecord("KICK_BLOCKED",player,reason)
end
Aegis.init({
    auditOnly=true,
    kickOnDetect=false,
    crossServer={enabled=false},
    bans={enabled=false},
    session={enabled=false},
    honeypot={enabled=false},
    
    movement={enabled=false,rollback=false,ignoreSeated=true},
    noclip={enabled=false,ignoreSeated=true},
    aimbot={enabled=false},
    combat={enabled=false},
    behavior={enabled=false},
    discordWebhook="",
})




local function readableNumber(value)
    if typeof(value)~="number" then return tostring(value) end
    if value~=value or math.abs(value)==math.huge then return tostring(value) end
    local negative=value&lt;0 and "-" or ""
    local absValue=math.abs(value)
    local output
    if absValue==math.floor(absValue) then
        output=string.format("%.0f",absValue)
    else
        output=string.format("%.2f",absValue):gsub("0+$",""):gsub("%.$","")
    end
    local integer,fraction=output:match("^(%d+)(.*)$")
    integer=(integer or output):reverse():gsub("(%d%d%d)","%1 "):reverse():gsub("^ ",""):gsub(" $","")
    return negative..integer..(fraction or "")
end
local economyConfig=typeof(config.Economy)=="table" and config.Economy or {}
local economyEnabled=settingBool(economyConfig.Enabled,true)
local economyCurrencies={}
local currencyNames=typeof(economyConfig.Currencies)=="table" and economyConfig.Currencies or {"Cash"}
for _,name in ipairs(currencyNames) do
    if typeof(name)=="string" and #name&gt;0 and #name&lt;=60 then
        economyCurrencies[name]=true
    end
end
local economyLargeGain=settingNumber(economyConfig.LargeGain,100000,1,1e12)
local economyRapidWindow=settingNumber(economyConfig.RapidGainWindow,3,0.2,60)
local economyRapidCount=math.floor(settingNumber(economyConfig.RapidGainCount,5,2,200))
local economyCooldown=settingNumber(economyConfig.AlertCooldown,8,1,120)
local economyAuthSeconds=settingNumber(economyConfig.AuthorizationSeconds,2,0.1,10)
local economyLogAuthorized=settingBool(economyConfig.LogAuthorizedChanges,false)
local economyAuthorize=script.Parent:FindFirstChild("EconomyAuthorize")
if not economyAuthorize then
    economyAuthorize=Instance.new("BindableEvent")
    economyAuthorize.Name="EconomyAuthorize"
    economyAuthorize.Parent=script.Parent
end
if economyAuthorize and not economyAuthorize:IsA("BindableEvent") then
    addRecord("BALANCE_CONFIG_ERROR",nil,"EconomyAuthorize name conflict; authorized-grant API unavailable")
    economyAuthorize=nil
end
local authorizedEconomy={}
local watchedEconomy={}
local function clearEconomy(player)
    local state=watchedEconomy[player.UserId]
    if state then
        for _,connection in ipairs(state.connections) do connection:Disconnect() end
        watchedEconomy[player.UserId]=nil
    end
    authorizedEconomy[player.UserId]=nil
end


if economyAuthorize then economyAuthorize.Event:Connect(function(player,currency,delta,reason)
    if not economyEnabled or typeof(player)~="Instance" or not player:IsA("Player") then return end
    if typeof(currency)~="string" or not economyCurrencies[currency] then return end
    if typeof(delta)~="number" or delta~=delta or math.abs(delta)==math.huge or delta==0 then return end
    local uid=player.UserId
    local grants=authorizedEconomy[uid]
    if not grants then grants={};authorizedEconomy[uid]=grants end
    grants[currency]={delta=delta,expires=os.clock()+economyAuthSeconds,reason=string.sub(tostring(reason or "authorized"),1,80)}
end) end
local function watchEconomy(player)
    clearEconomy(player)
    if not economyEnabled then return end
    local state={connections={},values={},watching={},stats=nil}
    watchedEconomy[player.UserId]=state
    local function track(stat)
        if not economyCurrencies[stat.Name] or not (stat:IsA("IntValue") or stat:IsA("NumberValue")) then return end
        if state.watching[stat] then return end
        state.watching[stat]=true
        local previous=stat.Value
        local increases={}
        local lastAlert=-1e9
        local connection=stat:GetPropertyChangedSignal("Value"):Connect(function()
            local nextValue=stat.Value
            local change=nextValue-previous
            previous=nextValue
            if change==0 then return end
            local now=os.clock()
            local grantList=authorizedEconomy[player.UserId]
            local grant=grantList and grantList[stat.Name]
            if grant and now&lt;=grant.expires and math.abs(grant.delta-change)&lt;0.0001 then
                grantList[stat.Name]=nil
                if economyLogAuthorized then
                    addRecord("BALANCE_AUTHORIZED",player,string.format("%s %+g (%s)",stat.Name,change,grant.reason))
                end
                return
            end
            if grant and now&gt;grant.expires then grantList[stat.Name]=nil end
            if change&lt;=0 then return end
            increases[#increases+1]=now
            while #increases&gt;0 and increases[1]&lt;now-economyRapidWindow do
                table.remove(increases,1)
            end
            if now-lastAlert&lt;economyCooldown then return end
            local large=change&gt;=economyLargeGain
            local rapid=#increases&gt;=economyRapidCount
            if large or rapid then
                lastAlert=now
                addRecord("BALANCE_REVIEW",player,string.format(
                    "%s +%s -&gt; %s; %s; SERVER change, origin not proven",
                    stat.Name,readableNumber(change),readableNumber(nextValue),large and "large gain" or "rapid gains"))
            end
        end)
        table.insert(state.connections,connection)
    end
    local function attachStats(stats)
        if not stats:IsA("Folder") or stats.Name~="leaderstats" or state.stats==stats then return end
        state.stats=stats
        for _,stat in ipairs(stats:GetChildren()) do track(stat) end
        table.insert(state.connections,stats.ChildAdded:Connect(track))
    end
    local stats=player:FindFirstChild("leaderstats")
    if stats then attachStats(stats) end
    table.insert(state.connections,player.ChildAdded:Connect(attachStats))
end
if economyEnabled then
    Players.PlayerAdded:Connect(watchEconomy)
    for _,player in ipairs(Players:GetPlayers()) do watchEconomy(player) end
    addRecord("BALANCE_MONITOR",nil,"Monitoring leaderstats currencies; review alerts only; no punishment")
else
    addRecord("BALANCE_MONITOR",nil,"Economy monitoring disabled in Config")
end
Players.PlayerRemoving:Connect(clearEconomy)




local MONITOR_PERIOD=0.15
local lastPositions={}
local recentRespawn={}
local recentNoclip={}
local teleportExempt={}
local movementWarningAt={}
local lastDetectedMove={}
local liveProbeActive={}
local function classifyMove(fromPos,toPos,dt,walkSpeed)
    if dt&lt;=0 or dt&gt;1.5 then return nil end 
    local delta=toPos-fromPos
    local horizontal=Vector3.new(delta.X,0,delta.Z).Magnitude
    local vertical=math.abs(delta.Y)
    local allowed=math.max(12, math.max(0,walkSpeed)*dt*2.5+8)
    
    if horizontal&gt;allowed or vertical&gt;75 then
        return {horizontal=horizontal,vertical=vertical,allowed=allowed,dt=dt}
    end
    return nil
end
local function recordMove(player,fromPos,toPos,dt,speed)
    local result=classifyMove(fromPos,toPos,dt,speed)
    if not result then return false end
    local now=os.clock()
    if liveProbeActive[player.UserId] and result.horizontal&gt;=80 then
        lastDetectedMove[player.UserId]=now
    end
    if now-(movementWarningAt[player.UserId] or -1e9)&gt;0.9 then
        movementWarningAt[player.UserId]=now
        addRecord("MOVEMENT",player,string.format("h=%.1f, v=%.1f, allowed h=%.1f, dt=%.3fs",result.horizontal,result.vertical,result.allowed,result.dt))
    end
    return true
end
local function watchCharacter(player)
    lastPositions[player.UserId]=nil
    recentNoclip[player.UserId]=nil
    recentRespawn[player.UserId]=os.clock()+2
end
Players.PlayerAdded:Connect(function(player)
    player.CharacterAdded:Connect(function() watchCharacter(player) end)
    if player.Character then watchCharacter(player) end
end)
for _,p in ipairs(Players:GetPlayers()) do
    p.CharacterAdded:Connect(function() watchCharacter(p) end)
    if p.Character then watchCharacter(p) end
end
Players.PlayerRemoving:Connect(function(p)
    local id=p.UserId
    lastPositions[id]=nil;recentNoclip[id]=nil;recentRespawn[id]=nil
    teleportExempt[id]=nil;movementWarningAt[id]=nil
    lastDetectedMove[id]=nil;liveProbeActive[id]=nil
end)

local allowTeleport=script.Parent:FindFirstChild("AllowTeleport")
if not allowTeleport then
    allowTeleport=Instance.new("BindableEvent")
    allowTeleport.Name="AllowTeleport";allowTeleport.Parent=script.Parent
end
local function exemptTeleport(player,seconds)
    if typeof(player)~="Instance" or not player:IsA("Player") then return end
    teleportExempt[player.UserId]=os.clock()+math.clamp(tonumber(seconds) or 2,0.1,10)
    lastPositions[player.UserId]=nil
end
allowTeleport.Event:Connect(exemptTeleport)


local originalTeleport=Aegis.teleport
Aegis.teleport=function(player,cframe)
    exemptTeleport(player,2)
    return originalTeleport(player,cframe)
end
task.spawn(function()
    while controllerRunning() do
        task.wait(MONITOR_PERIOD)
        if not controllerRunning() then break end
        local now=os.clock()
        for _,player in ipairs(Players:GetPlayers()) do
            local char=player.Character
            local root=char and char:FindFirstChild("HumanoidRootPart")
            local humanoid=char and char:FindFirstChildOfClass("Humanoid")
            local uid=player.UserId
            if root and humanoid and humanoid.Health&gt;0 then
                local pos=root.Position
                local prev=lastPositions[uid]
                lastPositions[uid]={pos=pos,time=now}
                local seated=humanoid.Sit or humanoid.SeatPart~=nil
                local state=humanoid:GetState()
                local exempt=now&lt;(recentRespawn[uid] or 0) or now&lt;(teleportExempt[uid] or 0)
                if prev and not seated and not exempt and state~=Enum.HumanoidStateType.Physics and state~=Enum.HumanoidStateType.Dead then
                    local dt=now-prev.time
                    local bad=recordMove(player,prev.pos,pos,dt,humanoid.WalkSpeed)
                    
                    local displacement=pos-prev.pos
                    if not bad and dt&lt;0.6 and displacement.Magnitude&gt;4 then
                        local params=RaycastParams.new()
                        params.FilterType=Enum.RaycastFilterType.Exclude
                        params.FilterDescendantsInstances={char}
                        local hit=Workspace:Raycast(prev.pos,displacement,params)
                        if hit and hit.Instance.CanCollide and math.abs(hit.Normal.Y)&lt;0.55 then
                            local prior=recentNoclip[uid]
                            if prior and now-prior.time&lt;1.4 and prior.part==hit.Instance then
                                addRecord("POSSIBLE_NOCLIP",player,"Crossed "..hit.Instance:GetFullName().." twice; review manually")
                                recentNoclip[uid]=nil
                            else
                                recentNoclip[uid]={time=now,part=hit.Instance}
                            end
                        end
                    end
                end
            else
                lastPositions[uid]=nil
            end
        end
    end
end)






local flySettings=typeof(config.Fly)=="table" and config.Fly or {}
local flyEnabled=settingBool(flySettings.Enabled,true)
local flyClearance=settingNumber(flySettings.MinGroundClearance,18,8,80)
local flyHoverSeconds=settingNumber(flySettings.HoverSeconds,2.75,1.5,15)
local flyAscendSeconds=settingNumber(flySettings.SustainedAscentSeconds,2.5,1.5,15)
local flyAlertCooldown=settingNumber(flySettings.AlertCooldown,15,5,120)
local flyState={}
if flyEnabled then
    task.spawn(function()
        while controllerRunning() do
            task.wait(0.20)
            if not controllerRunning() then break end
            local now=os.clock()
            for _,p in ipairs(Players:GetPlayers()) do
                local uid=p.UserId
                local char=p.Character
                local humanoid=char and char:FindFirstChildOfClass("Humanoid")
                local root=char and char:FindFirstChild("HumanoidRootPart")
                if not (root and humanoid and humanoid.Health&gt;0) then
                    flyState[uid]=nil
                else
                    local state=humanoid:GetState()
                    local ignored=humanoid.Sit or humanoid.SeatPart~=nil
                        or state==Enum.HumanoidStateType.Seated
                        or state==Enum.HumanoidStateType.Climbing
                        or state==Enum.HumanoidStateType.Swimming
                        or state==Enum.HumanoidStateType.Dead
                        or now&lt;(recentRespawn[uid] or 0)
                        or now&lt;(teleportExempt[uid] or 0)
                        or char:GetAttribute("FTAllowFlight")==true
                    local previous=flyState[uid]
                    if ignored then
                        flyState[uid]=nil
                    else
                        local params=RaycastParams.new()
                        params.FilterType=Enum.RaycastFilterType.Exclude
                        params.FilterDescendantsInstances={char}
                        params.IgnoreWater=false
                        local ground=Workspace:Raycast(root.Position,Vector3.new(0,-flyClearance,0),params)
                        local airborne=ground==nil and humanoid.FloorMaterial==Enum.Material.Air
                        local pos=root.Position
                        local sampleDt=previous and (now-previous.sampleTime) or 0
                        
                        
                        local observedVy=sampleDt&gt;0.01 and sampleDt&lt;0.75 and (pos.Y-previous.y)/sampleDt or nil
                        local current={y=pos.Y,sampleTime=now,
                            hoverSince=previous and previous.hoverSince or nil,
                            ascentSince=previous and previous.ascentSince or nil,
                            prevVy=observedVy,
                            lastAlert=previous and previous.lastAlert or -1e9}
                        if not airborne or not observedVy then
                            current.hoverSince=nil
                            current.ascentSince=nil
                        else
                            
                            
                            local hovering=math.abs(observedVy)&lt;=2.5
                            if hovering then
                                current.hoverSince=current.hoverSince or now
                            else
                                current.hoverSince=nil
                            end
                            
                            
                            local priorVy=previous and previous.prevVy
                            local acceleration=priorVy and (observedVy-priorVy)/sampleDt or nil
                            local poweredAscent=observedVy&gt;6 and acceleration~=nil and math.abs(acceleration)&lt;45
                            if poweredAscent then
                                current.ascentSince=current.ascentSince or now
                            else
                                current.ascentSince=nil
                            end
                            local hoverDuration=current.hoverSince and (now-current.hoverSince) or 0
                            local ascentDuration=current.ascentSince and (now-current.ascentSince) or 0
                            local reason=nil
                            if hoverDuration&gt;=flyHoverSeconds then reason="hover"
                            elseif ascentDuration&gt;=flyAscendSeconds then reason="controlled ascent" end
                            if reason and now-current.lastAlert&gt;=flyAlertCooldown then
                                current.lastAlert=now
                                addRecord("FLY_SUSPECTED",p,string.format(
                                    "%s; airborne %.1fs; server vy %.1f studs/s; clearance &gt;%.1f; review only",
                                    reason,reason=="hover" and hoverDuration or ascentDuration,
                                    observedVy,flyClearance))
                            end
                        end
                        flyState[uid]=current
                    end
                end
            end
        end
    end)
    addRecord("FLY_MONITOR",nil,"Air hover / controlled ascent review active; no punishment")
else
    addRecord("FLY_MONITOR",nil,"Fly monitor disabled in Config")
end
Players.PlayerRemoving:Connect(function(p) flyState[p.UserId]=nil end)

local graphConfig=typeof(config.Relationships)=="table" and config.Relationships or {}
local graphEnabled=settingBool(graphConfig.Enabled,true)
local graphMaxEvents=math.floor(settingNumber(graphConfig.MaxEvents,600,50,3000))
local graphMaxAge=settingNumber(graphConfig.MaxAgeHours,24,1,72)*3600
local graphEvents={}
local graphSeenIds={}
local graphUserNames={}
local graphRecord=script.Parent:FindFirstChild("RecordTransaction")
if not graphRecord then
    graphRecord=Instance.new("BindableEvent")
    graphRecord.Name="RecordTransaction"
    graphRecord.Parent=script.Parent
end
if not graphRecord:IsA("BindableEvent") then
    addRecord("GRAPH_CONFIG_ERROR",nil,"RecordTransaction name conflict")
    graphRecord=nil
end
local function graphUserId(input)
    if typeof(input)=="Instance" and input:IsA("Player") then return input.UserId,input.Name end
    if typeof(input)=="number" and input%1==0 and input&gt;0 and input&lt;1e16 then return input,nil end
    return nil,nil
end
local function recordGraphTransaction(event)
    if not graphEnabled or typeof(event)~="table" then return end
    local kind=event.kind
    if kind~="trade" and kind~="currency" and kind~="item" then return end
    local from,fromName=graphUserId(event.from)
    local to,toName=graphUserId(event.to)
    if not from or not to or from==to then return end
    local transactionId=event.id
    if typeof(transactionId)~="string" or #transactionId&lt;6 or #transactionId&gt;100 then return end
    local amount=event.amount
    if amount~=nil and (typeof(amount)~="number" or amount~=amount or math.abs(amount)==math.huge or amount&lt;0 or amount&gt;1e15) then return end
    local itemCount=event.itemCount
    if itemCount~=nil and (typeof(itemCount)~="number" or itemCount%1~=0 or itemCount&lt;0 or itemCount&gt;100000) then return end
    local now=os.time()
    for key,timestamp in pairs(graphSeenIds) do
        if now-timestamp&gt;graphMaxAge then graphSeenIds[key]=nil end
    end
    if graphSeenIds[transactionId] then return end
    graphSeenIds[transactionId]=now
    local eventName=event.currency
    if typeof(eventName)~="string" or #eventName&gt;35 then eventName="" end
    if fromName then graphUserNames[from]=fromName end
    if toName then graphUserNames[to]=toName end
    local record={id=transactionId,from=from,to=to,kind=kind,amount=amount or 0,itemCount=itemCount or 0,currency=eventName,time=now}
    table.insert(graphEvents,record)
    while #graphEvents&gt;graphMaxEvents do
        local old=table.remove(graphEvents,1)
        graphSeenIds[old.id]=nil
    end
end
if graphRecord then
    graphRecord.Event:Connect(recordGraphTransaction)
end
local graphBridgeInvokeAt={}
local graphUsernameCache={}
local function graphResolveUser(input)
    local query=tostring(input or "")
    if #query&gt;40 then return nil,"Слишком длинный запрос" end
    query=query:gsub("^%s+",""):gsub("%s+$",""):gsub("^@","")
    if query=="" then return nil,"Укажи ник игрока или UserId" end
    local numeric=tonumber(query)
    if numeric and numeric%1==0 and numeric&gt;0 and numeric&lt;1e16 then return numeric,nil end
    if not query:match("^[%w_]+$") or #query&gt;20 then return nil,"Недопустимый ник" end
    for _,p in ipairs(Players:GetPlayers()) do
        if p.Name:lower()==query:lower() then return p.UserId,nil end
    end
    for uid,name in pairs(graphUserNames) do
        if name:lower()==query:lower() then return uid,nil end
    end
    if graphUsernameCache[query:lower()] then return graphUsernameCache[query:lower()],nil end
    local ok,userId=pcall(function() return Players:GetUserIdFromNameAsync(query) end)
    if ok and userId then
        graphUsernameCache[query:lower()]=userId
        return userId,nil
    end
    return nil,"Игрок не найден. Можно ввести UserId."
end
local function graphName(userId)
    if graphUserNames[userId] then return graphUserNames[userId] end
    local active=Players:GetPlayerByUserId(userId)
    return active and active.Name or tostring(userId)
end
local function graphSnapshot(player,query,kind)
    if not permitted(player) then return nil end
    local nowClock=os.clock()
    if nowClock-(graphBridgeInvokeAt[player.UserId] or -1e9)&lt;0.65 then
        return {error="Подожди перед следующим запросом"}
    end
    graphBridgeInvokeAt[player.UserId]=nowClock
    if kind~="all" and kind~="trade" and kind~="currency" and kind~="item" then kind="all" end
    local center,errorText=graphResolveUser(query)
    if not center then return {error=errorText} end
    local now=os.time()
    local edges={}
    local neighbors={}
    local total=0
    local lastTime=0
    for _,e in ipairs(graphEvents) do
        if now-e.time&lt;=graphMaxAge and (kind=="all" or e.kind==kind) and (e.from==center or e.to==center) then
            local other=e.from==center and e.to or e.from
            local edgeKey=tostring(e.from)..":"..tostring(e.to)..":"..e.kind
            local edge=edges[edgeKey]
            if not edge then
                edge={from=e.from,to=e.to,kind=e.kind,count=0,amount=0,itemCount=0,last=0}
                edges[edgeKey]=edge
            end
            edge.count+=1
            edge.amount+=e.amount
            edge.itemCount+=e.itemCount
            edge.last=math.max(edge.last,e.time)
            neighbors[other]=true
            total+=1
            lastTime=math.max(lastTime,e.time)
        end
    end
    local results={}
    for _,edge in pairs(edges) do table.insert(results,edge) end
    table.sort(results,function(a,b)
        if a.count~=b.count then return a.count&gt;b.count end
        return a.last&gt;b.last
    end)
    local selected={}
    local nodes={{userId=center,name=graphName(center)}}
    local neighborIds={}
    for uid in pairs(neighbors) do table.insert(neighborIds,uid) end
    table.sort(neighborIds,function(a,b)
        local ac,bc=0,0
        for _,e in ipairs(results) do
            if e.from==a or e.to==a then ac+=e.count end
            if e.from==b or e.to==b then bc+=e.count end
        end
        return ac&gt;bc
    end)
    for i=1,math.min(24,#neighborIds) do
        local uid=neighborIds[i]
        selected[uid]=true
        table.insert(nodes,{userId=uid,name=graphName(uid)})
    end
    local visibleEdges={}
    for _,edge in ipairs(results) do
        local other=edge.from==center and edge.to or edge.from
        if selected[other] then table.insert(visibleEdges,edge) end
    end
    return {center=center,nodes=nodes,edges=visibleEdges,summary={operations=total,connections=#neighborIds,last=lastTime,shown=#visibleEdges},windowHours=graphMaxAge/3600,limited=#neighborIds&gt;24}
end
Players.PlayerRemoving:Connect(function(player)
    graphBridgeInvokeAt[player.UserId]=nil
end)

local bridge=ReplicatedStorage:FindFirstChild("FTAntiCheatBridge")
if bridge and bridge:GetAttribute("ForgeToolsManaged")~=true then
    warn("[FT AntiCheat] Bridge name conflict. Refusing to overwrite another system.")
    return
end
if not bridge then
    bridge=Instance.new("Folder")
    bridge.Name="FTAntiCheatBridge"
    bridge:SetAttribute("ForgeToolsManaged",true)
    bridge.Parent=ReplicatedStorage
end
local snapshot=bridge:FindFirstChild("Snapshot")
if not snapshot then
    snapshot=Instance.new("RemoteFunction")
    snapshot.Name="Snapshot"
    snapshot.Parent=bridge
end
snapshot.OnServerInvoke=function(player)
    if not permitted(player) then return nil end
    local result={}
    for _,entry in ipairs(entries:GetChildren()) do
        if entry:IsA("StringValue") then
            local kind=entry.Name:match("^%d+_(.+)$") or "SYSTEM"
            local category="system"
            if kind:find("FLY") then category="fly"
            elseif kind:find("MOVEMENT") or kind:find("NOCLIP") then category="movement"
            elseif kind:find("BALANCE") or kind:find("ECON") then category="economy"
            elseif kind:find("REMOTE") or kind:find("FLAG") or kind:find("WARN") then category="security" end
            table.insert(result,{key=entry.Name,text=entry.Value,category=category})
        end
    end
    table.sort(result,function(a,b) return a.key&gt;b.key end)
    return result
end
local graphRemote=bridge:FindFirstChild("GraphSnapshot")
if graphRemote and not graphRemote:IsA("RemoteFunction") then
    addRecord("GRAPH_CONFIG_ERROR",nil,"GraphSnapshot name conflict")
else
    if not graphRemote then
        graphRemote=Instance.new("RemoteFunction")
        graphRemote.Name="GraphSnapshot"
        graphRemote.Parent=bridge
    end
    graphRemote.OnServerInvoke=graphSnapshot
end

local listRemote=bridge:FindFirstChild("PlayerList")
if not listRemote then listRemote=Instance.new("RemoteFunction");listRemote.Name="PlayerList";listRemote.Parent=bridge end
listRemote.OnServerInvoke=function(viewer)
    local isAdmin=permitted(viewer)
    local playerList={}
    for _,other in ipairs(Players:GetPlayers()) do
        local observer=other:GetAttribute("FTObserverMode")==true
        if not observer or isAdmin then
            local cash=nil
            local stats=other:FindFirstChild("leaderstats")
            local cashValue=stats and stats:FindFirstChild("Cash")
            if isAdmin and cashValue and (cashValue:IsA("IntValue") or cashValue:IsA("NumberValue")) then
                cash=cashValue.Value
            end
            table.insert(playerList,{name=other.DisplayName,userId=other.UserId,observer=observer and isAdmin,cash=cash})
        end
    end
    table.sort(playerList,function(a,b) return a.name&lt;b.name end)
    return {enabled=script:GetAttribute("CustomPlayerListEnabled")==true,players=playerList}
end
local observerRemote=bridge:FindFirstChild("SetObserver")
if not observerRemote then observerRemote=Instance.new("RemoteEvent");observerRemote.Name="SetObserver";observerRemote.Parent=bridge end
observerRemote.OnServerEvent:Connect(function(p,enabled)
    if not permitted(p) or typeof(enabled)~="boolean" then return end
    if p:GetAttribute("FTObserverMode")==enabled then return end
    p:SetAttribute("FTObserverMode",enabled)
    addRecord("ADMIN_OBSERVER",p,enabled and "Observer enabled" or "Observer disabled")
end)
local remoteBudgets={}
local remoteAlertAt={}
local function guardBridgeRemote(player,remoteName,limit,window)
    local id=tostring(player.UserId)..":"..remoteName
    local now=os.clock()
    local state=remoteBudgets[id]
    if not state or now-state.start&gt;=window then
        state={start=now,count=0}
        remoteBudgets[id]=state
    end
    state.count+=1
    if state.count&gt;limit then
        if now-(remoteAlertAt[id] or -1e9)&gt;=5 then
            remoteAlertAt[id]=now
            addRecord("REMOTE_SPAM",player,remoteName.." exceeded "..limit.." calls/"..window.."s; rejected")
        end
        return false
    end
    return true
end
Players.PlayerRemoving:Connect(function(p)
    for key in pairs(remoteBudgets) do
        if key:sub(1,#tostring(p.UserId)+1)==tostring(p.UserId)..":" then
            remoteBudgets[key]=nil;remoteAlertAt[key]=nil
        end
    end
end)
addRecord("START",nil,"Monitor-only: FT measured-dt movement and possible noclip active; no punishments")






local function boolSetting(name,default)
    local value=script:GetAttribute(name)
    if typeof(value)=="boolean" then return value end
    return default
end
local function numberSetting(name,default,minimum,maximum)
    local value=script:GetAttribute(name)
    if typeof(value)~="number" or value~=value then return default end
    return math.clamp(value,minimum,maximum)
end
local remoteConfig=typeof(config.RemoteMonitor)=="table" and config.RemoteMonitor or {}
local MONITOR_GAME_REMOTES=settingBool(remoteConfig.Enabled,boolSetting("MonitorGameRemotes",true))
local GAME_REMOTE_WINDOW=settingNumber(remoteConfig.WindowSeconds,numberSetting("GameRemoteWindowSeconds",2,0.25,30),0.25,30)
local GAME_REMOTE_LIMIT=math.floor(settingNumber(remoteConfig.MaxCalls,numberSetting("GameRemoteMaxCalls",20,3,1000),3,1000))
local GAME_REMOTE_COOLDOWN=settingNumber(remoteConfig.AlertCooldown,numberSetting("GameRemoteAlertCooldown",10,1,120),1,120)
local watchedRemotes={}
local gameRemoteStates=setmetatable({},{__mode="k"})
local function isGameRemote(remote)
    return remote:IsA("RemoteEvent")
        and (remote:IsDescendantOf(ReplicatedStorage) or remote:IsDescendantOf(Workspace))
        and not remote:IsDescendantOf(bridge)
end
local function unwatchGameRemote(remote)
    local connection=watchedRemotes[remote]
    if connection then
        connection:Disconnect()
        watchedRemotes[remote]=nil
    end
    gameRemoteStates[remote]=nil
end
local function watchGameRemote(remote)
    if not MONITOR_GAME_REMOTES or watchedRemotes[remote] or not isGameRemote(remote) then return end
    local states={}
    gameRemoteStates[remote]=states
    watchedRemotes[remote]=remote.OnServerEvent:Connect(function(player,...)
        if not player or not player:IsA("Player") then return end
        
        local now=os.clock()
        local uid=player.UserId
        local state=states[uid]
        if not state then
            state={times={},lastAlert=-1e9}
            states[uid]=state
        end
        local times=state.times
        times[#times+1]=now
        
        if #times&gt;GAME_REMOTE_LIMIT+1 then table.remove(times,1) end
        local cut=now-GAME_REMOTE_WINDOW
        while #times&gt;0 and times[1]&lt;cut do
            table.remove(times,1)
        end
        if #times==GAME_REMOTE_LIMIT+1 and now-state.lastAlert&gt;=GAME_REMOTE_COOLDOWN then
            state.lastAlert=now
            addRecord("REMOTE_SPAM",player,string.format(
                "Game RemoteEvent %s: %d calls in %.2fs (limit %d); observed, NOT blocked",
                string.sub(remote:GetFullName(),1,180),#times,GAME_REMOTE_WINDOW,GAME_REMOTE_LIMIT))
        elseif #times&gt;GAME_REMOTE_LIMIT and now-state.lastAlert&gt;=GAME_REMOTE_COOLDOWN then
            state.lastAlert=now
            addRecord("REMOTE_SPAM",player,string.format(
                "Game RemoteEvent %s: %d calls in %.2fs; observed, NOT blocked",
                string.sub(remote:GetFullName(),1,180),#times,GAME_REMOTE_WINDOW))
        end
    end)
end
if MONITOR_GAME_REMOTES then
    for _,rootInstance in ipairs({ReplicatedStorage,Workspace}) do
        for _,obj in ipairs(rootInstance:GetDescendants()) do
            if obj:IsA("RemoteEvent") then watchGameRemote(obj) end
        end
        rootInstance.DescendantAdded:Connect(function(obj)
            if obj:IsA("RemoteEvent") then watchGameRemote(obj) end
        end)
        rootInstance.DescendantRemoving:Connect(function(obj)
            if watchedRemotes[obj] then unwatchGameRemote(obj) end
        end)
    end
    Players.PlayerRemoving:Connect(function(player)
        for _,states in pairs(gameRemoteStates) do
            states[player.UserId]=nil
        end
    end)
    addRecord("REMOTE_MONITOR",nil,string.format(
        "Game RemoteEvent audit active: %d calls / %.2fs; alerts only, no blocking",
        GAME_REMOTE_LIMIT,GAME_REMOTE_WINDOW))
else
    addRecord("REMOTE_MONITOR",nil,"Game RemoteEvent audit disabled by controller configuration")
end












]====]</ProtectedString>
        </Properties>
      </Item>
      <Item class="ModuleScript" referent="RBXFT110">
        <Properties>
          <string name="Name">FT_ANTICHEAT_CLIENT_SOURCE</string>
          <ProtectedString name="Source">return [====[

local Players=game:GetService("Players")
local RunService=game:GetService("RunService")
local ReplicatedStorage=game:GetService("ReplicatedStorage")
local player=Players.LocalPlayer
local bridge=ReplicatedStorage:WaitForChild("FTAntiCheatBridge",8)
if not bridge then return end
local snapshot=bridge:WaitForChild("Snapshot",5)
if not snapshot then return end
local function readEvents()
    local ok,result=pcall(function() return snapshot:InvokeServer() end)
    if ok and typeof(result)=="table" then return result end
    return nil
end
local initial=readEvents()
if not initial then return end 
local playerGui=player:WaitForChild("PlayerGui")
local previousGui=playerGui:FindFirstChild("FTAntiCheatAdmin")
if previousGui then previousGui:Destroy() end
local gui=Instance.new("ScreenGui")
gui.Name="FTAntiCheatAdmin"
gui.ResetOnSpawn=false
gui.DisplayOrder=80
gui.Parent=playerGui
local function inst(class,properties,parent)
    local o=Instance.new(class)
    for k,v in pairs(properties) do o[k]=v end
    o.Parent=parent
    return o
end
local TweenService=game:GetService("TweenService")
local UserInputService=game:GetService("UserInputService")
local function motion(button)
    button.AutoButtonColor=false
    local scale=inst("UIScale",{Name="Motion",Scale=1},button)
    local tween
    local function animate(target,seconds)
        if not button.Parent then return end
        if tween then tween:Cancel() end
        tween=TweenService:Create(scale,TweenInfo.new(seconds,Enum.EasingStyle.Quint,Enum.EasingDirection.Out),{Scale=target})
        tween:Play()
    end
    button.MouseEnter:Connect(function() animate(1.025,.20) end)
    button.MouseLeave:Connect(function() animate(1,.20) end)
    button.MouseButton1Down:Connect(function() animate(.945,.10) end)
    button.MouseButton1Up:Connect(function() animate(1.025,.22) end)
end
local dark=Color3.fromRGB(27,31,35)
local amber=Color3.fromRGB(217,119,6)
local top=inst("TextButton",{Name="Toggle",AnchorPoint=Vector2.new(1,0),Position=UDim2.new(1,-12,0,12),Size=UDim2.fromOffset(32,30),BackgroundColor3=Color3.fromRGB(30,34,40),BackgroundTransparency=.12,Text="",AutoButtonColor=false},gui)
inst("Frame",{Position=UDim2.fromOffset(9,11),Size=UDim2.fromOffset(14,1),BackgroundColor3=Color3.fromRGB(204,211,220),BorderSizePixel=0},top)
inst("Frame",{Position=UDim2.fromOffset(9,17),Size=UDim2.fromOffset(10,1),BackgroundColor3=Color3.fromRGB(204,211,220),BorderSizePixel=0},top)
inst("UICorner",{CornerRadius=UDim.new(0,6)},top)
motion(top)
inst("UIStroke",{Color=Color3.fromRGB(94,103,113),Thickness=1,Transparency=.55},top)
local panel=inst("Frame",{Name="AuditPanel",AnchorPoint=Vector2.new(1,0),Position=UDim2.new(1,-12,0,56),Size=UDim2.fromOffset(468,412),BackgroundColor3=dark,BorderSizePixel=0,Visible=false},gui)
inst("UICorner",{CornerRadius=UDim.new(0,7)},panel)
inst("UIStroke",{Color=Color3.fromRGB(85,91,97),Thickness=1,Transparency=.38},panel)
inst("TextLabel",{Size=UDim2.new(1,-200,0,34),Position=UDim2.fromOffset(16,8),BackgroundTransparency=1,Text="FT  /  Мониторинг",TextColor3=Color3.fromRGB(224,228,232),Font=Enum.Font.Gotham,TextSize=14,TextXAlignment=Enum.TextXAlignment.Left},panel)
local box=inst("ScrollingFrame",{Position=UDim2.fromOffset(14,126),Size=UDim2.new(1,-28,1,-190),BackgroundColor3=Color3.fromRGB(20,22,24),BorderSizePixel=0,ScrollBarThickness=4,CanvasSize=UDim2.fromOffset(0,0),AutomaticCanvasSize=Enum.AutomaticSize.Y},panel)
inst("UICorner",{CornerRadius=UDim.new(0,5)},box)
inst("UIListLayout",{Padding=UDim.new(0,6),SortOrder=Enum.SortOrder.LayoutOrder},box)
local refresh=inst("TextButton",{Position=UDim2.new(0,14,1,-48),Size=UDim2.fromOffset(110,32),BackgroundColor3=amber,Text="Обновить",TextColor3=Color3.new(1,1,1),Font=Enum.Font.GothamMedium,TextSize=12},panel)
inst("UICorner",{CornerRadius=UDim.new(0,5)},refresh)
local lastRevision=nil
local selectedCategory="all"
local lastRows=initial
local filters={{"Все","all"},{"Движение","movement"},{"Полёт","fly"},{"Баланс","economy"},{"RemoteEvents","security"},{"Система","system"}}
local filterButtons={}
local eventNames={ADMIN_OBSERVER="Режим наблюдения",REMOTE_SPAM="Частые вызовы RemoteEvent",REMOTE_MONITOR="Мониторинг RemoteEvents",MOVEMENT="Необычное перемещение",FLY_SUSPECTED="Подозрение на полёт",BALANCE_REVIEW="Проверка изменения баланса",BALANCE_MONITOR="Мониторинг валюты",START="Запуск защиты"}
local function readableEntry(v)
    local text=tostring(v.text or "")
    local time,who,kind,info=text:match("^.-(%d%d:%d%d:%d%d) UTC%s*|%s*(.-)%s*|%s*([%w_]+)%s*|%s*(.*)$")
    if not kind then
        return "Событие",text,""
    end
    local label=eventNames[kind] or kind:gsub("_"," ")
    local nick=who:match("^([^%(]+)") or who
    nick=nick:gsub("%s+$","")
    local desc=info:gsub("Observer enabled","Режим включён"):gsub("Observer disabled","Режим выключен")
        :gsub("origin not proven","источник начисления не подтверждён")
        :gsub("observed, NOT blocked","обнаружено; вызовы не заблокированы")
    return label,desc,(time or "").."  ·  "..nick
end
local function render(rows)
    lastRows=rows
    local revision=(rows[1] and tostring(rows[1].key) or "empty")..":"..tostring(#rows)..":"..selectedCategory
    if lastRevision==revision then return end
    lastRevision=revision
    for _,o in ipairs(box:GetChildren()) do if o:IsA("Frame") or (o:IsA("TextLabel") and o.Name=="Empty") then o:Destroy() end end
    local shown=0
    for i,v in ipairs(rows) do
        local category=v.category or "system"
        if selectedCategory=="all" or selectedCategory==category then
            shown+=1
            local label,desc,meta=readableEntry(v)
            local cardHeight=math.clamp(94+math.floor(#desc/55)*13,105,210)
            local card=inst("Frame",{Name="Event",LayoutOrder=i,Size=UDim2.new(1,-9,0,cardHeight),BackgroundColor3=Color3.fromRGB(35,40,46),BorderSizePixel=0},box)
            inst("UICorner",{CornerRadius=UDim.new(0,5)},card)
            inst("Frame",{Size=UDim2.new(0,3,1,-14),Position=UDim2.fromOffset(0,7),BackgroundColor3=category=="system" and Color3.fromRGB(100,111,122) or category=="economy" and Color3.fromRGB(211,156,70) or Color3.fromRGB(217,119,6),BorderSizePixel=0},card)
            inst("TextLabel",{Position=UDim2.fromOffset(12,6),Size=UDim2.new(1,-20,0,19),BackgroundTransparency=1,Text=label,Font=Enum.Font.GothamMedium,TextSize=12,TextColor3=Color3.fromRGB(239,241,242),TextXAlignment=Enum.TextXAlignment.Left},card)
            inst("TextLabel",{Position=UDim2.fromOffset(12,26),Size=UDim2.new(1,-20,0,17),BackgroundTransparency=1,Text=meta,Font=Enum.Font.Gotham,TextSize=10,TextColor3=Color3.fromRGB(177,186,197),TextXAlignment=Enum.TextXAlignment.Left},card)
            local raw=tostring(v.text or "")
            local kind=raw:match("|%s*([%w_]+)%s*|") or ""
            inst("TextLabel",{Position=UDim2.fromOffset(12,45),Size=UDim2.new(1,-25,0,17),BackgroundTransparency=1,Text="Code: "..kind,Font=Enum.Font.Code,TextSize=10,TextColor3=Color3.fromRGB(245,177,90),TextXAlignment=Enum.TextXAlignment.Left},card)
            local detail=inst("TextBox",{Position=UDim2.fromOffset(12,65),Size=UDim2.new(1,-24,0,cardHeight-71),BackgroundTransparency=1,Text=desc,ClearTextOnFocus=false,MultiLine=true,TextEditable=false,Font=Enum.Font.Gotham,TextSize=11,TextWrapped=true,TextColor3=Color3.fromRGB(220,225,230),TextXAlignment=Enum.TextXAlignment.Left,TextYAlignment=Enum.TextYAlignment.Top},card)
            detail.SelectionStart=-1
        end
    end
    if shown==0 then
        inst("TextLabel",{Name="Empty",LayoutOrder=999,Size=UDim2.new(1,-10,0,48),BackgroundTransparency=1,Text="Здесь пока нет событий",Font=Enum.Font.Gotham,TextSize=12,TextColor3=Color3.fromRGB(177,186,197)},box)
    end
    for _,item in ipairs(filterButtons) do
        item.button.BackgroundColor3=item.id==selectedCategory and amber or Color3.fromRGB(43,49,56)
    end
end
for i,item in ipairs(filters) do
    local b=inst("TextButton",{Position=UDim2.new(0,14+((i-1)%3)*148,0,54+math.floor((i-1)/3)*33),Size=UDim2.fromOffset(142,28),Text=item[1],Font=Enum.Font.Gotham,TextSize=10,TextColor3=Color3.new(1,1,1),BackgroundColor3=Color3.fromRGB(43,49,56),BorderSizePixel=0},panel)
    inst("UICorner",{CornerRadius=UDim.new(0,4)},b)
    table.insert(filterButtons,{id=item[2],button=b})
    b.MouseButton1Click:Connect(function() selectedCategory=item[2];lastRevision=nil;render(lastRows) end)
end
render(initial)
local function togglePanel()
    panel.Visible=not panel.Visible
    if panel.Visible then
        panel.Position=UDim2.new(1,-12,0,68)
        TweenService:Create(panel,TweenInfo.new(.27,Enum.EasingStyle.Quint,Enum.EasingDirection.Out),{Position=UDim2.new(1,-12,0,56)}):Play()
    end
end
top.MouseButton1Click:Connect(togglePanel)
UserInputService.InputBegan:Connect(function(input,gameProcessed)
    if not gameProcessed and input.KeyCode==Enum.KeyCode.F8 and gui.Parent then togglePanel() end
end)
refresh.MouseButton1Click:Connect(function() local rows=readEvents() if rows then render(rows) end end)
task.spawn(function()
    while gui.Parent do
        task.wait(2)
        if panel.Visible then local rows=readEvents();if rows then render(rows) end end
    end
end)

for _,control in ipairs({refresh}) do motion(control) end
for _,filterItem in ipairs(filterButtons) do motion(filterItem.button) end
local graphRemote=bridge:WaitForChild("GraphSnapshot",5)
local graphButton=inst("TextButton",{Name="OpenRelations",Position=UDim2.new(1,-134,0,12),Size=UDim2.fromOffset(118,26),BackgroundColor3=Color3.fromRGB(43,49,56),Text="Связи игроков",TextColor3=Color3.new(1,1,1),Font=Enum.Font.GothamMedium,TextSize=12,BorderSizePixel=0},panel)
inst("UICorner",{CornerRadius=UDim.new(0,5)},graphButton)
local relations=inst("Frame",{Name="Relationships",AnchorPoint=Vector2.new(0.5,0.5),Position=UDim2.fromScale(.5,.5),Size=UDim2.new(.90,0,.85,0),BackgroundColor3=Color3.fromRGB(27,31,35),BorderSizePixel=0,Visible=false,ZIndex=20},gui)
inst("UISizeConstraint",{MinSize=Vector2.new(360,300),MaxSize=Vector2.new(1020,740)},relations)
inst("UICorner",{CornerRadius=UDim.new(0,8)},relations)
inst("UIStroke",{Color=Color3.fromRGB(67,78,90),Thickness=1},relations)
local head=inst("TextLabel",{Position=UDim2.fromOffset(16,8),Size=UDim2.new(1,-60,0,28),BackgroundTransparency=1,Text="Связи игроков",Font=Enum.Font.Gotham,TextSize=16,TextColor3=Color3.fromRGB(239,241,244),TextXAlignment=Enum.TextXAlignment.Left,ZIndex=22},relations)
local close=inst("TextButton",{Position=UDim2.new(1,-39,0,8),Size=UDim2.fromOffset(28,28),Text="×",TextSize=19,Font=Enum.Font.GothamMedium,TextColor3=Color3.new(1,1,1),BackgroundColor3=Color3.fromRGB(68,77,88),BorderSizePixel=0,ZIndex=22},relations)
inst("UICorner",{CornerRadius=UDim.new(0,5)},close)
local search=inst("TextBox",{Position=UDim2.fromOffset(16,46),Size=UDim2.new(.60,-22,0,34),Text="",PlaceholderText="Ник игрока или UserId",ClearTextOnFocus=false,TextSize=13,Font=Enum.Font.Gotham,TextColor3=Color3.new(1,1,1),PlaceholderColor3=Color3.fromRGB(150,160,172),BackgroundColor3=Color3.fromRGB(41,47,56),BorderSizePixel=0,ZIndex=22},relations)
inst("UICorner",{CornerRadius=UDim.new(0,5)},search)
local go=inst("TextButton",{Position=UDim2.new(.60,2,0,46),Size=UDim2.new(.15,-6,0,34),Text="Найти",TextSize=12,Font=Enum.Font.GothamMedium,TextColor3=Color3.new(1,1,1),BackgroundColor3=amber,BorderSizePixel=0,ZIndex=22},relations)
inst("UICorner",{CornerRadius=UDim.new(0,5)},go)
local currentFilter="all"
local filter=inst("TextButton",{Position=UDim2.new(.75,3,0,46),Size=UDim2.new(.25,-19,0,34),Text="Все типы",TextSize=11,Font=Enum.Font.Gotham,TextColor3=Color3.new(1,1,1),BackgroundColor3=Color3.fromRGB(52,60,71),BorderSizePixel=0,ZIndex=22},relations)
inst("UICorner",{CornerRadius=UDim.new(0,5)},filter)
local viewport=inst("Frame",{Position=UDim2.fromOffset(16,130),Size=UDim2.new(1,-32,1,-190),BackgroundColor3=Color3.fromRGB(16,20,26),ClipsDescendants=true,BorderSizePixel=0,ZIndex=21},relations)
inst("UICorner",{CornerRadius=UDim.new(0,5)},viewport)
local world=inst("Frame",{Name="GraphCanvas",AnchorPoint=Vector2.new(.5,.5),Position=UDim2.fromScale(.5,.5),Size=UDim2.fromScale(1,1),BackgroundTransparency=1,ZIndex=22},viewport)
local worldScale=inst("UIScale",{Scale=1},world)
local message=inst("TextLabel",{Position=UDim2.new(0,14,0,14),Size=UDim2.new(1,-28,0,50),BackgroundTransparency=1,Text="Введите ник и нажмите «Найти». Здесь отображаются только операции, переданные игрой через RecordTransaction.",TextWrapped=true,TextSize=12,Font=Enum.Font.Gotham,TextColor3=Color3.fromRGB(172,182,193),TextXAlignment=Enum.TextXAlignment.Left,TextYAlignment=Enum.TextYAlignment.Top,ZIndex=24},viewport)
local legend=inst("Frame",{Name="SummaryLegend",Position=UDim2.new(0,12,1,-108),Size=UDim2.fromOffset(216,96),BackgroundColor3=Color3.fromRGB(30,36,44),BackgroundTransparency=.12,BorderSizePixel=0,ZIndex=29},viewport)
inst("UICorner",{CornerRadius=UDim.new(0,6)},legend)
local legendText=inst("TextLabel",{Position=UDim2.fromOffset(10,7),Size=UDim2.new(1,-20,1,-12),BackgroundTransparency=1,Text="СВОДКА\nСвязи — игроки с операциями\nЧисла на линиях — действия\nЦвет линии — тип передачи",TextSize=11,TextColor3=Color3.fromRGB(228,232,236),Font=Enum.Font.Gotham,TextWrapped=true,TextXAlignment=Enum.TextXAlignment.Left,TextYAlignment=Enum.TextYAlignment.Top,ZIndex=30},legend)
local summary=inst("TextLabel",{Position=UDim2.new(0,16,1,-48),Size=UDim2.new(1,-142,0,40),BackgroundTransparency=1,Text="История только текущего сервера. Данные игры не изменяются.",Font=Enum.Font.Gotham,TextSize=11,TextColor3=Color3.fromRGB(162,173,185),TextXAlignment=Enum.TextXAlignment.Left,TextWrapped=true,ZIndex=22},relations)
local less=inst("TextButton",{Position=UDim2.new(1,-91,1,-43),Size=UDim2.fromOffset(32,30),BackgroundColor3=Color3.fromRGB(49,57,67),Text="−",TextColor3=Color3.new(1,1,1),TextSize=20,ZIndex=22},relations)
local more=inst("TextButton",{Position=UDim2.new(1,-53,1,-43),Size=UDim2.fromOffset(32,30),BackgroundColor3=Color3.fromRGB(49,57,67),Text="+",TextColor3=Color3.new(1,1,1),TextSize=20,ZIndex=22},relations)
inst("UICorner",{CornerRadius=UDim.new(0,5)},less)
inst("UICorner",{CornerRadius=UDim.new(0,5)},more)
local detail=inst("Frame",{Name="HoverCard",Position=UDim2.fromOffset(0,0),Size=UDim2.fromOffset(255,146),BackgroundColor3=Color3.fromRGB(38,43,54),BorderSizePixel=0,Visible=false,ZIndex=35},relations)
inst("UICorner",{CornerRadius=UDim.new(0,7)},detail)
inst("UIStroke",{Color=Color3.fromRGB(205,151,75),Thickness=1},detail)
local detailText=inst("TextLabel",{Position=UDim2.fromOffset(10,7),Size=UDim2.new(1,-20,1,-14),BackgroundTransparency=1,Text="",TextWrapped=true,TextXAlignment=Enum.TextXAlignment.Left,TextYAlignment=Enum.TextYAlignment.Top,Font=Enum.Font.Gotham,TextSize=12,TextColor3=Color3.fromRGB(240,242,244),ZIndex=36},detail)
for _,control in ipairs({graphButton,close,search,go,filter,less,more}) do
    if control:IsA("TextButton") then motion(control) end
end
local latest=nil
local filterSequence={{"all","Все типы"},{"trade","Обмены"},{"currency","Валюта"},{"item","Предметы"}}
local function formatQty(value)
    local n=math.floor(tonumber(value) or 0)
    local s=tostring(n)
    return s:reverse():gsub("(%d%d%d)","%1 "):reverse():gsub("^ ","")
end
local zoom=1
local function updateZoom(value)
    zoom=math.clamp(value,.55,1.5)
    worldScale.Scale=zoom
end
less.MouseButton1Click:Connect(function() updateZoom(zoom-.15) end)
more.MouseButton1Click:Connect(function() updateZoom(zoom+.15) end)
local dragStart=nil
local dragPos=nil
local function beginPan(input)
    if input.UserInputType==Enum.UserInputType.MouseButton1 or input.UserInputType==Enum.UserInputType.Touch then
        dragStart=input.Position
        dragPos=world.Position
    end
end
viewport.InputBegan:Connect(beginPan)
local UIS=game:GetService("UserInputService")
local panMove=UIS.InputChanged:Connect(function(input)
    if not relations.Visible or not dragStart then return end
    if input.UserInputType==Enum.UserInputType.MouseMovement or input.UserInputType==Enum.UserInputType.Touch then
        local difference=input.Position-dragStart
        world.Position=UDim2.new(dragPos.X.Scale,dragPos.X.Offset+difference.X,dragPos.Y.Scale,dragPos.Y.Offset+difference.Y)
    end
end)
local panEnd=UIS.InputEnded:Connect(function(input)
    if input.UserInputType==Enum.UserInputType.MouseButton1 or input.UserInputType==Enum.UserInputType.Touch then dragStart=nil end
end)
local function line(a,b,color,width)
    local difference=b-a
    local length=difference.Magnitude
    if length&lt;1 then return nil end
    local midpoint=(a+b)*.5
    local frame=inst("Frame",{
        Name="Connection",
        AnchorPoint=Vector2.new(.5,.5),
        Position=UDim2.fromOffset(midpoint.X,midpoint.Y),
        Size=UDim2.fromOffset(length,width or 2),
        Rotation=math.deg(math.atan2(difference.Y,difference.X)),
        BackgroundColor3=color,BorderSizePixel=0,ZIndex=22
    },world)
    return frame
end
local function positionHover()
    local mouse=UserInputService:GetMouseLocation()
    local relative=mouse-relations.AbsolutePosition
    local width=detail.AbsoluteSize.X&gt;0 and detail.AbsoluteSize.X or 255
    local height=detail.AbsoluteSize.Y&gt;0 and detail.AbsoluteSize.Y or 146
    local maxX=math.max(7,relations.AbsoluteSize.X-width-8)
    local maxY=math.max(7,relations.AbsoluteSize.Y-height-8)
    local x=relative.X+18
    local y=relative.Y-height-13
    if x&gt;maxX then x=relative.X-width-18 end
    if y&lt;8 then y=relative.Y+20 end
    detail.Position=UDim2.fromOffset(math.clamp(x,8,maxX),math.clamp(y,8,maxY))
end
local function showCard(node,data)
    if not data then detail.Visible=false return end
    local inbound,outbound,cash,items=0,0,0,0
    for _,edge in ipairs(data.edges or {}) do
        if edge.to==node.userId then inbound+=edge.count end
        if edge.from==node.userId then outbound+=edge.count end
        if edge.from==node.userId or edge.to==node.userId then
            cash+=edge.amount or 0
            items+=edge.itemCount or 0
        end
    end
    detailText.Text="@"..node.name.."\nПолучено: "..inbound.."  ·  Передано: "..outbound.."\nВалюта в операциях: "..formatQty(cash).."\nПредметы в операциях: "..formatQty(items)..(data.demo and "\nТестовые данные" or "\nНажми для просмотра связей")
    positionHover()
    detail.Visible=true
end
local hoverMove=UserInputService.InputChanged:Connect(function(input)
    if detail.Visible and relations.Visible and input.UserInputType==Enum.UserInputType.MouseMovement then positionHover() end
end)
local requestGraph
local function renderGraph(data)
    latest=data
    detail.Visible=false
    for _,child in ipairs(world:GetChildren()) do
        if child~=worldScale then child:Destroy() end
    end
    if not data or data.error then
        message.Text=data and data.error or "Не удалось прочитать данные сервера"
        message.Visible=true
        return
    end
    local nodes=data.nodes or {}
    local edges=data.edges or {}
    local s=data.summary or {}
    summary.Text=string.format("Игроков: %d  ·  Действий: %d  ·  за %d ч%s",s.connections or 0,s.operations or 0,data.windowHours or 24,data.demo and "  ·  пример" or "")
    legendText.Text=string.format("%s\nИгроков со связями: %d\nВсего действий: %d\nНа линии — число действий\nОбмены · оранжевый\nВалюта · голубой\nПредметы · фиолетовый",data.demo and "ПРИМЕР · НЕ РЕАЛЬНЫЕ ДАННЫЕ" or "СВОДКА",s.connections or 0,s.operations or 0)
    if #edges==0 then
        message.Text=data.demo and "В демо нет операций выбранного типа. Выбери другой фильтр." or "Нет записанных передач для этого фильтра. Источник данных: серверный RecordTransaction. Изменение Cash само по себе не создаёт связь."
        message.Visible=true
        return
    end
    message.Visible=data.demo==true
    if data.demo==true then
        message.Text="ПРИМЕР · данные вымышленные. Выберите тип операций выше, чтобы увидеть, как работает фильтр."
        message.TextColor3=Color3.fromRGB(245,187,96)
    end
    local size=viewport.AbsoluteSize
    local w=math.max(size.X,360)
    local h=math.max(size.Y,250)
    local center=Vector2.new(w*.52,h*.38)
    local points={[data.center]=center}
    local count=math.max(1,#nodes-1)
    local outerRadiusX=math.max(70,math.min(w*.32,290))
    local outerRadiusY=math.max(50,math.min(h*.22,165))
    for index=2,#nodes do
        local i=index-2
        local ring=math.floor(i/10)
        local ringStart=ring*10
        local inRing=math.min(10,count-ringStart)
        local angle=(i-ringStart)/math.max(1,inRing)*math.pi*2-math.pi/2
        local spread=(ring==0 and (count&gt;10 and .63 or 1) or 1)
        local radiusX=outerRadiusX*spread
        local radiusY=outerRadiusY*spread
        points[nodes[index].userId]=center+Vector2.new(math.cos(angle)*radiusX,math.sin(angle)*radiusY)
    end
    local pairLanes={}
    for _,edge in ipairs(edges) do
        local a,b=points[edge.from],points[edge.to]
        if a and b and (b-a).Magnitude&gt;1 then
            local pairKey=tostring(math.min(edge.from,edge.to))..":"..tostring(math.max(edge.from,edge.to))
            local lane=pairLanes[pairKey] or 0
            pairLanes[pairKey]=lane+1
            local delta=(b-a).Unit
            local normal=Vector2.new(-delta.Y,delta.X)
            local shift=normal*((lane%2==0 and 1 or -1)*math.ceil(lane/2)*7)
            local color=edge.kind=="trade" and Color3.fromRGB(225,160,75) or (edge.kind=="currency" and Color3.fromRGB(88,161,233) or Color3.fromRGB(166,126,226))
            line(a+delta*34+shift,b-delta*34+shift,color,math.clamp(1.3+(edge.count or 1)*.14,1.5,3))
            local mid=(a+b)/2+shift
            local countLabel=inst("TextLabel",{Position=UDim2.fromOffset(mid.X-18,mid.Y-11),Size=UDim2.fromOffset(36,22),BackgroundColor3=Color3.fromRGB(26,30,36),BorderSizePixel=0,Text=tostring(edge.count or 0),TextColor3=color,Font=Enum.Font.GothamMedium,TextSize=11,ZIndex=24},world)
            inst("UICorner",{CornerRadius=UDim.new(0,4)},countLabel)
        end
    end
    for index,node in ipairs(nodes) do
        local position=points[node.userId]
        local isCenter=node.userId==data.center
        local size=isCenter and 76 or 54
        local button=inst("ImageButton",{Position=UDim2.fromOffset(position.X-size/2,position.Y-size/2),Size=UDim2.fromOffset(size,size),BackgroundColor3=Color3.fromRGB(45,57,68),Image=data.demo and "" or "rbxthumb://type=AvatarHeadShot&amp;id="..tostring(node.userId).."&amp;w=150&amp;h=150",BorderSizePixel=0,ZIndex=26},world)
        inst("UICorner",{CornerRadius=UDim.new(1,0)},button)
        if data.demo then inst("TextLabel",{Size=UDim2.fromScale(1,1),BackgroundTransparency=1,Text=node.name:sub(-1),Font=Enum.Font.GothamMedium,TextSize=21,TextColor3=Color3.fromRGB(230,235,240),ZIndex=27},button) end
        inst("UIStroke",{Color=isCenter and Color3.fromRGB(86,190,236) or Color3.fromRGB(226,155,69),Thickness=isCenter and 2 or 1.5},button)
        inst("TextLabel",{Position=UDim2.fromOffset(-31,size+3),Size=UDim2.fromOffset(size+62,28),BackgroundTransparency=1,Text="@"..node.name,TextScaled=false,TextTruncate=Enum.TextTruncate.AtEnd,TextSize=11,Font=Enum.Font.GothamMedium,TextColor3=Color3.fromRGB(237,239,241),TextStrokeTransparency=.35,ZIndex=27},button)
        button.MouseEnter:Connect(function() showCard(node,data) end)
        button.MouseLeave:Connect(function() detail.Visible=false end)
        button.MouseButton1Click:Connect(function()
            if data.demo then
                showCard(node,data)
            else
                search.Text=node.name
                requestGraph()
            end
        end)
    end
end
requestGraph=function()
    if not graphRemote then message.Text="Компоненты анализа связей не установлены. Обнови FT AntiCheat.";message.Visible=true return end
    message.Text="Загружаем связи игрока..."
    message.Visible=true
    local query=search.Text
    local ok,data=pcall(function() return graphRemote:InvokeServer(query,currentFilter) end)
    if not relations.Parent then return end
    if not ok or typeof(data)~="table" then
        renderGraph({error="Не удалось получить данные. Проверь доступ и работу сервера."})
    else
        renderGraph(data)
    end
end
filter.MouseButton1Click:Connect(function()
    local index=1
    for i,v in ipairs(filterSequence) do if v[1]==currentFilter then index=i break end end
    local nextValue=filterSequence[index%#filterSequence+1]
    currentFilter=nextValue[1]
    filter.Text=nextValue[2]
    if search.Text~="" then
        requestGraph()
    end
end)
search.FocusLost:Connect(function(enter) if enter then requestGraph() end end)
go.MouseButton1Click:Connect(requestGraph)
graphButton.MouseButton1Click:Connect(function()
    panel.Visible=false
    relations.Visible=true
    search.Text=search.Text~="" and search.Text or player.Name
    requestGraph()
end)
close.MouseButton1Click:Connect(function() relations.Visible=false end)
viewport:GetPropertyChangedSignal("AbsoluteSize"):Connect(function()
    if relations.Visible and latest and not dragStart then renderGraph(latest) end
end)
relations.Destroying:Connect(function()
    panMove:Disconnect()
    panEnd:Disconnect()
    hoverMove:Disconnect()
end)

]====]</ProtectedString>
        </Properties>
      </Item>
      <Item class="ModuleScript" referent="RBXFTLIC100">
        <Properties>
          <string name="Name">FT_ANTICHEAT_LICENSE_SOURCE</string>
          <ProtectedString name="Source">return [====[
MIT License

Copyright (c) 2026 Arzh

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
]====]</ProtectedString>
        </Properties>
      </Item>
      <Item class="ModuleScript" referent="RBXFTPUBLIC">
        <Properties>
          <string name="Name">FT_ANTICHEAT_PUBLIC_SOURCE</string>
          <ProtectedString name="Source">return [====[


local Players=game:GetService("Players")
local ReplicatedStorage=game:GetService("ReplicatedStorage")
local StarterGui=game:GetService("StarterGui")
local player=Players.LocalPlayer
local bridge=ReplicatedStorage:WaitForChild("FTAntiCheatBridge",10)
if not bridge then return end
local listing=bridge:WaitForChild("PlayerList",5)
if not listing then return end
local function fetch()
    local ok,result=pcall(function() return listing:InvokeServer() end)
    if ok and typeof(result)=="table" then return result end
    return nil
end
local config=fetch()
if not config then return end
local useCustom=config.enabled==true
local gui=Instance.new("ScreenGui")
gui.Name="FTCustomPlayerList"
gui.ResetOnSpawn=false
gui.DisplayOrder=20
gui.Enabled=useCustom
gui.Parent=player:WaitForChild("PlayerGui")
local function new(class,props,parent)
    local o=Instance.new(class)
    for k,v in pairs(props) do o[k]=v end
    o.Parent=parent
    return o
end
local panel=new("Frame",{AnchorPoint=Vector2.new(1,0),Position=UDim2.new(1,-12,0,54),Size=UDim2.fromOffset(250,300),BackgroundColor3=Color3.fromRGB(24,27,32),BorderSizePixel=0},gui)
new("UICorner",{CornerRadius=UDim.new(0,7)},panel)
new("UIStroke",{Color=Color3.fromRGB(75,79,85),Thickness=1},panel)
new("TextLabel",{Size=UDim2.new(1,-16,0,28),Position=UDim2.fromOffset(8,3),BackgroundTransparency=1,Text="Игроки",TextColor3=Color3.new(1,1,1),Font=Enum.Font.GothamBold,TextSize=13,TextXAlignment=Enum.TextXAlignment.Left},panel)
local list=new("ScrollingFrame",{Position=UDim2.fromOffset(8,34),Size=UDim2.new(1,-16,1,-42),BackgroundTransparency=1,BorderSizePixel=0,ScrollBarThickness=3,AutomaticCanvasSize=Enum.AutomaticSize.Y,CanvasSize=UDim2.fromOffset(0,0)},panel)
new("UIListLayout",{Padding=UDim.new(0,4)},list)
local function render(data)
    if not gui.Parent then return end
    gui.Enabled=data.enabled==true
    if not gui.Enabled then return end
    for _,child in ipairs(list:GetChildren()) do
        if child:IsA("TextLabel") then child:Destroy() end
    end
    local players=data.players or {}
    for _,info in ipairs(players) do
        local observer=info.observer==true
        local money=typeof(info.cash)=="number" and ("  ·  Cash "..tostring(info.cash)) or ""
        local entry=new("TextLabel",{Size=UDim2.new(1,-5,0,28),BackgroundColor3=Color3.fromRGB(36,40,46),BackgroundTransparency=observer and .55 or .1,BorderSizePixel=0,Text="  "..tostring(info.name or "?")..(observer and "  ◉" or "")..money,TextColor3=observer and Color3.fromRGB(155,163,174) or Color3.fromRGB(232,234,237),Font=Enum.Font.Gotham,TextSize=11,TextXAlignment=Enum.TextXAlignment.Left,TextTruncate=Enum.TextTruncate.AtEnd},list)
        new("UICorner",{CornerRadius=UDim.new(0,4)},entry)
    end
end
local function setCoreList(enabled)
    for _=1,5 do
        local ok=pcall(function() StarterGui:SetCoreGuiEnabled(Enum.CoreGuiType.PlayerList,enabled) end)
        if ok then return end
        task.wait(.3)
    end
end
if useCustom then setCoreList(false) end
render(config)
task.spawn(function()
    while gui.Parent do
        task.wait(2)
        local data=fetch()
        if data then
            if data.enabled~=useCustom then
                useCustom=data.enabled==true
                setCoreList(not useCustom)
            end
            render(data)
        end
    end
end)
]====]</ProtectedString>
        </Properties>
      </Item>
      <Item class="ModuleScript" referent="RBXFTCONFIG2026">
        <Properties>
          <string name="Name">FT_ANTICHEAT_CONFIG_SOURCE</string>
          <ProtectedString name="Source">return [====[

return {
    Economy = {
        Enabled = true,
        
        Currencies = {"Cash"},
        
        LargeGain = 100000,
        
        RapidGainWindow = 3,
        RapidGainCount = 5,
        AlertCooldown = 8,

        AuthorizationSeconds = 2,
        LogAuthorizedChanges = false,
    },
    Fly = {
        Enabled = true,

        MinGroundClearance = 18,
        HoverSeconds = 2.75,
        SustainedAscentSeconds = 2.5,
        AlertCooldown = 15,
    },
    RemoteMonitor = {
        Enabled = true,
        WindowSeconds = 2,
        MaxCalls = 20,
        AlertCooldown = 10,
    },

    Relationships = {Enabled = true, MaxEvents = 600, MaxAgeHours = 24},
    Enforcement = {Enabled = false, Action = "log"},
}

]====]</ProtectedString>
        </Properties>
      </Item>
      <Item class="ModuleScript" referent="RBX_FT_FT_EDITOR_VIEWPORT">
        <Properties>
          <string name="Name">FT_EDITOR_VIEWPORT</string>
          <ProtectedString name="Source">-- ForgeTools original viewport controller; no Sketch implementation is copied.
-- Owns pan/zoom mathematics, with mouse-anchored zoom and no scrollbars.
local Viewport = {}
Viewport.__index = Viewport
function Viewport.new(surface, canvas, scale)
 local self=setmetatable({},Viewport)
 self.surface=surface
 self.canvas=canvas
 self.scale=scale
 self.zoom=math.clamp(scale.Scale,0.1,2.5)
 self.size=Vector2.new(canvas.Size.X.Offset,canvas.Size.Y.Offset)
 return self
end
function Viewport:valid()
 return self.surface and self.surface.Parent and self.canvas and self.canvas.Parent and self.scale and self.scale.Parent==self.canvas
end
function Viewport:center()
 if not self:valid() then return end
 local area=self.surface.AbsoluteSize
 local pos=Vector2.new((area.X-self.size.X*self.zoom)/2,(area.Y-self.size.Y*self.zoom)/2)
 self.canvas.Position=UDim2.fromOffset(math.floor(pos.X+0.5),math.floor(pos.Y+0.5))
end
function Viewport:zoomTo(value,mouse)
 if not self:valid() then return self.zoom end
 local previous=self.zoom
 local nextZoom=math.clamp(value,0.1,2.5)
 if nextZoom==previous then return previous end
 local oldPosition=Vector2.new(self.canvas.Position.X.Offset,self.canvas.Position.Y.Offset)
 local cursor=(mouse and (mouse-self.surface.AbsolutePosition)) or self.surface.AbsoluteSize/2
 local ratio=nextZoom/previous
 local newPosition=cursor-(cursor-oldPosition)*ratio
 self.zoom=nextZoom
 self.scale.Scale=nextZoom
 self.canvas.Position=UDim2.fromOffset(math.floor(newPosition.X+0.5),math.floor(newPosition.Y+0.5))
 return self.zoom
end
function Viewport:fit(margin)
 if not self:valid() then return self.zoom end
 local area=self.surface.AbsoluteSize
 local pad=margin or 64
 if area.X&lt;50 or area.Y&lt;50 then return self.zoom end
 self.zoom=math.clamp(math.min((area.X-pad)/self.size.X,(area.Y-pad)/self.size.Y),0.1,2.5)
 self.scale.Scale=self.zoom
 self:center()
 return self.zoom
end
function Viewport:setSize(width,height)
 self.size=Vector2.new(width,height)
 if self:valid() then self.canvas.Size=UDim2.fromOffset(width,height) end
 return self:fit(64)
end
function Viewport:panBy(delta)
 if not self:valid() then return end
 local x=self.canvas.Position.X.Offset+delta.X
 local y=self.canvas.Position.Y.Offset+delta.Y
 self.canvas.Position=UDim2.fromOffset(math.floor(x+0.5),math.floor(y+0.5))
end
function Viewport:contains(point)
 if not self.surface or not self.surface.Parent then return false end
 local origin,size=self.surface.AbsolutePosition,self.surface.AbsoluteSize
 return point.X&gt;=origin.X and point.Y&gt;=origin.Y and point.X&lt;origin.X+size.X and point.Y&lt;origin.Y+size.Y
end
return Viewport
</ProtectedString>
        </Properties>
      </Item>
      <Item class="ModuleScript" referent="RBX_FT_FT_EDITOR_ICONS">
        <Properties>
          <string name="Name">FT_EDITOR_ICONS</string>
          <ProtectedString name="Source">-- ForgeTools icon registry. Owner supplied the eight toolbar asset identifiers.
-- Names follow the Roblox GUI classes. Same asset may represent a class in Layers.
local Icons = {}
Icons.order={"Select","Frame","TextLabel","TextButton","TextBox","ImageLabel","ImageButton","Insert"}
Icons.ids={
 Select="81207047718394", Frame="83805318784612",
 TextLabel="83439365724987", TextButton="72128640163611",
 TextBox="124468740553739", ImageLabel="75063065101885",
 ImageButton="80092123223439", Insert="75018533207646",
}
Icons.labels={
 Select={"Выбор","Select"}, Frame={"Фрейм","Frame"},
 TextLabel={"Текст","Text label"},TextButton={"Текстовая кнопка","Text button"},
 TextBox={"Поле ввода","Text box"},ImageLabel={"Изображение","Image label"},
 ImageButton={"Кнопка с изображением","Image button"},Insert={"Добавить","Add"},
}
function Icons.asset(kind)
 local id=Icons.ids[kind]
 return id and ("rbxassetid://"..id) or ""
end
return Icons
</ProtectedString>
        </Properties>
      </Item>
      <Item class="ModuleScript" referent="RBX_FT_FT_EDITOR_GEOMETRY">
        <Properties>
          <string name="Name">FT_EDITOR_GEOMETRY</string>
          <ProtectedString name="Source">-- Native ForgeTools geometry: Roblox UDim2 parent-relative rectangle math.
local Geometry={}
function Geometry.nodeRect(item,parentSize)
 local p=item.props
 local size=p.Size or UDim2.fromOffset(100,40)
 local position=p.Position or UDim2.fromOffset(0,0)
 local anchor=p.AnchorPoint or Vector2.zero
 local width=math.max(1,parentSize.X*size.X.Scale+size.X.Offset)
 local height=math.max(1,parentSize.Y*size.Y.Scale+size.Y.Offset)
 local x=parentSize.X*position.X.Scale+position.X.Offset-width*anchor.X
 local y=parentSize.Y*position.Y.Scale+position.Y.Offset-height*anchor.Y
 return Vector2.new(x,y),Vector2.new(width,height)
end
return Geometry
</ProtectedString>
        </Properties>
      </Item>
      <Item class="ModuleScript" referent="RBX_FT_FT_EDITOR_STYLE">
        <Properties>
          <string name="Name">FT_EDITOR_STYLE</string>
          <ProtectedString name="Source">-- Original ForgeTools formatting and validation for colors/image property input.
local Style={}
function Style.normalizeImage(raw)
 local value=tostring(raw or ""):gsub("^%s+",""):gsub("%s+$","")
 if value=="" or value:match("^rbxassetid://%d+$") or value:match("^rbxasset://") or value:match("^https?://") then return value end
 if value:match("^%d+$") then return "rbxassetid://"..value end
 return nil
end
function Style.toRGB(color)
 if typeof(color)~="Color3" then return "#FFFFFF" end
 return string.format("#%02X%02X%02X",math.floor(color.R*255+.5),math.floor(color.G*255+.5),math.floor(color.B*255+.5))
end
function Style.parseHex(raw)
 local hex=tostring(raw or ""):gsub("#",""):gsub("%s","")
 if #hex~=6 or not hex:match("^%x+$") then return nil end
 return Color3.fromRGB(tonumber(hex:sub(1,2),16),tonumber(hex:sub(3,4),16),tonumber(hex:sub(5,6),16))
end
return Style
</ProtectedString>
        </Properties>
      </Item>
      <Item class="ModuleScript" referent="RBX_FTGUARDCORE_090">
        <Properties>
          <string name="Name">FT_ANTICHEAT_GUARD_CORE_SOURCE</string>
          <ProtectedString name="Source">return [======[
-- ForgeTools GuardCore 0.9.2 -- server-only validation (no automatic punishment)
-- Game integrations MUST call check() before committing a transaction on the server.
local Core={}
local active=false
local sink=function() end
local flags={RemoteGuard=true,MovementGuard=true,EconomyGuard=true,InventoryGuard=true,TradeGuard=true,RewardGuard=true,DamageGuard=false}
local gameRules={}
local adapters={}
local replay={}
local histories={}
local function finite(n) return typeof(n)=="number" and n==n and n~=math.huge and n~=-math.huge end
local function report(guard,player,reason)
    pcall(sink,"GUARD/"..guard,player,tostring(reason):sub(1,250))
end
local function validPlayer(p) return typeof(p)=="Instance" and p:IsA("Player") end
local function fail(guard,p,why)
    report(guard,p,why)
    return false,why
end
function Core.init(opts)
    opts=opts or {}
    if typeof(opts.eventSink)=="function" then sink=opts.eventSink end
    active=true
    return Core
end
function Core.configure(name,rules)
    assert(flags[name]~=nil,"Unknown guard")
    assert(typeof(rules)=="table","Rules must be server-side table")
    gameRules[name]=rules
    flags[name]=true
end
function Core.register(name,adapter)
    assert(flags[name]~=nil,"Unknown guard")
    assert(name~="MovementGuard" and name~="RemoteGuard","Managed by Controller")
    assert(typeof(adapter)=="table" and typeof(adapter.validate)=="function","Adapter.validate required")
    adapters[name]=adapter;flags[name]=true
end
function Core.disable(name)
    if flags[name]==nil then return false end
    flags[name]=false;return true
end
local function validate(name,p,ctx)
    local rules=gameRules[name] or {}
    if name=="EconomyGuard" then
        local amount=ctx.amount
        if not finite(amount) or amount==0 then return false,"INVALID_AMOUNT" end
        local max=rules.maxTransaction or 1000000
        if not finite(max) or max&lt;=0 then return false,"INVALID_LIMIT" end
        if math.abs(amount)&gt;max then return false,"AMOUNT_EXCEEDS_LIMIT" end
        if typeof(ctx.reason)~="string" or #ctx.reason&lt;1 or #ctx.reason&gt;100 then return false,"MISSING_REASON" end
        if ctx.before~=nil then
            if not finite(ctx.before) or ctx.before&lt;0 or ctx.before+amount&lt;0 then return false,"INVALID_BALANCE" end
        end
        return true,"VALIDATED"
    elseif name=="InventoryGuard" then
        if typeof(ctx.itemId)~="string" or #ctx.itemId==0 or #ctx.itemId&gt;128 then return false,"INVALID_ITEM_ID" end
        if ctx.action~="grant" and ctx.action~="remove" and ctx.action~="transfer" then return false,"INVALID_ACTION" end
        if not finite(ctx.quantity) or ctx.quantity%1~=0 or ctx.quantity&lt;1 or ctx.quantity&gt;(rules.maxQuantity or 100) then return false,"INVALID_QUANTITY" end
        if (ctx.action=="remove" or ctx.action=="transfer") and (not finite(ctx.owned) or ctx.owned&lt;ctx.quantity) then return false,"INSUFFICIENT_OWNERSHIP" end
        return true,"VALIDATED"
    elseif name=="TradeGuard" then
        if not validPlayer(ctx.partner) or ctx.partner==p then return false,"INVALID_PARTNER" end
        if typeof(ctx.tradeId)~="string" or #ctx.tradeId==0 or #ctx.tradeId&gt;128 then return false,"INVALID_TRADE_ID" end
        if ctx.bothConfirmed~=true then return false,"NOT_CONFIRMED" end
        if ctx.ownershipVerified~=true then return false,"OWNERSHIP_UNVERIFIED" end
        if ctx.locked~=true then return false,"NOT_LOCKED" end
        -- The game's transaction handler must atomically commit and persist the trade.
        return true,"READY_FOR_ATOMIC_COMMIT"
    elseif name=="RewardGuard" then
        if typeof(ctx.rewardId)~="string" or #ctx.rewardId==0 or #ctx.rewardId&gt;128 then return false,"INVALID_REWARD_ID" end
        if ctx.eligible~=true then return false,"NOT_ELIGIBLE" end
        if ctx.alreadyClaimed==true then return false,"ALREADY_CLAIMED" end
        -- For persistent/one-time rewards, recheck eligibility atomically in DataStore transaction.
        return true,"READY_FOR_ATOMIC_CLAIM"
    elseif name=="DamageGuard" then
        if not finite(ctx.amount) or ctx.amount&lt;0 then return false,"INVALID_DAMAGE" end
        if not finite(ctx.maxAuthorizedDamage) or ctx.maxAuthorizedDamage&lt;0 then return false,"NO_SERVER_DAMAGE_LIMIT" end
        if ctx.amount&gt;ctx.maxAuthorizedDamage then return false,"DAMAGE_EXCEEDS_AUTHORIZED" end
        return true,"VALIDATED"
    end
    return false,"UNSUPPORTED_GUARD"
end
function Core.check(name,player,context)
    if not active then return false,"CORE_NOT_STARTED" end
    if flags[name]==nil then return false,"UNKNOWN_GUARD" end
    if name=="MovementGuard" or name=="RemoteGuard" then return false,"MANAGED_BY_CONTROLLER" end
    if not flags[name] then return false,"GUARD_DISABLED" end
    if not validPlayer(player) or typeof(context)~="table" then return false,"INVALID_INPUT" end
    local ok,why=validate(name,player,context)
    if not ok then return fail(name,player,why) end
    local adapter=adapters[name]
    if adapter then
        local success,allowed,detail=pcall(adapter.validate,player,context)
        if not success then return fail(name,player,"ADAPTER_ERROR") end
        if allowed~=true then return fail(name,player,detail or "ADAPTER_REJECTED") end
    end
    return true,why
end
function Core.inspectDamage(player,amount,ctx)
    ctx=ctx or {};ctx.amount=amount
    return Core.check("DamageGuard",player,ctx)
end
function Core.status()
    local result={}
    for name,enabled in pairs(flags) do result[name]={enabled=enabled,adapter=adapters[name]~=nil,configured=gameRules[name]~=nil} end
    return result
end
function Core.stop() active=false;table.clear(adapters);table.clear(replay);table.clear(histories) end
return Core
]======]</ProtectedString>
        </Properties>
      </Item>
      <Item class="ModuleScript" referent="RBX_FORGE_INSPECTOR_MODULE">
        <Properties>
          <string name="Name">FORGE_INSPECTOR_MODULE</string>
          <ProtectedString name="Source">return function(plugin)
-- Forge Inspector module for ForgeTools 1.0.0 | public report receipt
-- Read-only analyzer. Upload only on explicit SEND action; no source modifications.
local ScriptEditorService = game:GetService("ScriptEditorService")
local HttpService = game:GetService("HttpService")
-- Persistent installation ID. Not proof of Roblox account identity.
local INSTALL_KEY = "ForgeInspector_InstallId_v1"
local function getInstallId()
 local ok, stored = pcall(function() return plugin:GetSetting(INSTALL_KEY) end)
 if ok and type(stored)=="string" and #stored==36 and stored:match("^[%x%-]+$") then return stored end
 local fresh = HttpService:GenerateGUID(false)
 pcall(function() plugin:SetSetting(INSTALL_KEY, fresh) end)
 return fresh
end
local installId = getInstallId()

local TextService = game:GetService("TextService")
local Selection = game:GetService("Selection")
local TweenService = game:GetService("TweenService")
local widgetInfo = DockWidgetPluginGuiInfo.new(Enum.InitialDockState.Float, false, false, 840, 650, 480, 470)
local widget = plugin:CreateDockWidgetPluginGuiAsync("ForgeInspector_Engine_102", widgetInfo)
widget.Title = "Forge Inspector"

-- Exact ForgeTools 0.9.12 "Forge Orange" palette; no approximate colors.
local C = {
 bg = Color3.fromRGB(20,22,24), panel = Color3.fromRGB(27,31,35), item = Color3.fromRGB(35,40,46),
 text = Color3.fromRGB(243,244,246), mute = Color3.fromRGB(169,178,188), accent = Color3.fromRGB(217,119,6),
 accentHover = Color3.fromRGB(245,158,11), soft = Color3.fromRGB(58,42,24),
 border = Color3.fromRGB(49,56,65), critical = Color3.fromRGB(246,71,71), high = Color3.fromRGB(201,90,90),
 medium = Color3.fromRGB(217,164,65), low = Color3.fromRGB(169,178,188),
}

local function new(class, props, parent)
 local obj = Instance.new(class)
 for k,v in pairs(props) do obj[k] = v end
 obj.Parent = parent
 return obj
end
local root = new("Frame", {Size=UDim2.fromScale(1,1), BackgroundColor3=C.bg, BorderSizePixel=0}, widget)
new("UIPadding", {PaddingLeft=UDim.new(0,16), PaddingRight=UDim.new(0,16), PaddingTop=UDim.new(0,14), PaddingBottom=UDim.new(0,12)}, root)
local header = new("TextLabel", {Size=UDim2.new(1,0,0,28), BackgroundTransparency=1, Text="FORGE / INSPECTOR", TextColor3=C.text, TextSize=18, Font=Enum.Font.GothamBold, TextXAlignment=Enum.TextXAlignment.Left}, root)
local subtitle = new("TextLabel", {Position=UDim2.fromOffset(0,29), Size=UDim2.new(1,0,0,24), BackgroundTransparency=1, Text="", TextColor3=C.mute, TextSize=13, Font=Enum.Font.Gotham, TextXAlignment=Enum.TextXAlignment.Left}, root)
local function rounded(parent, radius)
 new("UICorner", {CornerRadius=UDim.new(0,radius or 5)}, parent)
end
local controls = new("Frame", {Position=UDim2.fromOffset(0,60), Size=UDim2.new(1,0,0,94), BackgroundTransparency=1}, root)
local scanButton = new("TextButton", {Size=UDim2.fromOffset(146,38), BackgroundColor3=C.accent, Text="LOCAL SCAN", TextSize=13, Font=Enum.Font.GothamBold, TextColor3=C.text, BorderSizePixel=0}, controls)
rounded(scanButton)
local exportButton = new("TextButton", {Position=UDim2.fromOffset(154,0), Size=UDim2.fromOffset(145,38), BackgroundColor3=C.item, Text="EXPORT", TextSize=13, Font=Enum.Font.GothamBold, TextColor3=C.text, BorderSizePixel=0}, controls)
rounded(exportButton)
local deepButton = new("TextButton", {Position=UDim2.fromOffset(307,0), Size=UDim2.fromOffset(143,38), BackgroundColor3=C.item, Text="DEEP SCAN", TextSize=13, Font=Enum.Font.GothamBold, TextColor3=C.text, BorderSizePixel=0}, controls)
rounded(deepButton)
local filterButtons = {}
for index, filter in ipairs({"ALL","CRITICAL","HIGH","MEDIUM","LOW"}) do
 local btn = new("TextButton", {Position=UDim2.fromOffset((index-1)*94,48), Size=UDim2.fromOffset(88,32), BackgroundColor3=C.panel, Text=filter, TextSize=12, Font=Enum.Font.GothamBold, TextColor3=C.mute, BorderSizePixel=0}, controls)
 rounded(btn,4)
 filterButtons[filter] = btn
end
local status = new("TextLabel", {Position=UDim2.fromOffset(0,155), Size=UDim2.new(1,0,0,38), BackgroundColor3=C.panel, BorderSizePixel=0, Text="  Готово · Локальная проверка не требует сервера.", TextColor3=C.mute, TextSize=12, Font=Enum.Font.Gotham, TextXAlignment=Enum.TextXAlignment.Left, TextWrapped=true}, root)
rounded(status)
local results = new("ScrollingFrame", {Position=UDim2.fromOffset(0,201), Size=UDim2.new(1,0,1,-230), BackgroundColor3=C.panel, BorderSizePixel=0, ScrollBarThickness=6, ScrollBarImageColor3=C.accent, AutomaticCanvasSize=Enum.AutomaticSize.Y, CanvasSize=UDim2.fromOffset(0,0)}, root)
rounded(results)
new("UIStroke", {Color=C.border, Thickness=1, Transparency=0.28}, results)
new("UIPadding", {PaddingTop=UDim.new(0,6), PaddingBottom=UDim.new(0,6), PaddingLeft=UDim.new(0,6), PaddingRight=UDim.new(0,6)}, results)
new("UIListLayout", {Padding=UDim.new(0,5), SortOrder=Enum.SortOrder.LayoutOrder}, results)
local footer = new("TextLabel", {Position=UDim2.new(0,0,1,-23), Size=UDim2.new(1,0,0,21), BackgroundTransparency=1, Text="Локальная проверка без отправки кода · Нажмите на находку, чтобы открыть скрипт", TextColor3=C.mute, Font=Enum.Font.Gotham, TextSize=12, TextXAlignment=Enum.TextXAlignment.Left}, root)

local exportOverlay = new("Frame", {Size=UDim2.fromScale(1,1), BackgroundColor3=C.bg, BorderSizePixel=0, Visible=false, ZIndex=10}, root)
local exportTitle = new("TextLabel", {Position=UDim2.fromOffset(0,4), Size=UDim2.new(1,-95,0,32), BackgroundTransparency=1, Text="EXPORT REPORT", Font=Enum.Font.GothamBold, TextSize=20, TextColor3=C.text, TextXAlignment=Enum.TextXAlignment.Left, ZIndex=11}, exportOverlay)
local closeExport = new("TextButton", {Position=UDim2.new(1,-82,0,3), Size=UDim2.fromOffset(82,32), Text="CLOSE", BackgroundColor3=C.item, TextColor3=C.text, Font=Enum.Font.GothamBold, TextSize=12, BorderSizePixel=0, ZIndex=11}, exportOverlay)
rounded(closeExport)
local mdButton = new("TextButton", {Position=UDim2.fromOffset(0,45), Size=UDim2.fromOffset(120,34), Text="MARKDOWN", BackgroundColor3=C.accent, TextColor3=C.text, Font=Enum.Font.GothamBold, TextSize=12, BorderSizePixel=0, ZIndex=11}, exportOverlay)
rounded(mdButton)
local jsonButton = new("TextButton", {Position=UDim2.fromOffset(130,45), Size=UDim2.fromOffset(92,34), Text="JSON", BackgroundColor3=C.item, TextColor3=C.text, Font=Enum.Font.GothamBold, TextSize=12, BorderSizePixel=0, ZIndex=11}, exportOverlay)
rounded(jsonButton)
local selectButton = new("TextButton", {Position=UDim2.new(1,-125,0,45), Size=UDim2.fromOffset(125,34), Text="SELECT TEXT", BackgroundColor3=C.item, TextColor3=C.text, Font=Enum.Font.GothamBold, TextSize=12, BorderSizePixel=0, ZIndex=11}, exportOverlay)
rounded(selectButton)
local exportHint = new("TextLabel", {Position=UDim2.fromOffset(0,84), Size=UDim2.new(1,0,0,34), BackgroundTransparency=1, Text="Local + Deep Scan results. SELECT TEXT, then Ctrl+C. No script source included.", Font=Enum.Font.Gotham, TextColor3=C.mute, TextSize=12, TextWrapped=true, TextXAlignment=Enum.TextXAlignment.Left, ZIndex=11}, exportOverlay)
local reportScroll = new("ScrollingFrame", {Position=UDim2.fromOffset(0,124), Size=UDim2.new(1,0,1,-190), BackgroundColor3=C.panel, BorderSizePixel=0, ScrollBarThickness=8, ScrollBarImageColor3=C.accent, CanvasSize=UDim2.fromOffset(0,0), ScrollingDirection=Enum.ScrollingDirection.Y, ZIndex=11}, exportOverlay)
rounded(reportScroll)
new("UIStroke", {Color=C.border, Thickness=1, Transparency=0.36, ApplyStrokeMode=Enum.ApplyStrokeMode.Border}, reportScroll)
local reportBox = new("TextBox", {Position=UDim2.fromOffset(10,8), Size=UDim2.new(1,-30,0,200), BackgroundTransparency=1, TextColor3=C.text, Font=Enum.Font.Code, TextSize=13, TextXAlignment=Enum.TextXAlignment.Left, TextYAlignment=Enum.TextYAlignment.Top, TextWrapped=true, MultiLine=true, ClearTextOnFocus=false, TextEditable=true, Text="", BorderSizePixel=0, ZIndex=12}, reportScroll)
local sendButton = new("TextButton", {Position=UDim2.fromOffset(235,45), Size=UDim2.fromOffset(145,34), Text="SEND LOCAL", BackgroundColor3=C.item, TextColor3=C.text, Font=Enum.Font.GothamBold, TextSize=12, BorderSizePixel=0, ZIndex=11}, exportOverlay)
rounded(sendButton)
local uploadStatus = new("TextLabel", {Position=UDim2.new(0,0,1,-56), Size=UDim2.new(1,0,0,52), BackgroundColor3=C.panel, Text="Not sent. Only findings are uploaded, never source code.", TextSize=12, Font=Enum.Font.Gotham, TextColor3=C.mute, TextXAlignment=Enum.TextXAlignment.Left, TextWrapped=true, ZIndex=12}, exportOverlay)
rounded(uploadStatus)
new("UIPadding",{PaddingLeft=UDim.new(0,10), PaddingRight=UDim.new(0,10)},uploadStatus)
local function resizeReport()
 local width = math.max(140, reportScroll.AbsoluteSize.X - 38)
 local ok, bounds = pcall(function()
  return TextService:GetTextSize(reportBox.Text, reportBox.TextSize, reportBox.Font, Vector2.new(width,100000))
 end)
 local h = ok and math.max(180, math.ceil(bounds.Y)+24) or math.max(200, #reportBox.Text / 3)
 reportBox.Size = UDim2.new(1,-30,0,h)
 reportScroll.CanvasSize = UDim2.fromOffset(0,h+16)
end
reportScroll:GetPropertyChangedSignal("AbsoluteSize"):Connect(resizeReport)
-- Separate server review view; local scan and exports are unchanged.
local deepOverlay = new("Frame", {Size=UDim2.fromScale(1,1), BackgroundColor3=C.bg, BorderSizePixel=0, Visible=false, ZIndex=20}, root)
local deepTitle = new("TextLabel", {Position=UDim2.fromOffset(0,4), Size=UDim2.new(1,-95,0,32), BackgroundTransparency=1, Text="DEEP SCAN", Font=Enum.Font.GothamBold, TextSize=19, TextColor3=C.text, TextXAlignment=Enum.TextXAlignment.Left, ZIndex=21}, deepOverlay)
local deepClose = new("TextButton", {Position=UDim2.new(1,-84,0,3), Size=UDim2.fromOffset(84,32), Text="CLOSE", BackgroundColor3=C.item, TextColor3=C.text, Font=Enum.Font.GothamBold, TextSize=12, BorderSizePixel=0, ZIndex=21}, deepOverlay)
rounded(deepClose)
local deepExportButton = new("TextButton", {Position=UDim2.new(1,-238,0,3), Size=UDim2.fromOffset(145,32), Text="EXPORT RESULTS", BackgroundColor3=C.item, TextColor3=C.text, Font=Enum.Font.GothamBold, TextSize=12, BorderSizePixel=0, ZIndex=21}, deepOverlay)
rounded(deepExportButton)
local deepHint = new("TextLabel", {Position=UDim2.fromOffset(0,49), Size=UDim2.new(1,0,0,85), Text="Luau и Security Audit работают на сервере Forge Inspector.\nВыберите скрипт в Explorer или выполните Local Scan. Проверьте код, подтвердите отправку и нажмите ANALYZE CODE. Не отправляйте секреты.", TextColor3=C.mute, BackgroundTransparency=1, TextWrapped=true, TextYAlignment=Enum.TextYAlignment.Top, TextXAlignment=Enum.TextXAlignment.Left, TextSize=14, Font=Enum.Font.Gotham, ZIndex=21}, deepOverlay)
local deepRun = new("TextButton", {Position=UDim2.fromOffset(0,142), Size=UDim2.fromOffset(170,40), Text="ANALYZE CODE", BackgroundColor3=C.accent, TextColor3=C.text, Font=Enum.Font.GothamBold, TextSize=12, BorderSizePixel=0, ZIndex=21}, deepOverlay)
rounded(deepRun)
local deepStatus = new("TextLabel", {Position=UDim2.fromOffset(182,142), Size=UDim2.new(1,-182,0,40), BackgroundColor3=C.panel, Text="  Awaiting scan", TextColor3=C.mute, Font=Enum.Font.Gotham, TextSize=12, TextXAlignment=Enum.TextXAlignment.Left, TextWrapped=true, ZIndex=21}, deepOverlay)
rounded(deepStatus)
local deepScroll = new("ScrollingFrame", {Position=UDim2.fromOffset(0,247), Size=UDim2.new(1,0,1,-257), BackgroundColor3=C.panel, BorderSizePixel=0, ScrollBarThickness=7, ScrollBarImageColor3=C.accent, AutomaticCanvasSize=Enum.AutomaticSize.Y, CanvasSize=UDim2.fromOffset(0,0), ZIndex=21}, deepOverlay)
rounded(deepScroll)
new("UIStroke", {Color=C.border, Thickness=1, Transparency=0.28}, deepScroll)
new("UIPadding", {PaddingTop=UDim.new(0,7),PaddingBottom=UDim.new(0,7),PaddingLeft=UDim.new(0,7),PaddingRight=UDim.new(0,7)}, deepScroll)
new("UIListLayout", {Padding=UDim.new(0,6),SortOrder=Enum.SortOrder.LayoutOrder},deepScroll)
local consent = false
local consentButton = new("TextButton", {Position=UDim2.fromOffset(0,195), Size=UDim2.new(1,0,0,40), BackgroundColor3=C.item, BorderSizePixel=0, Text="", AutoButtonColor=false, ZIndex=21},deepOverlay)
rounded(consentButton)
local consentSquare = new("Frame", {Position=UDim2.fromOffset(12,11),Size=UDim2.fromOffset(18,18),BackgroundColor3=C.panel,BorderSizePixel=0,ZIndex=22},consentButton)
rounded(consentSquare,3)
new("UIStroke",{Color=C.mute,Thickness=1,Transparency=0.15},consentSquare)
local consentCheck = new("TextLabel",{Size=UDim2.fromScale(1,1),BackgroundTransparency=1,Text="",TextSize=15,Font=Enum.Font.GothamBold,TextColor3=C.text,ZIndex=23},consentSquare)
new("TextLabel",{Position=UDim2.fromOffset(42,0),Size=UDim2.new(1,-52,1,0),BackgroundTransparency=1,Text="Разрешаю отправить выбранные скрипты на сервер анализа",TextColor3=C.text,Font=Enum.Font.Gotham,TextSize=13,TextXAlignment=Enum.TextXAlignment.Left,TextWrapped=true,ZIndex=22},consentButton)
local function setConsent(allowed)
 consent = allowed
 consentCheck.Text = allowed and "✓" or ""
 consentSquare.BackgroundColor3 = allowed and C.accent or C.panel
 consentButton.BackgroundColor3 = allowed and C.soft or C.item
end
consentButton.MouseButton1Click:Connect(function() setConsent(not consent) end)
local function clearDeep()
 for _, item in ipairs(deepScroll:GetChildren()) do
  if item:IsA("GuiObject") then item:Destroy() end
 end
end
local function deepCard(head, detail, color)
 local card = new("Frame", {Size=UDim2.new(1,-10,0,104), BackgroundColor3=C.item, BorderSizePixel=0, ZIndex=22}, deepScroll)
 rounded(card,5)
 new("TextLabel", {Position=UDim2.fromOffset(14,12),Size=UDim2.new(1,-28,0,22),BackgroundTransparency=1,Text=head,TextColor3=color or C.text,Font=Enum.Font.GothamBold,TextSize=14,TextXAlignment=Enum.TextXAlignment.Left,TextTruncate=Enum.TextTruncate.AtEnd,ZIndex=23},card)
 new("TextLabel", {Position=UDim2.fromOffset(14,40),Size=UDim2.new(1,-28,0,56),BackgroundTransparency=1,Text=detail,TextColor3=C.mute,Font=Enum.Font.Gotham,TextSize=13,TextWrapped=true,TextYAlignment=Enum.TextYAlignment.Top,TextXAlignment=Enum.TextXAlignment.Left,ZIndex=23},card)
 return card
end
local deepBusy = false
local deepLastResponse = nil
local findings = {}
local currentFilter = "ALL"
local scannedCount, skippedCount = 0, 0
local scannedAt = ""
local scanning = false
local function clearResults()
 for _,child in ipairs(results:GetChildren()) do
  if child:IsA("GuiObject") then child:Destroy() end
 end
end
local function showMessage(message)
 local lbl = new("TextLabel", {Size=UDim2.new(1,-10,0,76), BackgroundTransparency=1, Text=message, TextColor3=C.mute, Font=Enum.Font.Gotham, TextSize=14, TextWrapped=true, TextXAlignment=Enum.TextXAlignment.Left}, results)
 return lbl
end
local function jumpTo(scriptInstance, line)
 if not scriptInstance or not scriptInstance.Parent then return end
 local ok, err = pcall(function() plugin:OpenScript(scriptInstance, line) end)
 if not ok then
  warn("[Forge Inspector] Cannot open script at line " .. tostring(line) .. ": " .. tostring(err))
 end
end
local function updateFilters()
 for key, btn in pairs(filterButtons) do
  local active = key == currentFilter
  btn.BackgroundColor3 = active and C.accent or C.panel
  btn.TextColor3 = active and C.text or C.mute
 end
end
local function drawResults()
 clearResults()
 updateFilters()
 local visible = 0
 for _,finding in ipairs(findings) do
  if currentFilter == "ALL" or finding.severity == currentFilter then
   visible += 1
   local color = C.low
   if finding.severity == "CRITICAL" then color = C.critical elseif finding.severity == "HIGH" then color = C.high elseif finding.severity == "MEDIUM" then color = C.medium end
   local item = new("TextButton", {Size=UDim2.new(1,-10,0,88), BackgroundColor3=C.item, BorderSizePixel=0, Text="", AutoButtonColor=true}, results)
   new("UICorner", {CornerRadius=UDim.new(0,5)}, item)
   new("UIStroke", {Color=C.border, Thickness=1, Transparency=0.45, ApplyStrokeMode=Enum.ApplyStrokeMode.Border}, item)
   new("Frame", {Size=UDim2.fromOffset(3,88), BackgroundColor3=color, BorderSizePixel=0}, item)
   new("TextLabel", {Position=UDim2.fromOffset(14,8), Size=UDim2.new(1,-30,0,20), BackgroundTransparency=1, Text=finding.severity .. "  •  " .. finding.code, TextColor3=color, Font=Enum.Font.GothamBold, TextSize=12, TextXAlignment=Enum.TextXAlignment.Left}, item)
   new("TextLabel", {Position=UDim2.fromOffset(14,32), Size=UDim2.new(1,-30,0,20), BackgroundTransparency=1, Text=finding.path .. ":" .. finding.line, TextColor3=C.text, Font=Enum.Font.Code, TextSize=12, TextTruncate=Enum.TextTruncate.AtEnd, TextXAlignment=Enum.TextXAlignment.Left}, item)
   new("TextLabel", {Position=UDim2.fromOffset(14,56), Size=UDim2.new(1,-30,0,27), BackgroundTransparency=1, Text=finding.message, TextColor3=C.mute, Font=Enum.Font.Gotham, TextSize=12, TextWrapped=true, TextXAlignment=Enum.TextXAlignment.Left, TextYAlignment=Enum.TextYAlignment.Top}, item)
   item.MouseButton1Click:Connect(function() jumpTo(finding.script, finding.line) end)
  end
 end
 status.Text = string.format("  ForgeTools 1.0.0  |  %d скриптов  |  %d замечаний  |  Показано %d [%s]", scannedCount, #findings, visible, currentFilter)
 if visible == 0 then showMessage(#findings == 0 and "Локальная проверка завершена: известных подозрительных конструкций не найдено. Проверка не доказывает безопасность." or "No " .. currentFilter .. " findings. Try another filter.") end
end
local function appendIssue(scriptInstance, line, severity, code, message)
 if #findings &gt;= 500 then return end
 table.insert(findings, {script=scriptInstance, line=line, severity=severity, code=code, message=message, path=scriptInstance:GetFullName()})
end
-- Local audit uses conservative rules. This is NOT a full Luau parser/type checker.
-- Ignore ordinary RemoteEvent/RemoteFunction usage; it is not a vulnerability.
local checks = {
 {severity="HIGH", code="DYNAMIC_CODE", pattern="%f[%w]loadstring%s*%(", message="Dynamic execution detected. Verify that code cannot originate from an untrusted source."},
 {severity="MEDIUM", code="EXTERNAL_REQUIRE", pattern="%f[%w]require%s*%(%s*%d+%s*%)", message="Numeric asset require: verify owner, code and update process."},
 {severity="MEDIUM", code="ENV_MUTATION", pattern="%f[%w]setfenv%s*%(", message="Environment mutation complicates auditing and can bypass static assumptions."},
 {severity="MEDIUM", code="CLIENT_DATASTORE", pattern="DataStoreService", clientOnly=true, message="DataStoreService is server-only. Move access into a server script."},
}
local function addUniqueIssue(scriptInstance, line, severity, code, message, seen)
 local id = code .. ':' .. tostring(line)
 if not seen[id] then
  seen[id]=true
  appendIssue(scriptInstance,line,severity,code,message)
 end
end
-- Minimal lexical masker: skip strings and comments so examples/documentation do not generate alarms.
-- Preserve character positions and newlines. Long-bracket Luau strings/comments are covered.
local function maskNonCode(source)
 local out, i, n = {}, 1, #source
 local function blank(fragment)
  return fragment:gsub("[^\n]", " ")
 end
 while i &lt;= n do
  local rem = source:sub(i)
  local eq = rem:match("^%-%-%[(=*)%[")
  local isComment = eq ~= nil
  if not eq then eq = rem:match("^%[(=*)%[") end
  if eq then
   local opener = (isComment and 4 or 2) + #eq
   local closer = "]" .. eq .. "]"
   local j = source:find(closer,i+opener,true)
   local finish = j and (j+#closer-1) or n
   out[#out+1] = blank(source:sub(i,finish))
   i=finish+1
  elseif rem:sub(1,2)=="--" then
   local e=source:find("\n",i,true) or (n+1)
   out[#out+1]=blank(source:sub(i,e-1))
   i=e
  else
   local q=source:sub(i,i)
   if q=='"' or q=="'" or q=='`' then
    local j=i+1
    while j&lt;=n do
     local c=source:sub(j,j)
     if c=="\\" then j+=2
     elseif c==q then j+=1 break
     else j+=1 end
    end
    out[#out+1]=blank(source:sub(i,math.min(j-1,n)))
    i=j
   else
    out[#out+1]=q
    i+=1
   end
  end
 end
 return table.concat(out)
end
local function auditSource(scriptInstance, source)
 local clean = maskNonCode(source:gsub("\r\n","\n"))
 local lines={}
 for line in (clean.."\n"):gmatch("(.-)\n") do lines[#lines+1]=line end
 local seen={}
 local isClient=scriptInstance:IsA("LocalScript") or scriptInstance:GetFullName():find("StarterPlayerScripts",1,true) ~= nil
 for lineNo,line in ipairs(lines) do
  for _,rule in ipairs(checks) do
   if (not rule.clientOnly or isClient) and line:find(rule.pattern) then
    addUniqueIssue(scriptInstance,lineNo,rule.severity,rule.code,rule.message,seen)
   end
  end
  if line:find("while%s+true%s+do") or line:find("repeat%s*$") then
   local last = math.min(#lines,lineNo+24)
   local sample = table.concat(lines,"\n",lineNo,last)
   local hasYield = sample:find("task%.wait%s*%(") or sample:find("%f[%w]wait%s*%(") or sample:find(":Wait%s*%(") or sample:find(":WaitForChild%s*%(")
   if not hasYield then
    addUniqueIssue(scriptInstance,lineNo,"MEDIUM","LOOP_NO_YIELD","Possible non-yielding loop. Check loop body and termination; heuristic only.",seen)
   end
  end
  -- Security heuristics: inspect a short, local RemoteEvent handler window.
  -- Reports are potential risks, never proof of exploitation.
  local params=line:match("%.OnServerEvent%s*:%s*Connect%s*%(%s*function%s*%(([^)]*)%)")
  if params then
   local paramList={}
   for v in params:gmatch("[^,%s]+") do paramList[#paramList+1]=v end
   local start=math.min(#lines,lineNo+1)
   local finish=math.min(#lines,lineNo+23)
   local observed={}
   for j=start,finish do
    local body=lines[j]
    -- Avoid attributing a second unrelated remote handler to this one.
    if j&gt;start and body:find("%.OnServerEvent%s*:%s*Connect%s*%(") then break end
    -- Third-party parameters are not trusted. However, their mere use is not a finding.
    local input={}
    for k=2,#paramList do
     local v=paramList[k]
     if #v&gt;1 and body:find("%f[%w_]"..v.."%f[^%w_]") then input[#input+1]=v end
    end
    if #input&gt;0 then
     local lower=body:lower()
     local currency=lower:find("coins",1,true) or lower:find("currency",1,true) or lower:find("cash",1,true) or lower:find("gems",1,true)
     local moneyChange=body:find("[%+%-]=") or body:find("=%s*[^=].*[%+%-]")
     if currency and moneyChange then
      addUniqueIssue(scriptInstance,j,"HIGH","SEC_CURRENCY_INPUT","Клиентский аргумент участвует в изменении валюты. Проверьте серверный расчёт, диапазоны и полномочия; потенциальный риск.",seen)
     elseif lower:find("inventory",1,true) and (body:find("table%.insert%s*%(") or body:find("table%.remove%s*%(")) then
      addUniqueIssue(scriptInstance,j,"HIGH","SEC_INVENTORY_INPUT","Клиентский аргумент влияет на инвентарь. Проверьте владение, цену и атомарность операции; потенциальный риск.",seen)
     elseif lower:find("rarity",1,true) and (body:find("rarity%s*=") or body:find("rarity%s*,")) then
      addUniqueIssue(scriptInstance,j,"HIGH","SEC_SUMMON_RARITY","Редкость или награда выбирается из клиентского запроса. Проверить серверный RNG и каталоги.",seen)
     elseif body:find("%.Level%s*%+=") or body:find("%.Level%s*=%s*.-%+") then
      addUniqueIssue(scriptInstance,j,"MEDIUM","SEC_UPGRADE_INPUT","Аргумент клиента используется в обработчике улучшения. Проверить стоимость и принадлежность юнита.",seen)
     end
    end
    -- Unrestricted privileged commands are suspicious even if the function has no client parameters.
    if line:lower():find("admin",1,true) and (body:find('command%s*==') or body:find("target%.Coins")) and not observed.admin then
     observed.admin=true
     addUniqueIssue(scriptInstance,lineNo,"HIGH","SEC_ADMIN_REMOTE","Административный RemoteEvent: необходима проверка прав на сервере. Проверка эвристическая.",seen)
    end
    if body:find("SetAsync%s*%(") and not observed.save then
     observed.save=true
     addUniqueIssue(scriptInstance,j,"MEDIUM","SEC_REMOTE_DATASTORE","Запись в DataStore из обработчика RemoteEvent. Проверьте лимиты запросов, обработку ошибок и согласованность данных.",seen)
    end
   end
  end
  if line:find("%.RenderStepped%s*:%s*Connect%s*%(") or line:find("%.Heartbeat%s*:%s*Connect%s*%(") then
   local sample=table.concat(lines,"\n",lineNo,math.min(#lines,lineNo+16))
   if sample:find(":GetDescendants%s*%(") or sample:find(":GetChildren%s*%(") or sample:find(":WaitForChild%s*%(") then
    addUniqueIssue(scriptInstance,lineNo,"LOW","FRAME_WORK","Frame callback contains hierarchy traversal/wait nearby; verify frequency and cost.",seen)
   end
  end
 end
end
-- Security rules v1: offline, conservative, no server dependency.
-- Findings are hypotheses, not proof of exploitability.
local function securityAudit(scriptInstance, source)
 if scriptInstance:IsA("LocalScript") then return end
 local clean = maskNonCode(source:gsub("\r\n","\n"))
 local rows, rawRows = {}, {}
 for s in (clean.."\n"):gmatch("(.-)\n") do rows[#rows+1]=s end
 for s in (source:gsub("\r\n","\n").."\n"):gmatch("(.-)\n") do rawRows[#rawRows+1]=s end
 local seen={}
 local function report(line,sev,code,msg)
  addUniqueIssue(scriptInstance,line,sev,code,msg,seen)
 end
 local function isUsed(line,name)
  return #name&gt;1 and line:find("%f[%w_]"..name.."%f[^%w_]")~=nil
 end
 for n,header in ipairs(rows) do
  local args=header:match("%.OnServerEvent%s*:%s*Connect%s*%(%s*function%s*%(([^)]*)%)")
   or header:match("%.OnServerInvoke%s*=%s*function%s*%(([^)]*)%)")
  if args then
   local params={}
   for p in args:gmatch("[^,%s]+") do params[#params+1]=p end
   local names={}
   for k=2,#params do
    local p=params[k]
    if p:match("^[%a_][%w_]*$") then names[#names+1]=p end
   end
   local handler=header:lower()
   local finish=math.min(#rows,n+65)
   for j=n+1,finish do
    local body=rows[j]
    if body:find("%.OnServerEvent%s*:%s*Connect%s*%(") or body:find("%.OnServerInvoke%s*=%s*function") then break end
    local lower=body:lower()
    local referenced={}
    for _,name in ipairs(names) do
     if isUsed(body,name) then referenced[#referenced+1]=name end
    end
    if #referenced&gt;0 then
     if (lower:find("%.coins",1,true) or lower:find("%.gems",1,true) or lower:find("%.cash",1,true))
         and (body:find("%+=") or body:find("%-=") or body:find("%s=%s.*[%+%-]")) then
      report(j,"HIGH","SEC_CLIENT_ECONOMY","Клиентский аргумент участвует в изменении валюты. Проверьте серверное определение суммы и разрешений; возможная уязвимость.")
     end
     if (lower:find("coins",1,true) or lower:find("gems",1,true) or lower:find("cash",1,true)) and
        (body:find("%s*&gt;=%s*") or body:find("%s*&gt;%s*")) then
      for _,v in ipairs(referenced) do
       if body:find("[&gt;&lt;=]=?%s*"..v.."%f[^%w_]") then
        report(j,"HIGH","SEC_CLIENT_PRICE","Клиентский аргумент используется как цена или порог оплаты. Проверьте, что цена задаётся серверным каталогом.")
        break
       end
      end
     end
     if body:find("table%.insert%s*%(") and (lower:find("inventory",1,true) or lower:find("units",1,true)) then
      report(j,"HIGH","SEC_CLIENT_ITEM","Клиентский аргумент используется при выдаче предмета/юнита. Проверьте серверные каталоги, оплату и право владения.")
     end
     if lower:find("rarity",1,true) and body:find("=%s*[%w_]+") then
      report(j,"HIGH","SEC_CLIENT_RARITY","Клиент может влиять на редкость. Подтвердите, что результат определяется сервером, а не аргументом RemoteEvent.")
     end
     if lower:find("%.level",1,true) and body:find("%+=") then
      report(j,"MEDIUM","SEC_CLIENT_UPGRADE","Обработчик улучшает уровень при наличии клиентских аргументов. Проверьте стоимость, лимиты и владение.")
     end
    end
    if (handler:find("admin",1,true) or header:lower():find("command",1,true)) and
       (lower:find("command%s*==") or lower:find("%.coins",1,true) or lower:find("%.inventory",1,true)) then
      local block=table.concat(rows,"\n",n,math.min(#rows,n+12)):lower()
      if not block:find("userid",1,true) or not (block:find("allowed",1,true) or block:find("adminids",1,true) or block:find("permission",1,true)) then
       report(n,"HIGH","SEC_ADMIN_AUTH_REVIEW","Привилегированный обработчик: проверьте серверную проверку прав. Автоматически подтвердить её отсутствие нельзя.")
      end
     end
    end
    -- Look for unconditional reward inside a remote callback, without claiming exploitability.
    if header:lower():find("reward",1,true) then
     local snippet=table.concat(rows,"\n",n,math.min(#rows,n+16)):lower()
     if snippet:find("%.coins%s*%+=") and not snippet:find("claimed",1,true) and not snippet:find("cooldown",1,true) then
      report(n,"HIGH","SEC_REWARD_REPLAY","Повторный вызов обработчика награды может начислять валюту. Проверьте одноразовость и серверный статус получения.")
     end
    end
    if header:lower():find("trade",1,true) then
     local snippet=table.concat(rows,"\n",n,math.min(#rows,n+35)):lower()
     if snippet:find("table%.insert") and snippet:find("inventory",1,true)
        and not snippet:find("table%.find") and not snippet:find("ownership",1,true) then
      report(n,"HIGH","SEC_TRADE_OWNERSHIP","Обмен изменяет инвентари, но здесь не видно проверки владения/атомарного переноса. Требуется аудит логики обмена.")
     end
    end
   end
  end
 end
 local SCAN_COOLDOWN = 8
 local lastLocalStart = -math.huge
 local function scan()
  if scanning then
   status.Text = "  Local Scan уже выполняется"
   return
  end
  local remaining = SCAN_COOLDOWN - (os.clock() - lastLocalStart)
  if remaining &gt; 0 then
   status.Text = string.format("  Повторная проверка через %.1f сек.",remaining)
   return
  end
  scanning = true
  lastLocalStart = os.clock()
  scanButton.Text = "SCANNING..."
  task.spawn(function()
   local ok, err = pcall(function()
 deepLastResponse=nil
 clearDeep()
 findings = {}
 local scanned, skipped = 0, 0
 local containers = {game:GetService("Workspace"),game:GetService("ReplicatedStorage"),game:GetService("ReplicatedFirst"),game:GetService("ServerScriptService"),game:GetService("ServerStorage"),game:GetService("StarterGui"),game:GetService("StarterPack"),game:GetService("StarterPlayer"),game:GetService("Lighting"),game:GetService("SoundService")}
 local scripts = {}
 for _,container in ipairs(containers) do
  for _,instance in ipairs(container:GetDescendants()) do
   if instance:IsA("LuaSourceContainer") and not instance.Name:match("^ForgeInspector[_v]") then table.insert(scripts, instance) end
  end
 end
 status.Text = "  Scanning " .. #scripts .. " scripts..."
 for i,scriptInstance in ipairs(scripts) do
  local ok, source = pcall(function() return ScriptEditorService:GetEditorSource(scriptInstance) end)
  if not ok or type(source) ~= "string" or #source &gt; 500000 then
   skipped += 1
  else
   scanned += 1
   auditSource(scriptInstance,source)
   securityAudit(scriptInstance,source)
  end
   if i % 3 == 0 then task.wait() end
 end
 table.sort(findings, function(a,b)
  if a.path ~= b.path then return a.path &lt; b.path end
  if a.line ~= b.line then return a.line &lt; b.line end
  local rank={CRITICAL=1,HIGH=2,MEDIUM=3,LOW=4}
  return (rank[a.severity] or 5)&lt;(rank[b.severity] or 5)
 end)
 status.Text = string.format("  %d scanned  |  %d skipped  |  %d findings%s", scanned, skipped, #findings, #findings &gt;= 500 and " (limit reached)" or "")
 scannedCount, skippedCount = scanned, skipped
 drawResults()
 scannedAt = os.date("!%Y-%m-%dT%H:%M:%SZ")
   end)
   if not ok then status.Text = "  Local Scan failed: " .. tostring(err):sub(1,130) end
   scanButton.Text = "LOCAL SCAN"
   scanning = false
  end)
 end
 scanButton.MouseButton1Click:Connect(scan)
for filter, btn in pairs(filterButtons) do
 btn.MouseButton1Click:Connect(function()
  currentFilter = filter
  drawResults()
 end)
end
local exportFormat = "MARKDOWN"
-- Format already-encoded JSON without modifying its data or values.
local function prettyJSON(compact)
 local out, indent, inString, escapeNext = {}, 0, false, false
 local function nl()
  out[#out+1] = "\n" .. string.rep("  ", indent)
 end
 for i = 1, #compact do
  local ch = compact:sub(i, i)
  if inString then
   out[#out+1] = ch
   if escapeNext then escapeNext = false
   elseif ch == "\\" then escapeNext = true
   elseif ch == '"' then inString = false end
  elseif ch == '"' then
   inString = true; out[#out+1] = ch
  elseif ch == "{" or ch == "[" then
   out[#out+1] = ch
   if compact:sub(i+1,i+1) ~= (ch == "{" and "}" or "]") then
    indent += 1; nl()
   else
    -- Empty objects and arrays need no extra whitespace.
   end
  elseif ch == "}" or ch == "]" then
   local prev = compact:sub(i-1,i-1)
   if prev ~= (ch == "}" and "{" or "[") then
    indent = math.max(0, indent-1); nl()
   end
   out[#out+1] = ch
  elseif ch == "," then
   out[#out+1] = ch; nl()
  elseif ch == ":" then
   out[#out+1] = ": "
  else
   out[#out+1] = ch
  end
 end
 return table.concat(out)
end
-- Export never includes source code. Deep results reflect the server's original line/column.
local function deepExportEntries()
 local scripts, diagnostics = {}, {}
 if not deepLastResponse or type(deepLastResponse.results) ~= "table" then
  return scripts, diagnostics
 end
 for _,item in ipairs(deepLastResponse.results) do
  local name = tostring(item.script or "?")
  local state = tostring(item.status or "unknown")
  table.insert(scripts, {script=name, status=state})
  local securitySeen = {}
  for _,f in ipairs(item.security or {}) do
   local signature = tostring(f.line or 0)..":"..tostring(f.rule or "")
   if not securitySeen[signature] then
    securitySeen[signature] = true
    table.insert(diagnostics, {script=name,line=tonumber(f.line) or 0,column=tonumber(f.column) or 0,kind=tostring(f.rule or "SecurityReview"),severity="security_review",priority=tostring(f.priority or "HIGH"),message=tostring(f.message or "Requires verification")})
   end
  end
  for _,d in ipairs(item.diagnostics or {}) do
   local kind = tostring(d.kind or "")
   local raw = tostring(d.severity or "info"):lower()
   local message = tostring(d.message or "Diagnostic")
   local level = "LOW"
   if raw == "error" then
    if kind == "SyntaxError" or message:lower():find("syntax",1,true) then
     level="HIGH"
    else
     level="MEDIUM"
    end
   end
   table.insert(diagnostics, {
    script=name, line=tonumber(d.line) or 0, column=tonumber(d.column) or 0,
    kind=kind, severity=raw, priority=level, message=message
   })
  end
 end
 table.sort(diagnostics,function(a,b)
  if a.script~=b.script then return a.script&lt;b.script end
  if a.line~=b.line then return a.line&lt;b.line end
  return a.column&lt;b.column
 end)
 return scripts, diagnostics
end
local function exportPayload()
 local items = {}
 for _,f in ipairs(findings) do
  if currentFilter == "ALL" or f.severity == currentFilter then
   table.insert(items, {severity=f.severity, rule=f.code, script=f.path, line=f.line, description=f.message})
  end
 end
 local deepScripts, deepDiags = deepExportEntries()
 local report = {
  tool="Forge Inspector", version="1.0.0", generated_utc=os.date("!%Y-%m-%dT%H:%M:%SZ"),
  local_scan={filter=currentFilter, scanned=scannedCount, skipped=skippedCount, findings=items},
  deep_scan={performed=deepLastResponse~=nil, engine=deepLastResponse and tostring(deepLastResponse.mode or "luau_analyze") or "not_run", scripts=deepScripts, diagnostics=deepDiags},
  note="Security findings are heuristic leads requiring review. No script source included."
 }
 if exportFormat == "JSON" then
  return prettyJSON(HttpService:JSONEncode(report))
 end
 local lines = {
  "# ForgeTools 1.0.0 — Forge Inspector Audit Report", "",
  "Generated (UTC): "..report.generated_utc, "",
  "## Local Scan", "",
  string.format("Filter: %s | Scanned: %d | Skipped: %d | Findings: %d", currentFilter, scannedCount, skippedCount, #items), ""
 }
 for i,f in ipairs(items) do
  table.insert(lines, string.format("### %d. [%s] %s",i,f.severity,f.rule))
  table.insert(lines, "Location: "..f.script..":"..tostring(f.line))
  table.insert(lines, "Review: "..f.description)
  table.insert(lines, "")
 end
 if #items==0 then table.insert(lines,"No local findings under the current filter.") end
 table.insert(lines, "")
 table.insert(lines, "## Deep Scan — Luau Analyzer")
 table.insert(lines, "")
 if not deepLastResponse then
  table.insert(lines,"Not run (or cleared by a new Local Scan).")
 else
  table.insert(lines,string.format("Scripts: %d | Diagnostics: %d",#deepScripts,#deepDiags))
  table.insert(lines,"")
  for _,item in ipairs(deepScripts) do
   table.insert(lines,"Script: "..item.script.." | Status: "..item.status)
  end
  table.insert(lines,"")
  for i,d in ipairs(deepDiags) do
   table.insert(lines,string.format("### %d. [%s] %s (%s)",i,d.priority,d.kind~="" and d.kind or "Luau diagnostic",d.severity))
   table.insert(lines,string.format("Location: %s:%d:%d",d.script,d.line,d.column))
   table.insert(lines,"Message: "..d.message)
   table.insert(lines,"")
  end
  if #deepDiags==0 then table.insert(lines,"No Luau diagnostics returned for these scripts.") end
 end
 table.insert(lines,"")
 table.insert(lines,"&gt; Code is not included. A clean Luau result does not prove security.")
 return table.concat(lines,"\n")
end
local uploadBusy = false
sendButton.MouseButton1Click:Connect(function()
 if uploadBusy then return end
 if #findings == 0 then uploadStatus.Text="Run scan before sending." return end
 local payload = {}
 for _, f in ipairs(findings) do
  if currentFilter == "ALL" or f.severity == currentFilter then
   table.insert(payload, {severity=f.severity,rule=f.code,script=f.path,line=f.line,description=f.message})
  end
 end
 if #payload == 0 then uploadStatus.Text="Current filter has no findings." return end
 uploadBusy=true; sendButton.Text="SENDING..."; uploadStatus.Text="Uploading finding metadata only..."
 task.spawn(function()
  local ok,result=pcall(function()
   return HttpService:RequestAsync({
    Url="https://inspector.mivvinet.xyz/api/v1/inspector/public-reports",
    Method="POST",
    Headers={ ["Content-Type"]="application/json" },
    Body=HttpService:JSONEncode({schema=1,tool="Forge Inspector",version="1.0.0",generated_utc=scannedAt,scanned=scannedCount,skipped=skippedCount,findings=payload})
   })
  end)
  if not ok then uploadStatus.Text="Network error: check HTTP Requests / Output"
  elseif result.Success then
   local decodedOk, data = pcall(function() return HttpService:JSONDecode(result.Body) end)
   uploadStatus.Text = decodedOk and ("RECEIVED  •  " .. tostring(data.findings_received or #payload) .. " findings\nReport ID: " .. tostring(data.report_id or "unknown")) or "Server received report (unreadable receipt)"
  else uploadStatus.Text="UPLOAD FAILED  •  HTTP " .. tostring(result.StatusCode) .. "\n" .. string.sub(tostring(result.Body),1,100) end
  uploadBusy=false; sendButton.Text="SEND LOCAL"
 end)
end)
deepButton.MouseButton1Click:Connect(function()
 exportOverlay.Visible=false
 deepOverlay.Visible=true
 if not deepLastResponse then
  clearDeep()
  deepCard("Готово к Deep Scan", "Выберите до 8 скриптов в Explorer. Лимит 49 152 байта на скрипт; требуется согласие на отправку.", C.mute)
 end
end)
deepClose.MouseButton1Click:Connect(function() deepOverlay.Visible=false end)
local DEEP_MAX_BYTES = 49152
local DEEP_COOLDOWN = 8
local lastDeepStart = -math.huge
deepRun.MouseButton1Click:Connect(function()
 if deepBusy then deepStatus.Text="  Deep Scan уже выполняется" return end
 local remaining = DEEP_COOLDOWN - (os.clock() - lastDeepStart)
 if remaining &gt; 0 then
  deepStatus.Text=string.format("  Повторная проверка через %.1f сек.",remaining)
  return
 end
 -- Deep Scan also supports an explicitly selected script, even without local findings.
 if not consent then deepStatus.Text="  Подтвердите отправку исходников" return end
 -- Collect candidate scripts, not the whole game. Do not persist source in plugin settings.
 local chosen,seen={},{}
 local oversized = {}
 for _,inst in ipairs(Selection:Get()) do
  if #chosen&gt;=8 then break end
  if inst:IsA("LuaSourceContainer") and inst.Parent then
   seen[inst]=true
   local ok,source=pcall(function() return ScriptEditorService:GetEditorSource(inst) end)
   if ok and type(source)=="string" then
    if #source &gt; DEEP_MAX_BYTES then
     table.insert(oversized,{name=inst:GetFullName(),bytes=#source})
    else
     table.insert(chosen,{name=inst:GetFullName(),source=source})
    end
   end
  end
 end
 for _,f in ipairs(findings) do
  if #chosen&gt;=8 then break end
  local inst=f.script
  if inst and inst.Parent and not seen[inst] then
   seen[inst]=true
   local ok,source=pcall(function() return ScriptEditorService:GetEditorSource(inst) end)
   if ok and type(source)=="string" then
    if #source &gt; DEEP_MAX_BYTES then
     table.insert(oversized,{name=f.path,bytes=#source})
    else
     table.insert(chosen,{name=f.path,source=source})
    end
   end
  end
 end
 if #oversized &gt; 0 then
  clearDeep()
  for _, item in ipairs(oversized) do
   deepCard("FILE TOO LARGE",string.format("%s: %d байт. Максимум %d байт (48 КиБ). Уменьшите исходник.",item.name,item.bytes,DEEP_MAX_BYTES),C.high)
  end
  deepStatus.Text=string.format("  Превышен лимит 48 КиБ (%d скрипт(ов)). Не отправлено.",#oversized)
  return
 end
 if #chosen==0 then deepStatus.Text="  Выберите скрипт в Explorer (лимит 48 КиБ)" return end
 lastDeepStart=os.clock()
 local requestBody = HttpService:JSONEncode({schema=1,scripts=chosen})
 if #requestBody &gt; 220000 then
  deepStatus.Text=string.format("  HTTP-запрос слишком большой: %d байт (макс. 220000)",#requestBody)
  return
 end
 deepBusy=true
 deepRun.Text="ANALYZING..."
 deepStatus.Text="  Sending "..#chosen.." scripts to Luau engine..."
 task.spawn(function()
  local ok,response=pcall(function()
   return HttpService:RequestAsync({
    Url="https://inspector.mivvinet.xyz/api/v1/inspector/analyze-public",
    Method="POST", Headers={["Content-Type"]="application/json", ["X-Forge-Install-ID"]=installId},
    Body=requestBody
   })
  end)
  clearDeep()
  if not ok then
   deepStatus.Text="  Network error"
   deepCard("Request error",tostring(response),C.high)
  elseif not response.Success then
   deepStatus.Text="  HTTP "..tostring(response.StatusCode)
   deepCard("Server error",string.sub(tostring(response.Body),1,400),C.high)
  else
   local valid,data=pcall(function() return HttpService:JSONDecode(response.Body) end)
   if not valid or type(data)~="table" or type(data.results)~="table" then
    deepStatus.Text="  Unexpected response"
   else
    deepLastResponse = data
    if type(data.quota)=="table" then
     local remaining = tonumber(data.quota.remaining)
     if remaining then deepStatus.Text = "  Deep Scan: -1 | Осталось "..tostring(remaining).." из 30 за 3 часа" end
    end

    local issues=0
    for _,item in ipairs(data.results) do
     local scriptName=tostring(item.script or "?")
     if item.status=="engine_unavailable" then
      deepCard("Engine not installed",tostring(item.message or "Install luau-analyze"),C.high)
     else
      local diags=item.diagnostics or {}
      local sec=item.security or {}
      issues+=#diags+#sec
      if #diags==0 and #sec==0 then deepCard(scriptName,"Не обнаружены известные проблемы. Это не доказывает безопасность кода.",C.mute) end
      table.sort(sec,function(a,b) return (tonumber(a.line) or 0)&lt;(tonumber(b.line) or 0) end)
      for _,f in ipairs(sec) do
       local level=tostring(f.priority or "MEDIUM")
       local color=level=="CRITICAL" and C.critical or (level=="HIGH" and C.high or C.medium)
       deepCard(level.."  ·  SECURITY  ·  "..scriptName..":"..tostring(f.line or "?"),tostring(f.rule or "Security").." — "..tostring(f.message or "Нужна проверка"),color)
      end
      for _,d in ipairs(diags) do
       -- Compiler error level and issue priority are different concepts.
       -- luau-analyze alone cannot confirm a security vulnerability.
       local kind=tostring(d.kind or "")
       local rawSeverity=tostring(d.severity or "info"):lower()
       local message=tostring(d.message or "Diagnostic")
       local priority="LOW"
       if rawSeverity=="error" then
        if kind=="SyntaxError" or message:lower():find("syntax",1,true) then
         priority="HIGH"
        else
         priority="MEDIUM"
        end
       elseif rawSeverity=="warning" then
        priority="LOW"
       end
       local color = priority=="HIGH" and C.high or (priority=="MEDIUM" and C.medium or C.low)
       local heading=priority.."  ·  LUAU "..rawSeverity:upper().."  ·  "..scriptName..":"..tostring(d.line or "?")
       deepCard(heading,message,color)
      end
     end
    end
    deepStatus.Text=string.format("  %d scripts  |  %d diagnostics",#data.results,issues)
   end
  end
  setConsent(false)
  deepRun.Text="ANALYZE CODE"
  deepBusy=false
 end)
end)
local function refreshReport()
 reportBox.Text = exportPayload()
 resizeReport()
 reportScroll.CanvasPosition = Vector2.new(0,0)
 mdButton.BackgroundColor3 = exportFormat == "MARKDOWN" and C.accent or C.item
 mdButton.TextColor3 = exportFormat == "MARKDOWN" and C.text or C.text
 jsonButton.BackgroundColor3 = exportFormat == "JSON" and C.accent or C.item
 jsonButton.TextColor3 = exportFormat == "JSON" and C.text or C.text
end
deepExportButton.MouseButton1Click:Connect(function()
 refreshReport()
 deepOverlay.Visible=false
 exportOverlay.Visible=true
 task.defer(resizeReport)
end)
exportButton.MouseButton1Click:Connect(function()
 refreshReport()
 exportOverlay.Visible = true
 task.defer(resizeReport)
end)
closeExport.MouseButton1Click:Connect(function() exportOverlay.Visible = false end)
mdButton.MouseButton1Click:Connect(function() exportFormat = "MARKDOWN"; refreshReport() end)
jsonButton.MouseButton1Click:Connect(function() exportFormat = "JSON"; refreshReport() end)
selectButton.MouseButton1Click:Connect(function()
 reportBox:CaptureFocus()
 reportBox.SelectionStart = 1
 reportBox.CursorPosition = #reportBox.Text + 1
end)

-- Studio dock widgets are resizable: keep controls inside narrow windows.
local function layoutToolbar()
 local w = controls.AbsoluteSize.X
 if w &lt; 480 then
  local bw = math.floor((w - 16) / 3)
  scanButton.Position = UDim2.fromOffset(0,0)
  scanButton.Size = UDim2.fromOffset(bw,38)
  exportButton.Position = UDim2.fromOffset(bw+8,0)
  exportButton.Size = UDim2.fromOffset(bw,38)
  deepButton.Position = UDim2.fromOffset((bw+8)*2,0)
  deepButton.Size = UDim2.fromOffset(bw,38)
 else
  scanButton.Size = UDim2.fromOffset(146,38)
  exportButton.Position = UDim2.fromOffset(154,0)
  exportButton.Size = UDim2.fromOffset(145,38)
  deepButton.Position = UDim2.fromOffset(307,0)
  deepButton.Size = UDim2.fromOffset(143,38)
 end
end
controls:GetPropertyChangedSignal("AbsoluteSize"):Connect(layoutToolbar)
task.defer(layoutToolbar)

-- Respect existing selected filter colors; only tween neutral action buttons.
local function motion(button, resting)
 button.AutoButtonColor = false
 local previous
 local function transition(color)
  if previous then previous:Cancel() end
  previous = TweenService:Create(button,TweenInfo.new(0.14,Enum.EasingStyle.Quad,Enum.EasingDirection.Out),{BackgroundColor3=color})
  previous:Play()
 end
 button.MouseEnter:Connect(function() transition(resting == C.accent and C.accentHover or C.border) end)
 button.MouseLeave:Connect(function() transition(resting) end)
end
for _,button in ipairs({scanButton,exportButton,deepButton,deepRun,deepClose,closeExport,sendButton,selectButton}) do
 motion(button, (button == scanButton or button == deepRun) and C.accent or C.item)
end
updateFilters()
showMessage("LOCAL SCAN проверяет код без сети. Выберите находку для перехода к строке; DEEP SCAN проверяет выбранный скрипт на сервере с согласия.")

    return function()
        widget.Enabled = true
    end
end
</ProtectedString>
        </Properties>
      </Item>
    </Item>
  </Item>
</roblox>