<roblox xmlns:xmime="http://www.w3.org/2005/05/xmlmime" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.roblox.com/roblox.xsd" version="4">
	<External>null</External>
	<External>nil</External>
	<Item class="Script" referent="RBXFB9C319D7E284607B16BDB483855">
		<Properties>
			<ProtectedString name="Source"><![CDATA[--[[
    Pisces V5 Studio Bridge Plugin
    Version: v5-2026-05-23-p2

    Bridges Roblox Studio to the Pisces V5 server bridge.
    Implements: M1 (parallel polls, Phase 2), M3 (ACK before exec),
                M4 (read-back after mutation), M5 (idempotent call_id cache),
                M7 (5s heartbeat / 15s liveness).

    Phase 2: 3 parallel long-poll workers (M1) + per-script-path lock to
    prevent two parallel handlers racing on the same script.

    PUBLISHABLE (Creator Store rules): no runtime code compiling or
    execution, no asset-id requires, no environment hacks, no obfuscation.
    Pure HttpService / standard Studio APIs.
]]

--------------------------------------------------------------------------------
-- SERVICES
--------------------------------------------------------------------------------

local ChangeHistoryService = game:GetService("ChangeHistoryService")
local ScriptEditorService  = game:GetService("ScriptEditorService")
local HttpService          = game:GetService("HttpService")
local LogService           = game:GetService("LogService")
local RunService           = game:GetService("RunService")

--------------------------------------------------------------------------------
-- CONSTANTS
--------------------------------------------------------------------------------

local PLUGIN_VERSION       = "v5-2026-11-18-p62-pipeline"
local BASE_URL             = "https://rbxpipeline.com"
local POLL_INTERVAL_S      = 0.05  -- gap between polls when in active mode
                                   -- rev 00978: 0.25 → 0.05. NOTIFY/LISTEN
                                   -- wakes the long-poll instantly, so this
                                   -- only fires when the long-poll returned
                                   -- empty (no work + no NOTIFY). 0.05s keeps
                                   -- the worker spinning ready instead of
                                   -- sleeping 250ms between empty cycles.
local HEARTBEAT_INTERVAL_S = 2     -- rev 00978: 5 → 2. After 5min idle, the
                                   -- worker drops to heartbeat-only. First
                                   -- message after a long idle gap would
                                   -- wait up to 5s for the heartbeat to
                                   -- detect queued work. 2s feels instant
                                   -- to the user and adds negligible cost.
local CACHE_TTL_S          = 180   -- idempotent result cache TTL
-- rev 01104 (P7): 60 → 180. The server's WTQ redelivery lease is ~45s, but a
-- slow tool (long playtest, retried result POST) plus a redelivery can land
-- the re-claim 60-120s after the original ran. At TTL=60 the cache entry was
-- already gone → the tool RE-EXECUTED (double create/edit). 180s covers the
-- worst realistic redelivery window with margin; entries are tiny.
-- 2026-05-25 (rev 00977): bumped back from 1 → 2. Subagent latency audit
-- found that with POLL_WORKERS=1, when the sole worker is mid-cycle
-- (executing a tool + posting result), NEW work from the model has NO
-- listener registered on the PG channel → NOTIFY fires into the void,
-- and the next batch waits the FULL 25s long-poll cycle. Real prod logs
-- showed 39/41 polls timed out at 25s, ~600ms→13s wall-clock per tool.
-- With 2 workers, one stays in LISTEN window while the other executes.
-- Cost: ~$2/day per connected plugin (acceptable for the latency drop).
-- 2026-05-23 cost reduction (REVERTED): dropped from 3 to 1 — assumed
-- LISTEN gave sub-second wakeup, but only when a LISTEN is registered.
local POLL_WORKERS         = 2
local POLL_BATCH           = 8     -- bumped 4→8 so single worker still handles bursts
local POLL_HTTP_TIMEOUT_S  = 10    -- rev p24b: was 30 (matched old 25s LISTEN). Server cut LISTEN 25→5s (rev 01029 V5_POLL_LISTEN_SEC), so 30s wastes 25s on every real network failure before pcall returns. 3 × 30s = 90s before reconnect; 3 × 10s = 30s. Matches 5s LISTEN + 5s headroom.

--------------------------------------------------------------------------------
-- INSTANCE RESOLUTION HELPERS  (ported from V4 pisces_web_plugin.lua:356-446)
--------------------------------------------------------------------------------

local SEARCH_LOCATIONS = {}
pcall(function() table.insert(SEARCH_LOCATIONS, game:GetService("ServerScriptService")) end)
pcall(function() table.insert(SEARCH_LOCATIONS, game:GetService("ReplicatedStorage")) end)
pcall(function() table.insert(SEARCH_LOCATIONS, game:GetService("ServerStorage")) end)
pcall(function() table.insert(SEARCH_LOCATIONS, game:GetService("StarterPlayer")) end)
pcall(function() table.insert(SEARCH_LOCATIONS, game:GetService("StarterGui")) end)
pcall(function() table.insert(SEARCH_LOCATIONS, game:GetService("StarterPack")) end)
pcall(function() table.insert(SEARCH_LOCATIONS, game:GetService("Workspace")) end)
pcall(function() table.insert(SEARCH_LOCATIONS, game:GetService("Lighting")) end)
pcall(function() table.insert(SEARCH_LOCATIONS, game:GetService("ReplicatedFirst")) end)
pcall(function() table.insert(SEARCH_LOCATIONS, game:GetService("SoundService")) end)

local function getServiceByName(name)
    local ok, svc = pcall(function() return game:GetService(name) end)
    return ok and svc or nil
end

local function findInstanceByPath(path)
    if not path or path == "" then return nil end
    path = path:gsub("%[%d+%]", "")  -- strip [N] disambiguation suffixes
    -- rev 01104 (P8): the model often writes "game.ServerScriptService.Foo"
    -- — segment 1 "game" matched no service so the WHOLE path failed and we
    -- fell back to a leaf-name scan. Strip the prefix instead.
    path = path:gsub("^[Gg]ame%.", "")
    local segments = {}
    for seg in path:gmatch("[^%.]+") do table.insert(segments, seg) end
    if #segments == 0 then return nil end

    local current = getServiceByName(segments[1]) or game:FindFirstChild(segments[1])
    if not current then return nil end

    for i = 2, #segments do
        current = current:FindFirstChild(segments[i])
        if not current then return nil end
    end
    return current
end

-- rev 01104 (P3): collect ALL leaf-name matches (capped) instead of
-- returning the first — two scripts named "Config" in different services
-- meant a coin-flip edit/delete of the wrong one.
local function findScriptsByName(name)
    local matches = {}
    if not name or name == "" then return matches end
    for _, svc in ipairs(SEARCH_LOCATIONS) do
        local ok, descs = pcall(function() return svc:GetDescendants() end)
        if ok then
            for _, d in ipairs(descs) do
                if d:IsA("LuaSourceContainer") and d.Name == name then
                    table.insert(matches, d)
                    if #matches >= 5 then return matches end
                end
            end
        end
    end
    return matches
end

local function findScriptByName(name)
    local matches = findScriptsByName(name)
    return matches[1]
end

local function _ambiguousMsg(name, matches)
    local paths = {}
    for _, m in ipairs(matches) do
        table.insert(paths, m:GetFullName())
    end
    return "Script name '" .. name .. "' is AMBIGUOUS - " .. #matches
        .. " scripts match: " .. table.concat(paths, ", ")
        .. ". Re-issue the call with the FULL path of the one you mean."
end

-- Returns inst[, errCode, errMsg]. errCode is set only for ambiguity —
-- plain not-found keeps returning bare nil (callers default to not_found).
local function resolveScriptTarget(path)
    local inst = findInstanceByPath(path)
    if inst and inst:IsA("LuaSourceContainer") then return inst end
    local matches = findScriptsByName(path)
    if #matches == 1 then return matches[1] end
    if #matches > 1 then
        return nil, "ambiguous_target", _ambiguousMsg(path, matches)
    end
    local lastName = path:match("([^%.]+)$")
    if lastName and lastName ~= path then
        matches = findScriptsByName(lastName)
        if #matches == 1 then return matches[1] end
        if #matches > 1 then
            return nil, "ambiguous_target", _ambiguousMsg(lastName, matches)
        end
    end
    return nil
end

local function findOrCreateParent(parentPath)
    -- p28: second return = list of segment paths VIVIFIED as Folders. Silent
    -- vivification is the root of the "my Model/Tool is a Folder" class (the
    -- TrainingDummy case): a child create/set path pointing at a container
    -- that doesn't exist yet quietly manufactures Folders. Callers surface the
    -- list so the model KNOWS it just created placeholders (and can create the
    -- real container class or fix its ordering).
    local inst = findInstanceByPath(parentPath)
    if inst then return inst, nil end
    inst = getServiceByName(parentPath)
    if inst then return inst, nil end

    -- Build missing Folder chain
    local parts = {}
    for seg in parentPath:gmatch("[^%.]+") do table.insert(parts, seg) end
    if #parts == 0 then return game:GetService("ReplicatedStorage"), nil end

    local current = getServiceByName(parts[1])
    if not current then return nil, nil end
    local vivified = nil
    for i = 2, #parts do
        local child = current:FindFirstChild(parts[i])
        if not child then
            child = Instance.new("Folder")
            child.Name = parts[i]
            child.Parent = current
            vivified = vivified or {}
            table.insert(vivified, child:GetFullName())
        end
        current = child
    end
    return current, vivified
end

--------------------------------------------------------------------------------
-- PROPERTY COERCION  (ported from V4 pisces_web_plugin.lua:450-631)
--------------------------------------------------------------------------------

local function vector3FromValue(val)
    if typeof(val) == "Vector3" then return val end
    if type(val) == "table" then
        local x = tonumber(val[1] or val.x or val.X) or 0
        local y = tonumber(val[2] or val.y or val.Y) or 0
        local z = tonumber(val[3] or val.z or val.Z) or 0
        return Vector3.new(x, y, z)
    end
    if type(val) == "string" then
        local x, y, z = val:match("([%d%.%-]+)%s*,%s*([%d%.%-]+)%s*,%s*([%d%.%-]+)")
        if x then return Vector3.new(tonumber(x) or 0, tonumber(y) or 0, tonumber(z) or 0) end
    end
    return nil
end

local function color3FromValue(val)
    if typeof(val) == "Color3" then return val end
    if type(val) == "table" then
        local r = tonumber(val[1] or val.r or val.R) or 0
        local g = tonumber(val[2] or val.g or val.G) or 0
        local b = tonumber(val[3] or val.b or val.B) or 0
        if r > 1 or g > 1 or b > 1 then
            return Color3.fromRGB(math.floor(r), math.floor(g), math.floor(b))
        end
        return Color3.new(r, g, b)
    end
    if type(val) == "string" then
        local r, g, b = val:match("([%d%.]+)%s*,%s*([%d%.]+)%s*,%s*([%d%.]+)")
        if r then
            r, g, b = tonumber(r) or 0, tonumber(g) or 0, tonumber(b) or 0
            if r > 1 or g > 1 or b > 1 then return Color3.fromRGB(math.floor(r), math.floor(g), math.floor(b)) end
            return Color3.new(r, g, b)
        end
        local hex = val:match("#(%x%x%x%x%x%x)")
        if hex then return Color3.fromHex("#" .. hex) end
    end
    return nil
end

-- 2026-05-29 (rev 01054) GUI value coercion. The model emits UI properties as
-- arrays (preferred) OR comma/space strings (e.g. Size "0, 220, 0, 64",
-- AnchorPoint "0.5, 0", CornerRadius "0, 16", gradient Transparency
-- "0 0 0.35 1"). Before this rev coercePropertyValue had NO branch for UDim2 /
-- Vector2 / UDim / NumberSequence / ColorSequence, so every one fell through to
-- the raw value and Roblox rejected the assignment → "I don't see the UI". These
-- helpers accept native types, arrays, AND numeric strings so whatever the model
-- produces lands.
local function numbersFromValue(val)
    -- Parse an ordered list of numbers from an array or a comma/space string.
    if type(val) == "table" then
        local t = {}
        for i = 1, #val do t[i] = tonumber(val[i]) end
        return t
    end
    if type(val) == "number" then return { val } end
    if type(val) == "string" then
        local t = {}
        for num in val:gmatch("(-?%d*%.?%d+)") do t[#t + 1] = tonumber(num) end
        return t
    end
    return nil
end

local function vector2FromValue(val)
    if typeof(val) == "Vector2" then return val end
    local n = numbersFromValue(val)
    if n and n[1] then return Vector2.new(n[1] or 0, n[2] or 0) end
    return nil
end

local function udim2FromValue(val)
    if typeof(val) == "UDim2" then return val end
    if typeof(val) == "UDim" then return UDim2.new(val, UDim.new()) end
    local n = numbersFromValue(val)
    if not n then return nil end
    if n[4] ~= nil then                       -- {scaleX, offsetX, scaleY, offsetY}
        return UDim2.new(n[1] or 0, n[2] or 0, n[3] or 0, n[4] or 0)
    elseif n[2] ~= nil then                   -- two numbers → pixel offset
        return UDim2.fromOffset(n[1] or 0, n[2] or 0)
    end
    return nil
end

local function udimFromValue(val)
    if typeof(val) == "UDim" then return val end
    local n = numbersFromValue(val)
    if not n then return nil end
    if n[2] ~= nil then return UDim.new(n[1] or 0, n[2] or 0) end  -- {scale, offset}
    if n[1] ~= nil then return UDim.new(0, n[1]) end               -- single → offset px
    return nil
end

local function rectFromValue(val)
    if typeof(val) == "Rect" then return val end
    local n = numbersFromValue(val)
    if n and n[4] ~= nil then return Rect.new(n[1], n[2], n[3], n[4]) end
    return nil
end

local function numberSequenceFromValue(val)
    if typeof(val) == "NumberSequence" then return val end
    if type(val) == "number" then return NumberSequence.new(val) end
    -- Array of {time=,value=} keypoint tables. p30: models emit CAPITALIZED
    -- keys ({Time=0, Value=0.35} — the Roblox property names), which fell
    -- through here and surfaced as "NumberSequence expected, got table" (live
    -- prod failure, 2026-07-04: UIGradient.Transparency silently lost). Accept
    -- both cases, sort ascending, and pad the 0/1 endpoints Roblox requires.
    if type(val) == "table" and type(val[1]) == "table" then
        local kps = {}
        for _, kp in ipairs(val) do
            local t = tonumber(kp.time or kp.Time or kp.t or kp[1])
            local v = tonumber(kp.value or kp.Value or kp.v
                or kp.transparency or kp.Transparency or kp[2])
            if t and v then
                kps[#kps + 1] = { t = math.clamp(t, 0, 1), v = v }
            end
        end
        if #kps >= 1 then
            table.sort(kps, function(a, b) return a.t < b.t end)
            local pts, last = {}, -1
            for _, kp in ipairs(kps) do
                local t = kp.t
                if t <= last then t = math.min(1, last + 0.001) end
                last = t
                pts[#pts + 1] = NumberSequenceKeypoint.new(t, kp.v)
            end
            if pts[1].Time ~= 0 then
                table.insert(pts, 1, NumberSequenceKeypoint.new(0, pts[1].Value))
            end
            if pts[#pts].Time ~= 1 then
                pts[#pts + 1] = NumberSequenceKeypoint.new(1, pts[#pts].Value)
            end
            local ok, seq = pcall(NumberSequence.new, pts)
            if ok then return seq end
        end
    end
    local n = numbersFromValue(val)
    if not n or #n == 0 then return nil end
    if #n == 1 then return NumberSequence.new(n[1]) end          -- constant
    if #n == 2 then return NumberSequence.new(n[1], n[2]) end    -- start → end ramp
    if #n % 2 == 0 then                                          -- flat (time,value) pairs
        local kps, last = {}, -1
        for i = 1, #n, 2 do
            local t = math.clamp(n[i], 0, 1)
            if t <= last then t = math.min(1, last + 0.001) end  -- enforce ascending
            last = t
            kps[#kps + 1] = NumberSequenceKeypoint.new(t, n[i + 1])
        end
        if kps[1].Time ~= 0 then table.insert(kps, 1, NumberSequenceKeypoint.new(0, kps[1].Value)) end
        if kps[#kps].Time ~= 1 then kps[#kps + 1] = NumberSequenceKeypoint.new(1, kps[#kps].Value) end
        local ok, seq = pcall(NumberSequence.new, kps)
        if ok then return seq end
    end
    return nil
end

local function colorSequenceFromValue(val)
    if typeof(val) == "ColorSequence" then return val end
    if typeof(val) == "Color3" then return ColorSequence.new(val) end
    -- Array of {time=,color=[r,g,b]} keypoints. p30: accept capitalized keys
    -- (same failure class as numberSequenceFromValue above) + sort/pad so a
    -- keypoint list not spanning 0..1 coerces instead of throwing.
    if type(val) == "table" and type(val[1]) == "table" then
        local kps = {}
        for _, kp in ipairs(val) do
            local t = tonumber(kp.time or kp.Time or kp.t or kp[1])
            local c = color3FromValue(kp.color or kp.Color
                or kp.value or kp.Value or kp)
            if t and c then
                kps[#kps + 1] = { t = math.clamp(t, 0, 1), c = c }
            end
        end
        if #kps >= 1 then
            table.sort(kps, function(a, b) return a.t < b.t end)
            local pts, last = {}, -1
            for _, kp in ipairs(kps) do
                local t = kp.t
                if t <= last then t = math.min(1, last + 0.001) end
                last = t
                pts[#pts + 1] = ColorSequenceKeypoint.new(t, kp.c)
            end
            if pts[1].Time ~= 0 then
                table.insert(pts, 1, ColorSequenceKeypoint.new(0, pts[1].Value))
            end
            if pts[#pts].Time ~= 1 then
                pts[#pts + 1] = ColorSequenceKeypoint.new(1, pts[#pts].Value)
            end
            local ok, seq = pcall(ColorSequence.new, pts)
            if ok then return seq end
        end
    end
    local c = color3FromValue(val)
    if c then return ColorSequence.new(c) end
    return nil
end

-- 2026-05-29 (rev 01057) NumberRange coercion. ParticleEmitter.Speed /
-- .Lifetime / .RotSpeed / .Rotation (and Sound playback ranges) are
-- NumberRange-typed. coercePropertyValue had NO branch for them, so the
-- model's "5,15" / [0.03,0.08] / 5 fell through raw and Roblox rejected the
-- assignment ("NumberRange expected, got string") — the muzzle particles
-- never configured. Accept a native NumberRange, a single number (min==max),
-- an array, or a comma/space string.
local function numberRangeFromValue(val)
    if typeof(val) == "NumberRange" then return val end
    if type(val) == "number" then return NumberRange.new(val) end
    local n = numbersFromValue(val)
    if n and n[1] ~= nil then
        if n[2] ~= nil then return NumberRange.new(n[1], n[2]) end
        return NumberRange.new(n[1])
    end
    return nil
end

-- Property names whose Roblox type we know even when the live value reads as a
-- default (belt-and-suspenders alongside the expectedType detection below).
local _GUI_PROP_TYPES = {
    Size = "UDim2", Position = "UDim2", CanvasSize = "UDim2", CanvasPosition = "Vector2",
    AnchorPoint = "Vector2", ImageRectOffset = "Vector2", ImageRectSize = "Vector2",
    CornerRadius = "UDim",
    PaddingLeft = "UDim", PaddingRight = "UDim", PaddingTop = "UDim", PaddingBottom = "UDim",
}

local function resolveEnumValue(enumTypeName, valueName)
    local ok, enumType = pcall(function() return Enum[enumTypeName] end)
    if not ok or not enumType then return nil end
    local okVal, enumVal = pcall(function() return enumType[valueName] end)
    if okVal and enumVal then return enumVal end
    local lower = tostring(valueName):lower()
    for _, item in ipairs(enumType:GetEnumItems()) do
        if item.Name:lower() == lower then return item end
    end
    return nil
end

local function coerceBool(val, default)
    if type(val) == "boolean" then return val end
    if type(val) == "string" then
        local l = val:lower()
        if l == "true" or l == "yes" or l == "1" then return true end
        if l == "false" or l == "no" or l == "0" then return false end
    end
    if type(val) == "number" then return val ~= 0 end
    return default
end

-- 2026-07-09 (audit): properties whose canonical Roblox casing carries INTERNAL
-- capitals that normalizePropertyName's char-by-char pass cannot recover. It
-- only up-cases the first letter and letters right after an underscore, so an
-- all-lowercase "cframe" became the INVALID "Cframe" — the set then threw, hit
-- trySetAttributeFallback, and got stored as an Attribute while still reporting
-- SUCCESS (the model never learned CFrame didn't actually move). Keyed by the
-- lowercased canonical name so any incoming casing (cframe / CFRAME / c_frame)
-- lands on the right property; the key is derived from the value to rule out
-- key/value drift. Extend freely — a miss just falls through to the old rule.
local _CANONICAL_PROP_CASING = {}
for _, _cn in ipairs({
    "CFrame", "MaxHealth", "WalkSpeed", "JumpPower", "JumpHeight", "HipHeight",
    "MaxSlopeAngle", "ZIndex", "ZOffset", "AnchorPoint", "LayoutOrder", "SortOrder",
    "FillDirection", "AutomaticSize", "ScaleType", "SliceCenter", "RichText",
    "BackgroundColor3", "BackgroundTransparency", "BorderColor3", "BorderSizePixel",
    "BorderMode", "TextColor3", "TextScaled", "TextWrapped", "TextSize", "TextTruncate",
    "TextStrokeColor3", "TextStrokeTransparency", "TextXAlignment", "TextYAlignment",
    "ImageColor3", "ImageTransparency", "ImageRectOffset", "ImageRectSize",
    "ScrollBarThickness", "CanvasSize", "ClipsDescendants", "CanCollide", "CanTouch",
    "CanQuery", "CastShadow", "SoundId", "MeshId", "TextureId", "MaxForce", "MaxTorque",
    "MaxVelocity", "PrimaryPart", "BrickColor", "SurfaceType", "CollisionGroup",
    "CustomPhysicalProperties", "AssemblyLinearVelocity", "AssemblyAngularVelocity",
    -- p38: the ONLY Roblox properties with underscores. normalizePropertyName's
    -- snake_case repair strips '_letter' BEFORE this lookup, so a correctly
    -- spelled ColorShift_Top arrived as the invalid ColorShiftTop and no
    -- set_property could ever set it (prod 8e7db92c doom loop, 2026-07-13).
    "ColorShift_Top", "ColorShift_Bottom",
}) do
    _CANONICAL_PROP_CASING[_cn:lower()] = _cn
    -- p38: also key the underscore-STRIPPED form — normalizePropertyName has
    -- already removed underscores by the time it consults this table.
    local _stripped = _cn:lower():gsub("_", "")
    if _stripped ~= _cn:lower() then
        _CANONICAL_PROP_CASING[_stripped] = _cn
    end
end

local function normalizePropertyName(raw)
    local prop = tostring(raw or ""):gsub("^%s+", ""):gsub("%s+$", "")
    prop = prop:gsub("_(%a)", function(c) return c:upper() end)
    prop = prop:sub(1, 1):upper() .. prop:sub(2)
    -- recover internal capitals the pass above can't (cframe → CFrame)
    return _CANONICAL_PROP_CASING[prop:lower()] or prop
end

-- p56 (2026-10-25): Roblox couples TextScaled and TextWrapped: TextScaled=true
-- forces TextWrapped=true, and TextWrapped=false set AFTER it turns TextScaled
-- back OFF. pairs() order is arbitrary, so a scaled label rendered at the 8 px
-- default (Studio capture: every EggShop label 54x10 in a 187x38 box).
-- Iterate a property table with TextScaled applied LAST.
local function _propPairs(t)
    local list, last = {}, {}
    for k, v in pairs(t) do
        if normalizePropertyName(k) == "TextScaled" then
            table.insert(last, {k, v})
        else
            table.insert(list, {k, v})
        end
    end
    for _, kv in ipairs(last) do table.insert(list, kv) end
    local i = 0
    return function()
        i = i + 1
        local kv = list[i]
        if kv then return kv[1], kv[2] end
        return nil
    end
end

-- 2026-05-25 (rev p19) — known Instance-typed property names. The
-- runtime-detection path (`typeof(currentVal) == "Instance"`) fails on
-- freshly-created instances because the property defaults to nil →
-- `typeof(nil)` is "nil", not "Instance". Plugin log showed
-- "Unable to assign Part1, BasePart expected, got string" for every
-- WeldConstraint the model emitted. This allowlist lets the string-
-- path → Instance coercion fire even when the property has no
-- current value to inspect.
local _INSTANCE_PROP_NAMES = {
    Part0 = true, Part1 = true,           -- Weld, WeldConstraint, Motor6D, Snap
    PrimaryPart = true,                    -- Model
    Adornee = true,                        -- SurfaceGui, BillboardGui, Light, etc.
    Attachment0 = true, Attachment1 = true,-- AlignPosition, AlignOrientation,
                                           -- Constraint subclasses, Beam,
                                           -- HingeConstraint, RopeConstraint, etc.
    Value = true,                          -- ObjectValue.Value (note: BoolValue
                                           -- .Value etc. are not Instance, but
                                           -- coerceBool / tonumber branches above
                                           -- handle those before this fires)
    Target = true,                         -- Decal/Texture targets, AnimationController
    Texture = true,                        -- Some legacy properties
    RootPart = true,                       -- Humanoid.RootPart (read-only but
                                           -- some user code attempts to set)
}

local function coercePropertyValue(instance, property, value)
    if value == nil then return nil end
    local expectedType = ""
    pcall(function() local cur = instance[property]; if cur ~= nil then expectedType = typeof(cur) end end)

    -- p28 (ported from web plugin v8.7): instance-REFERENCE properties. The
    -- model passes a PATH STRING for properties that expect a live Instance —
    -- Part0/Part1 (welds), PrimaryPart, Adornee, Attachment0/1. Without
    -- resolving, `inst.Part0 = "path"` throws "BasePart expected, got string"
    -- (live prod failure class, 2026-07-01) and the weld binds NOTHING.
    if type(value) == "string" then
        local _p = tostring(property)
        local _isRef = (expectedType == "Instance")
            or _p == "Part0" or _p == "Part1" or _p == "Part"
            or _p == "PrimaryPart" or _p == "Adornee"
            or _p == "Attachment0" or _p == "Attachment1"
        if _isRef then
            local _inst = findInstanceByPath(value)
            if _inst then return _inst end
        end
    end

    -- 2026-05-29 (rev 01057) the name-based "color" match must NOT fire when
    -- the live property is a ColorSequence/NumberSequence (e.g.
    -- ParticleEmitter.Color is a ColorSequence). Before this guard it returned
    -- a Color3 → "ColorSequence expected, got Color3". Only treat as Color3
    -- when the type really is Color3, or the type is unknown and the name says
    -- color.
    if expectedType == "Color3"
            or (expectedType ~= "ColorSequence"
                and expectedType ~= "NumberSequence"
                and expectedType ~= "Sequence"
                and tostring(property):lower():find("color")) then
        local c = color3FromValue(value)
        if c then return c end
    end
    if expectedType == "BrickColor" and type(value) == "string" then
        local ok, bc = pcall(function() return BrickColor.new(value) end)
        if ok then return bc end
    end
    if expectedType == "Vector3" then
        local v = vector3FromValue(value)
        if v then return v end
    end
    if expectedType == "CFrame" then
        -- rev 01104 (P9): preserve ROTATION. The old path only did
        -- CFrame.new(position) → every rotated part landed axis-aligned
        -- (ramps flat, tilted signs upright). Handle the rich forms first:
        --   • 12-number array  → CFrame.new(x,y,z, R00..R22) verbatim
        --   • {position=..., orientation=...} (degrees) → pos * Angles
        --   • {position=..., rotation=...} alias
        -- then fall back to position-only.
        if type(value) == "table" then
            -- 12-component array (numeric keys)
            local comps, n = {}, 0
            for i = 1, 12 do
                local c = tonumber(value[i])
                if c == nil then break end
                comps[i] = c; n = i
            end
            if n == 12 then
                local ok, cf = pcall(function() return CFrame.new(unpack(comps)) end)
                if ok then return cf end
            end
            local posV = vector3FromValue(value.position or value.Position or value.pos)
            local oriV = vector3FromValue(
                value.orientation or value.Orientation
                or value.rotation or value.Rotation)
            if posV and oriV then
                local ok, cf = pcall(function()
                    return CFrame.new(posV)
                        * CFrame.Angles(
                            math.rad(oriV.X), math.rad(oriV.Y), math.rad(oriV.Z))
                end)
                if ok then return cf end
            end
        end
        local v = vector3FromValue(value)
        if v then return CFrame.new(v) end
    end
    if expectedType == "EnumItem" and type(value) == "string" then
        local current = nil; pcall(function() current = instance[property] end)
        if current and typeof(current) == "EnumItem" then
            local resolved = resolveEnumValue(tostring(current.EnumType), value)
            if resolved then return resolved end
        end
    end
    -- 2026-05-25 (rev 00991) Instance-typed props: WeldConstraint.Part0/Part1,
    -- Motor6D.Part0/Part1, ObjectValue.Value, PrimaryPart, Adornee, etc. expect
    -- an Instance ref. The model emits string paths like
    -- "ReplicatedStorage.SportsCar.Chassis"; without this branch the string is
    -- handed to pcall and silently rejected, so the weld is created with blank
    -- Part0/Part1 and the parts don't move together.
    --
    -- 2026-05-25 (rev p19) extended fix: on a FRESHLY created WeldConstraint,
    -- Part0/Part1 are nil by default → `typeof(nil)` is "nil" not "Instance",
    -- so the runtime-detection branch above silently skipped. Plugin log
    -- showed "Unable to assign Part1, BasePart expected, got string".
    -- Allowlist the known Instance-typed property names so the coercion
    -- fires regardless of the current value being nil.
    if (expectedType == "Instance" or _INSTANCE_PROP_NAMES[property])
            and type(value) == "string" then
        local resolved = findInstanceByPath(value)
        if resolved then return resolved end
    end
    if expectedType == "boolean" then return coerceBool(value, false) end
    if expectedType == "number" then
        local n = tonumber(value)
        if n then return n end
    end
    if expectedType == "string" and type(value) ~= "string" then return tostring(value) end
    if property == "Font" and type(value) == "string" then
        local e = resolveEnumValue("Font", value)
        if e then return e end
    end
    if property == "Material" and type(value) == "string" then
        local e = resolveEnumValue("Material", value)
        if e then return e end
    end
    -- 2026-05-29 (rev 01054) GUI value types. Keyed on the live property type
    -- (a fresh Frame's Size is already a UDim2, a UICorner's CornerRadius a
    -- UDim, a UIGradient's Transparency a NumberSequence) with a name-based
    -- fallback for any default-nil cases. Accept arrays AND comma/space strings.
    local guiType = expectedType
    if guiType == "" then guiType = _GUI_PROP_TYPES[property] or "" end
    if guiType == "UDim2" then
        local v = udim2FromValue(value); if v then return v end
    elseif guiType == "Vector2" then
        local v = vector2FromValue(value); if v then return v end
    elseif guiType == "UDim" then
        local v = udimFromValue(value); if v then return v end
    elseif guiType == "NumberSequence" then
        local v = numberSequenceFromValue(value); if v then return v end
    elseif guiType == "ColorSequence" then
        local v = colorSequenceFromValue(value); if v then return v end
    elseif guiType == "NumberRange" then
        local v = numberRangeFromValue(value); if v then return v end
    elseif guiType == "Rect" then
        local v = rectFromValue(value); if v then return v end
    end
    -- 2026-05-29 (rev 01057) name fallback for NumberRange props that read as
    -- a default-nil value on a freshly created instance (so expectedType was
    -- "" and the live-type branch above couldn't fire).
    if guiType == "" then
        local pl = tostring(property):lower()
        if pl == "speed" or pl == "lifetime" or pl == "rotspeed" then
            local v = numberRangeFromValue(value); if v then return v end
        end
    end
    return value
end

local function countLines(source)
    if not source or source == "" then return 0 end
    local count = 0
    for _ in (source .. "\n"):gmatch("(.-)\n") do count = count + 1 end
    return count
end

--------------------------------------------------------------------------------
-- EFFECTIVE PLACE ID  (2026-07-05 p31)
--------------------------------------------------------------------------------
-- Unsaved Studio places ALL report game.PlaceId == 0, so every unsaved place
-- shared the (api_key, "0") snapshot bucket: a brand-new unsaved place read the
-- PREVIOUS unsaved place's stale index (phantom tools / wrong scripts) and its
-- incremental syncs piled on top of the old rows. Give each unsaved DataModel
-- its own STABLE bucket id by stamping a GUID attribute on ServerStorage and
-- returning "u:<guid>". The attribute survives plugin reloads within the same
-- place (same DataModel); a genuinely new unsaved place gets a fresh DataModel
-- with no attribute → a fresh id → its own clean bucket. Saved places
-- (PlaceId > 0) are unchanged. The server treats place_id as an opaque string,
-- so this is fully backward-compatible. Kill switch: V5_UNSAVED_BUCKETS = false
-- restores the raw-PlaceId behavior.
local V5_UNSAVED_BUCKETS = true
local UNSAVED_ID_ATTR    = "PiscesUnsavedId"
-- Last-resort fallback: if ServerStorage attributes don't persist (name
-- rejected, read-only DM, …) a stable in-memory id keeps us from minting a new
-- bucket on every reconcile → full-resync thrash. Only trusted when the
-- persisted attribute is genuinely unavailable (verified by read-back below).
local _unsaved_id_cache = nil

local function v5_effective_place_id()
    local okP, pid = pcall(function() return game.PlaceId end)
    if okP and type(pid) == "number" and pid > 0 then
        return tostring(pid)   -- saved place: real, globally-unique id
    end
    if not V5_UNSAVED_BUCKETS then
        return tostring((okP and pid) or 0)
    end
    local okS, ss = pcall(function() return game:GetService("ServerStorage") end)
    if okS and ss then
        -- Persisted attribute is the source of truth: it's per-DataModel, so a
        -- genuinely NEW unsaved place reads nil here and mints its own bucket.
        local nonce
        pcall(function() nonce = ss:GetAttribute(UNSAVED_ID_ATTR) end)
        if type(nonce) == "string" and nonce ~= "" then
            return "u:" .. nonce
        end
        -- Fresh place (or persistence unavailable): mint, write, verify.
        local minted = HttpService:GenerateGUID(false)
        pcall(function() ss:SetAttribute(UNSAVED_ID_ATTR, minted) end)
        local rb
        pcall(function() rb = ss:GetAttribute(UNSAVED_ID_ATTR) end)
        if rb == minted then
            return "u:" .. minted   -- persistence works → attribute stays authoritative
        end
        -- write didn't stick → degrade to the in-memory id (no thrash).
        if not _unsaved_id_cache then _unsaved_id_cache = minted end
        return "u:" .. _unsaved_id_cache
    end
    -- no ServerStorage at all: stable in-memory id beats a churning "0".
    if not _unsaved_id_cache then _unsaved_id_cache = HttpService:GenerateGUID(false) end
    return "u:" .. _unsaved_id_cache
end

--------------------------------------------------------------------------------
-- PLUGIN STATE
--------------------------------------------------------------------------------

local plugin_state = {
    connected             = false,
    api_key               = "",
    place_id              = v5_effective_place_id(),
    -- 2026-05-30: report the place NAME so the website pill shows the real game
    -- name (e.g. "dddddd") instead of "Untitled place". game.Name is what Studio
    -- calls the open place; /v5/connect now stores it (was never sent before).
    place_name            = tostring(game.Name),
    session_id            = HttpService:GenerateGUID(false),
    last_heartbeat_at     = 0,
    -- 2026-05-23: user explicitly clicked Disconnect — even if main_loop
    -- gets re-triggered by Studio lifecycle, do nothing while this is true.
    user_disconnected     = false,
    -- UI counters (populated by execute_tool, displayed by the dock widget)
    calls_handled         = 0,
    last_call_latency_ms  = 0,
    last_call_label       = "",   -- last tool executed (for log/UI)
    last_poll_at          = 0,
    -- rev p24c (2026-05-27): shared reconnect coordination. Any worker
    -- that hits _RECONNECT_AFTER_FAILS consecutive HTTP failures can
    -- now trigger reconnect, but only ONE worker at a time fires
    -- v5_connect (the gate flips this true before, false after). The
    -- previous rev p24b only let worker_id == 1 trigger reconnect, so
    -- worker 2 sat in a dead TCP socket forever after a worker recycle.
    -- Caught by fresh-eyes reviewer in rev 01030 audit (main.lua:1619).
    reconnect_in_progress = false,
    -- monotonic timestamp of last successful poll (any worker). Used by
    -- a watchdog so we can re-test connectivity even if the failure
    -- counter hasn't reached the reconnect threshold yet.
    last_successful_poll_at = 0,
    -- p29 audit: poll-worker generation. Each Connect/Reconnect bumps this
    -- and spawns fresh workers stamped with the new value; stale workers
    -- (often parked inside a 25s long-poll while `connected` flips
    -- false→true underneath them) see the mismatch on their next loop
    -- check and exit. Without it every Reconnect click stacked +2 workers
    -- that polled forever.
    worker_gen = 0,
}

-- Forward declaration: UI panel installs the real implementation after build.
-- All call sites (v5_connect, execute_tool, button handlers, etc.) reference
-- this upvalue, which Lua re-binds when the UI assigns the real function.
local ui_log = function(_level, _msg) end

-- call_id → {success, result, name, source_after, value_after, timestamp}
local result_cache = {}

-- M1: per-script-path mutex — prevents two parallel workers racing on the
-- same script file.  Key = script path string, value = true while locked.
local _execute_locks = {}

-- Cancellation set: call_ids that the server has cancelled.  Workers check
-- this before executing and post a cancelled result immediately if matched.
local _cancelled_call_ids = {}

--------------------------------------------------------------------------------
-- CACHE HELPERS  (M5 — idempotent execution)
--------------------------------------------------------------------------------

local function cache_prune()
    local now = os.time()
    for cid, entry in pairs(result_cache) do
        if (now - entry.timestamp) > CACHE_TTL_S then
            result_cache[cid] = nil
        end
    end
    -- p29 audit: _cancelled_call_ids entries for calls that were cancelled
    -- but never redelivered were retained FOREVER (slow leak over a long
    -- Studio session). Same TTL discipline as the result cache.
    for cid, ts in pairs(_cancelled_call_ids) do
        if type(ts) == "number" and (now - ts) > CACHE_TTL_S then
            _cancelled_call_ids[cid] = nil
        end
    end
end

local function cache_get(call_id)
    local entry = result_cache[call_id]
    if not entry then return nil end
    if (os.time() - entry.timestamp) > CACHE_TTL_S then
        result_cache[call_id] = nil
        return nil
    end
    return entry
end

local function cache_put(call_id, success, result, name, source_after, value_after)
    result_cache[call_id] = {
        timestamp    = os.time(),
        success      = success,
        result       = result,
        name         = name,
        source_after = source_after,
        value_after  = value_after,
    }
end

--------------------------------------------------------------------------------
-- V5 HTTP PRIMITIVES
--------------------------------------------------------------------------------

local function v5_headers()
    return {
        ["Content-Type"]      = "application/json",
        -- Server reads X-Pisces-Api-Key (or Authorization: Bearer). Send both
        -- so we work regardless of which resolver path is used downstream.
        ["X-Pisces-Api-Key"]  = plugin_state.api_key,
        ["Authorization"]     = "Bearer " .. plugin_state.api_key,
        ["X-Pisces-Session"]  = plugin_state.session_id,
        ["X-Plugin-Version"]  = PLUGIN_VERSION,
        ["X-Place-Id"]        = plugin_state.place_id,
    }
end

-- Forward declarations (p21): v5_connect references v5_sync_codebase which
-- is declared further down. Without these locals the closure inside
-- v5_connect would resolve them as globals and silently no-op.
local v5_sync_codebase
-- rev 01090b: the freshness watcher (defined after v5_sync_codebase) is armed
-- from inside v5_connect, so it must be forward-declared too.
local v5_install_freshness_watchers
local v5_freshness_reconcile
-- p48: instance-tree watchers (manual Explorer edits → tree resync) are armed
-- from inside v5_connect alongside the script freshness watcher.
local v5_install_tree_watchers

-- p29 (2026-07-02): resolve the REAL published place name. game.Name captured
-- at module init is whatever Studio had before the place finished loading
-- (often "Baseplate"/"Place1"), which is why the website pill said
-- "Untitled place" even for published games. Strategy:
--   1. re-read game.Name live (plugins load before the DataModel settles),
--   2. for published places (PlaceId > 0) prefer the marketplace title via
--      GetProductInfo — the authoritative published name,
--   3. push updates through the heartbeat (place_name field) so a late
--      resolve or a rename reaches the server without a reconnect.
local function v5_refresh_place_name()
    local live = ""
    pcall(function() live = tostring(game.Name or "") end)
    -- strip a ".rbxl" suffix from file-based names so the pill reads clean
    live = live:gsub("%.rbxl$", "")
    if live ~= "" then
        plugin_state.place_name = live
    end
    return plugin_state.place_name
end

local function v5_resolve_published_name_async()
    local pid = tonumber(plugin_state.place_id) or 0
    if pid <= 0 then return end
    task.spawn(function()
        local ok, info = pcall(function()
            local MarketplaceService = game:GetService("MarketplaceService")
            return MarketplaceService:GetProductInfo(pid)
        end)
        if ok and type(info) == "table" and type(info.Name) == "string"
                and info.Name ~= ""
                -- private/unapproved places return the literal placeholder
                -- "[ TITLE UNAVAILABLE ]" — worse than the live game.Name we
                -- already have; never adopt it.
                and not info.Name:lower():find("title unavailable", 1, true) then
            plugin_state.place_name = info.Name
        end
    end)
end

-- p29 (2026-07-02): SCRIPT-INJECTION PERMISSION PROBE. The #1 prod build
-- killer is Studio's "Allow Script Injection" being denied/unanswered — every
-- create_script/edit_script bounces mid-build. Probe at connect time instead:
-- write-then-destroy a throwaway ModuleScript in ServerStorage. Three outcomes:
--   granted  → instant silent success,
--   denied   → instant throw → status carried on connect/heartbeat → web UI
--              pins a fix-it banner before the user even sends a prompt,
--   never asked → Studio pops its permission modal NOW, while the user is
--              looking at Studio (they just clicked Connect) instead of
--              mid-build; the answer resolves the parked coroutine and the
--              next heartbeat carries it.
local function v5_probe_injection_async()
    -- Probe ONCE per Studio session: reconnects are frequent (worker recycles,
    -- network blips) and each re-probe would re-pop the permission modal on
    -- users who haven't answered + spam undo history. Live tool results keep
    -- the status current after the first resolution.
    if plugin_state.injection_status ~= nil then return end
    task.spawn(function()
        -- "__PiscesV" prefix rides the _is_internal_script filter so the
        -- freshness watcher / codebase sync NEVER index the probe as user code.
        local probeName = "__PiscesV5PermProbe"
        local container = game:GetService("ServerStorage")
        pcall(function()
            local old = container:FindFirstChild(probeName)
            if old then old:Destroy() end
        end)
        local okP, probe = pcall(function()
            local m = Instance.new("ModuleScript")
            m.Name = probeName
            m.Parent = container
            return m
        end)
        if not okP or not probe then return end
        local okW, errW = pcall(function()
            ScriptEditorService:UpdateSourceAsync(probe, function()
                return "-- Pipeline permission probe (auto-removed)\nreturn true\n"
            end)
        end)
        pcall(function() probe:Destroy() end)
        if okW then
            plugin_state.injection_status = "granted"
        else
            local es = tostring(errW):lower()
            if es:find("injection", 1, true) or es:find("permission", 1, true)
                or es:find("denied", 1, true) then
                plugin_state.injection_status = "denied"
                warn("[Pipeline] Script Injection permission is DENIED — "
                    .. "enable it: Plugins tab -> Manage Plugins -> Pipeline "
                    .. "-> allow Script Injection")
                ui_log("err", "Script Injection is blocked — enable it in "
                    .. "Manage Plugins, or Pipeline can't write scripts")
            end
            -- any other throw: leave status unknown (nil) — don't false-alarm
        end
    end)
end

-- M6: Connect and claim session lock
local function v5_connect()
    -- p29: refresh from the LIVE DataModel + kick the async published-name
    -- resolve BEFORE building the body — the init-time capture is stale.
    plugin_state.place_id = v5_effective_place_id()
    v5_refresh_place_name()
    v5_resolve_published_name_async()
    v5_probe_injection_async()
    -- 2026-07-24: report which Roblox account STUDIO is signed in as, so the
    -- server can warn when it differs from the user's linked OAuth account
    -- (animations/meshes mint under the Studio account — wrong login = assets
    -- land on the wrong account).
    local studio_uid = 0
    pcall(function() studio_uid = game:GetService("StudioService"):GetUserId() end)
    local body = HttpService:JSONEncode({
        place_id         = plugin_state.place_id,
        place_name       = plugin_state.place_name,   -- 2026-05-30: real game name
        session_id       = plugin_state.session_id,
        plugin_version   = PLUGIN_VERSION,
        injection_status = plugin_state.injection_status,
        studio_user_id   = tostring(studio_uid or 0),
    })
    local ok, resp = pcall(function()
        return HttpService:RequestAsync({
            Url     = BASE_URL .. "/v5/connect",
            Method  = "POST",
            Headers = v5_headers(),
            Body    = body,
        })
    end)
    if not ok then
        warn("[Pipeline] connect error:", resp)
        ui_log("err", "Network error: " .. tostring(resp))
        return false
    end
    if resp.StatusCode == 404 then
        -- 404 = the key didn't match any Pisces account (server gate is
        -- global-open; the old dev-era allowlist message here made users
        -- think their key "belonged to" another account — it never did).
        print("[Pipeline] API key not recognized. Plugin will stay inactive.")
        ui_log("err", "API key not recognized (HTTP 404). Re-copy your key " ..
            "from " .. BASE_URL .. "/web (Copy Key button) and paste the " ..
            "whole thing with no spaces, then Connect again.")
        return false
    end
    if resp.StatusCode == 409 then
        local parsed = nil
        pcall(function() parsed = HttpService:JSONDecode(resp.Body) end)
        local age = parsed and tostring(parsed.current_session_age_s or "?") or "?"
        warn(
            "[Pipeline] Another Studio session is already connected (age=" .. age .. "s). " ..
            "Click 'Force Disconnect' in the Pipeline web tab to take over, then click Reconnect here."
        )
        ui_log("warn", "Another Studio session is connected (age=" .. age ..
            "s). Click Force Disconnect on the web, then Connect again.")
        return false
    end
    if resp.StatusCode ~= 200 then
        warn("[Pipeline] connect HTTP " .. tostring(resp.StatusCode) .. ": " .. tostring(resp.Body))
        ui_log("err", "Connect failed: HTTP " .. tostring(resp.StatusCode) ..
            " " .. tostring(resp.Body):sub(1, 120))
        return false
    end
    plugin_state.connected = true
    print("[Pipeline] connected. session_id=" .. plugin_state.session_id)
    ui_log("ok", "Connected (session " .. plugin_state.session_id:sub(1, 8) .. "…)")
    -- rev 01090b: refresh place_id from the LIVE DataModel at connect time.
    -- It was captured once at module init; if the user opened a different place
    -- in the same Studio session, the stale id would route snapshot writes (and
    -- the freshness watcher's incremental deletes) to the WRONG place bucket —
    -- a data-loss path. Re-reading it here, plus the live place-guard inside
    -- _post_incremental_sync, makes a reconnect after a place-switch correct.
    plugin_state.place_id = v5_effective_place_id()
    -- p23: codebase + instance-tree sync runs SYNCHRONOUSLY before connect
    -- returns. Previous p21/p22 used task.spawn which raced the user's first
    -- /chat_v5 — the model saw an empty world_state on the first turn until
    -- the user refreshed or did /clear. Sync is pcall-wrapped + retries
    -- internally; worst case it logs a warning, connect still returns ok.
    v5_sync_codebase(true)
    -- rev 01090b: arm the continuous script-freshness watcher off the
    -- just-synced baseline so the user's MANUAL Studio edits between requests
    -- get reindexed within ~0.3s (incremental delta), with zero per-request
    -- latency. Idempotent → safe to re-arm on every reconnect.
    pcall(v5_install_freshness_watchers)
    pcall(v5_install_tree_watchers)
    -- rev 01104 (P6): publishing an unsaved place flips game.PlaceId
    -- (0 → real id) with NO reconnect — the rev01090b live-pid guard then
    -- blocks every incremental sync until reconnect (stale cached id) and
    -- snapshot traffic routes to the wrong bucket. Watch the flip and
    -- re-baseline: refresh cached id, full-sync the new bucket, re-arm.
    if not plugin_state.placeid_watch_conn then
        local okC, conn = pcall(function()
            return game:GetPropertyChangedSignal("PlaceId"):Connect(function()
                local newPid = v5_effective_place_id()
                if newPid == plugin_state.place_id then return end
                plugin_state.place_id = newPid
                -- p29: a publish also settles the real name — re-resolve it.
                v5_refresh_place_name()
                v5_resolve_published_name_async()
                ui_log("info", "PlaceId changed -> full resync (" .. newPid .. ")")
                task.spawn(function()
                    pcall(function() v5_sync_codebase(true) end)
                    pcall(v5_install_freshness_watchers)
                    pcall(v5_install_tree_watchers)
                end)
            end)
        end)
        if okC then plugin_state.placeid_watch_conn = conn end
    end
    return true
end

-- M1 (Phase 2 parallel workers): Poll for up to POLL_BATCH queued work items.
-- Server may return a "cancelled" list alongside "work"; those call_ids are
-- added to _cancelled_call_ids so workers skip them immediately.
-- rev p24 (2026-05-27): v5_poll now returns (work_list, http_ok). The
-- second return value lets poll_worker distinguish "no work, server
-- happy" (status 200, empty work) from "HTTP failed" (pcall error or
-- non-200). Without this distinction, the worker counted every empty
-- 25s LISTEN return as a "failure" and could trigger reconnect storms.
local function v5_poll()
    local ok, resp = pcall(function()
        return HttpService:RequestAsync({
            Url     = BASE_URL .. "/v5/poll?batch=" .. tostring(POLL_BATCH),
            Method  = "GET",
            Headers = v5_headers(),
            -- Explicit 30s timeout matches server 25s LISTEN + overhead.
            Timeout = POLL_HTTP_TIMEOUT_S,
        })
    end)
    if not ok then return {}, false end
    if resp.StatusCode ~= 200 then return {}, false end
    local data = nil
    pcall(function() data = HttpService:JSONDecode(resp.Body) end)
    if type(data) ~= "table" then return {}, true end

    -- Register any cancelled call_ids so workers skip them. Value = arrival
    -- time so cache_prune can TTL entries that never get redelivered (leak fix).
    if type(data.cancelled) == "table" then
        local nowT = os.time()
        for _, cid in ipairs(data.cancelled) do
            _cancelled_call_ids[tostring(cid)] = nowT
        end
    end

    -- p48: the server flags `reindex = true` when it noticed our instance
    -- tree is stale (e.g. a tree read hit a sentinel older than its window).
    return (type(data.work) == "table" and data.work or {}), true,
        (data.reindex == true)
end

-- M3: ACK before execution
local function v5_ack(call_id)
    pcall(function()
        HttpService:RequestAsync({
            Url     = BASE_URL .. "/v5/ack",
            Method  = "POST",
            Headers = v5_headers(),
            Body    = HttpService:JSONEncode({ call_id = call_id }),
        })
    end)
end

-- M4: POST result with optional read-back fields
-- rev p20 (2026-05-25): retry on transient failures. Silent-pcall caused
-- "WTQ redeliver lease-expired" — when result POST failed (network blip,
-- 502/503 on server, etc.) the plugin moved on but the server never got
-- the ack. The lease expired 45s later → the row was redelivered →
-- plugin (or another instance) re-ran the tool → eventually one succeeded.
-- User-visible symptom: 45-90s extra wait per tool. Now retries up to
-- 3 times with backoff so transient failures get recovered fast.
local function v5_post_result(call_id, success, result, name, source_after, value_after)
    local body = {
        call_id  = call_id,
        success  = success,
        result   = result or {},
        name     = name,
    }
    if source_after ~= nil then body.source_after = source_after end
    if value_after  ~= nil then body.value_after  = value_after  end
    -- rev 01104 (P4a): JSONEncode THROWS on non-encodable values (NaN/inf,
    -- mixed-key tables, Instances leaked into a result). Unprotected, the
    -- result never posted and the server waited out the full tool deadline
    -- ("plugin stopped responding"). Fall back to a minimal error envelope
    -- so the call resolves as a tool error instead of a hang.
    local okEnc, encoded = pcall(function() return HttpService:JSONEncode(body) end)
    if not okEnc then
        warn("[PISCES_V5] result JSONEncode failed call_id=" .. tostring(call_id))
        local okEnc2, fallback = pcall(function()
            return HttpService:JSONEncode({
                call_id = call_id,
                success = false,
                result  = {
                    error      = "plugin could not serialize the tool result "
                        .. "(non-JSON value in output)",
                    error_code = "result_encode_failed",
                },
                name    = name,
            })
        end)
        if not okEnc2 then return end
        encoded = fallback
    end
    local attempts = 0
    local max_attempts = 3
    while attempts < max_attempts do
        attempts = attempts + 1
        local ok, resp = pcall(function()
            return HttpService:RequestAsync({
                Url     = BASE_URL .. "/v5/result",
                Method  = "POST",
                Headers = v5_headers(),
                Body    = encoded,
            })
        end)
        if ok and resp and resp.StatusCode and resp.StatusCode >= 200
                and resp.StatusCode < 500 then
            -- 2xx/3xx/4xx all count as "server got it" — only 5xx and
            -- network errors retry. 4xx is a permanent bad-request, not
            -- worth re-sending.
            return
        end
        if attempts < max_attempts then
            task.wait(0.5 * attempts)  -- 0.5s, 1.0s backoff
        end
    end
    -- All retries failed. Log so we can see it in plugin console.
    warn(string.format(
        "[PISCES_V5] result POST failed after %d attempts call_id=%s",
        max_attempts, tostring(call_id)
    ))
end

-- 2026-05-23: explicit Disconnect from the plugin side. Best-effort POST
-- to /v5/force_disconnect so the server clears its liveness row immediately
-- (vs waiting for the 15s window to age out).
local function v5_force_disconnect()
    pcall(function()
        HttpService:RequestAsync({
            Url     = BASE_URL .. "/v5/force_disconnect",
            Method  = "POST",
            Headers = v5_headers(),
            Body    = HttpService:JSONEncode({
                api_key  = plugin_state.api_key,
                place_id = plugin_state.place_id,
            }),
        })
    end)
end

-- 2026-05-26 p21: walk the DataModel for every LuaSourceContainer and POST
-- the (path, source) pairs to /sync_script_snapshots. Without this the
-- PluginScriptSnapshot table is empty for V5-only users and the model sees
-- an "empty codebase" even when the user has dozens of scripts. V5 had been
-- relying on V4-plugin sync, which V5-only users don't run.
local function v5_collect_all_scripts()
    local scripts = {}
    -- rev 01085: track whether any RESOLVED container failed to enumerate. A
    -- partial walk must NOT claim full_sync, or the server's reconcile would
    -- delete real scripts that are merely missing from this incomplete walk.
    local had_failure = false
    local containers = {
        "ServerScriptService", "ServerStorage", "ReplicatedStorage",
        "ReplicatedFirst",     "StarterPlayer",  "StarterPack",
        "StarterGui",          "Workspace",      "Lighting",
        "Chat",                "Teams",          "SoundService",
    }
    for _, svc_name in ipairs(containers) do
        local ok_svc, svc = pcall(function() return game:GetService(svc_name) end)
        if ok_svc and svc then
            local ok_desc, descendants = pcall(function() return svc:GetDescendants() end)
            if ok_desc and descendants then
                for _, inst in ipairs(descendants) do
                    -- p29 audit: skip plugin-internal scaffolds (__PiscesV5
                    -- playtest scripts / permission probe) — a connect-time
                    -- walk racing a playtest or probe was indexing them as
                    -- USER code (_flush_freshness already filters these).
                    if inst:IsA("LuaSourceContainer")
                        and not (type(inst.Name) == "string"
                                 and string.sub(inst.Name, 1, 9) == "__PiscesV") then
                        local ok_src, src = pcall(function() return inst.Source end)
                        if ok_src and type(src) == "string" then
                            table.insert(scripts, {
                                script_path = inst:GetFullName(),
                                source_text = src,
                            })
                        end
                    end
                end
            else
                -- resolved the service but couldn't list its descendants →
                -- this walk is incomplete; withhold full_sync downstream.
                had_failure = true
            end
        end
    end
    return scripts, had_failure
end

-- p22: walk every Instance (Folder, Part, Model, GUI, etc) so world_state can
-- show the FULL tree, not just scripts. Sentinel-row trick: stash the JSON
-- tree as the `source_text` of a row with script_path = "__pisces_instance_tree__".
-- Server filters this sentinel out of all script-listing paths.
local INSTANCE_TREE_SENTINEL = "__pisces_instance_tree__"
-- 2026-05-30: effectively NO cap (user: "no cap on snapshot"). 1e6 is ~100× the
-- largest real game's instance count — it only bounds a runaway/pathological
-- DataModel from OOMing the plugin, never a normal place.
local INSTANCE_TREE_MAX_NODES = 1000000
-- 2026-05-30: walk SCRIPT/CODE-bearing services FIRST so a large Workspace can
-- never exhaust the node budget before ServerScriptService/StarterPlayer are
-- reached (that bug made the AI's tree omit those services). Workspace +
-- Lighting (the biggest, mostly non-code) come LAST.
local INSTANCE_TREE_CONTAINERS = {
    "ServerScriptService", "StarterPlayer", "ReplicatedStorage", "ServerStorage",
    "StarterPack", "StarterGui", "ReplicatedFirst", "Chat", "Teams",
    "SoundService", "MaterialService", "Workspace", "Lighting",
}
local function v5_collect_instance_tree()
    local nodes = {}
    local count = 0
    for _, svc_name in ipairs(INSTANCE_TREE_CONTAINERS) do
        if count >= INSTANCE_TREE_MAX_NODES then break end
        local ok_svc, svc = pcall(function() return game:GetService(svc_name) end)
        if ok_svc and svc then
            -- Emit the service node itself so the tree has a root.
            count = count + 1
            table.insert(nodes, {
                path = svc:GetFullName(),
                class_name = svc.ClassName,
            })
            local ok_desc, descendants = pcall(function() return svc:GetDescendants() end)
            if ok_desc and descendants then
                for _, inst in ipairs(descendants) do
                    if count >= INSTANCE_TREE_MAX_NODES then break end
                    -- Skip Terrain mesh chunks and ParticleEmitter spam etc.
                    -- if needed in a future iter, but include everything for now.
                    local ok_path, full = pcall(function() return inst:GetFullName() end)
                    if ok_path and full then
                        count = count + 1
                        table.insert(nodes, {
                            path = full,
                            class_name = inst.ClassName,
                        })
                    end
                end
            end
        end
    end
    return nodes
end

local _last_sync_at = 0
v5_sync_codebase = function(force)
    -- Throttle: don't sync more than once every 5s under normal reconnect
    -- churn (Force Disconnect → Connect can fire in quick succession).
    local now = os.time()
    if not force and (now - _last_sync_at) < 5 then return end
    _last_sync_at = now

    local scripts, walk_had_failure = v5_collect_all_scripts()
    -- p22: ALSO collect the full instance tree (folders/parts/models/etc).
    -- Encode as a sentinel "script" row so the existing sync endpoint can
    -- carry it without a schema change. Server filters this row out of
    -- script-listing paths and renders it as the tree in world_state.
    local instance_nodes = v5_collect_instance_tree()
    if #instance_nodes > 0 then
        local tree_json = HttpService:JSONEncode({
            count = #instance_nodes,
            nodes = instance_nodes,
        })
        table.insert(scripts, {
            script_path = INSTANCE_TREE_SENTINEL,
            source_text = tree_json,
        })
    end
    if #scripts == 0 then
        ui_log("info", "Codebase sync: no scripts or instances found")
        return
    end
    local headers = v5_headers()
    headers["X-Pisces-Key"] = plugin_state.api_key
    local body = HttpService:JSONEncode({
        place_id         = plugin_state.place_id,
        index_generation = now,
        index_digest     = tostring(#scripts) .. "-" .. plugin_state.session_id,
        idempotency_key  = HttpService:GenerateGUID(false),
        -- rev 01085: this is the COMPLETE DataModel walk (v5_collect_all_scripts
        -- enumerates every LuaSourceContainer). The flag lets the server
        -- reconcile away stale snapshot rows from prior sessions that share this
        -- place_id (unsaved places all report PlaceId 0). Only a full walk sets
        -- this — never an incremental/partial push — so the server can safely
        -- delete rows absent from `scripts`. Withheld (false) when the walk was
        -- partial (a container failed to enumerate) so the server does NOT
        -- reconcile-delete real scripts merely missing from an incomplete walk.
        full_sync        = (not walk_had_failure),
        scripts          = scripts,
    })
    local ok, resp = pcall(function()
        return HttpService:RequestAsync({
            Url     = BASE_URL .. "/sync_script_snapshots",
            Method  = "POST",
            Headers = headers,
            Body    = body,
        })
    end)
    if not ok then
        warn("[Pipeline] codebase sync error:", resp)
        ui_log("warn", "Codebase sync failed: " .. tostring(resp):sub(1, 80))
        return
    end
    if resp.StatusCode ~= 200 then
        warn("[Pipeline] codebase sync HTTP " .. tostring(resp.StatusCode))
        ui_log("warn", "Codebase sync HTTP " .. tostring(resp.StatusCode))
        return
    end
    print(string.format("[Pipeline] codebase sync ok (%d scripts, %d instances)",
        #scripts - (#instance_nodes > 0 and 1 or 0), #instance_nodes))
    ui_log("ok", string.format("Synced %d scripts + %d instances",
        #scripts - (#instance_nodes > 0 and 1 or 0), #instance_nodes))
end

-- ============================================================================
-- p48 (2026-07-30): INSTANCE-TREE FRESHNESS
-- ----------------------------------------------------------------------------
-- The sentinel instance tree used to refresh ONLY on connect/place-switch, so
-- objects the user added BY HAND after connecting (imported folders, parts,
-- sounds) were invisible to the server-side readers until reconnect — the AI
-- read a connect-time tree and confidently reported them absent ("there is no
-- keycap folder", 2026-07-30). Two additions close it:
--   1. a debounced DescendantAdded/Removing watcher on the tree containers
--      pushes a TREE-ONLY incremental sync (~3s after the burst settles);
--   2. the /v5/poll response can carry `reindex = true` (server noticed a
--      stale tree) → full v5_sync_codebase re-run, throttled.
-- Script churn is excluded here — the script freshness watcher owns it.
-- ============================================================================
local _treeDirty = false
local _treeFlushQueued = false
local _lastTreeSync = 0
local TREE_SYNC_DEBOUNCE_S = 3.0

local function v5_sync_instance_tree()
    _treeFlushQueued = false
    if not plugin_state.api_key or not plugin_state.connected then return end
    if not _treeDirty then return end
    if RunService:IsRunning() then
        -- play-session churn (character clones etc.) — retry after it ends
        _treeFlushQueued = true
        task.delay(5.0, v5_sync_instance_tree)
        return
    end
    -- rev 01090b data-loss guard, same as incremental script sync: never
    -- write under a stale place bucket after an unreconnected place switch.
    local ok_pid, livePid = pcall(v5_effective_place_id)
    if ok_pid and livePid ~= plugin_state.place_id then return end
    local now = os.time()
    if now - _lastTreeSync < 2 then
        _treeFlushQueued = true
        task.delay(TREE_SYNC_DEBOUNCE_S, v5_sync_instance_tree)
        return
    end
    _treeDirty = false
    _lastTreeSync = now
    local instance_nodes = v5_collect_instance_tree()
    if #instance_nodes == 0 then return end
    local headers = v5_headers()
    headers["X-Pisces-Key"] = plugin_state.api_key
    local body = HttpService:JSONEncode({
        place_id         = plugin_state.place_id,
        index_generation = now,
        idempotency_key  = HttpService:GenerateGUID(false),
        incremental      = true,  -- NOT full_sync → server never reconcile-deletes
        scripts          = { {
            script_path = INSTANCE_TREE_SENTINEL,
            source_text = HttpService:JSONEncode({
                count = #instance_nodes, nodes = instance_nodes }),
        } },
    })
    local okReq, resp = pcall(function()
        return HttpService:RequestAsync({
            Url     = BASE_URL .. "/sync_script_snapshots",
            Method  = "POST",
            Headers = headers,
            Body    = body,
        })
    end)
    if okReq and resp and resp.StatusCode == 200 then
        ui_log("info", string.format("Instance tree resynced (%d nodes)",
            #instance_nodes))
    else
        -- failed push: stay dirty so the next event (or reindex request)
        -- retries — never silently drop a tree change.
        _treeDirty = true
    end
end

local function _tree_mark_dirty(inst)
    -- scripts are the freshness watcher's job; a script's OWN add/remove
    -- still changes the tree, but the sentinel unions with live script rows
    -- server-side, so skipping them here avoids double-sync on code churn.
    local okc, isScript = pcall(function()
        return inst:IsA("LuaSourceContainer")
    end)
    if okc and isScript then return end
    _treeDirty = true
    if _treeFlushQueued then return end
    _treeFlushQueued = true
    task.delay(TREE_SYNC_DEBOUNCE_S, v5_sync_instance_tree)
end

local _tree_watch_conns = {}
v5_install_tree_watchers = function()
    if RunService:IsRunning() then return end  -- never in a play session
    for _, c in ipairs(_tree_watch_conns) do
        pcall(function() c:Disconnect() end)
    end
    _tree_watch_conns = {}
    for _, svc_name in ipairs(INSTANCE_TREE_CONTAINERS) do
        local ok_svc, svc = pcall(function() return game:GetService(svc_name) end)
        if ok_svc and svc then
            local okA, cA = pcall(function()
                return svc.DescendantAdded:Connect(_tree_mark_dirty)
            end)
            if okA then _tree_watch_conns[#_tree_watch_conns + 1] = cA end
            local okR, cR = pcall(function()
                return svc.DescendantRemoving:Connect(_tree_mark_dirty)
            end)
            if okR then _tree_watch_conns[#_tree_watch_conns + 1] = cR end
        end
    end
end

-- ============================================================================
-- rev 01090b (2026-06-03): CONTINUOUS SCRIPT FRESHNESS WATCHER
-- ----------------------------------------------------------------------------
-- User: "on each request, scan for changes and if scripts changed, reindex —
-- but make it blazing blazing fast." Until now v5_sync_codebase ran ONLY on
-- connect, so a user's MANUAL Studio edits between requests never reached the
-- server → the AI read stale code. Instead of a per-request BLOCKING scan
-- (adds latency to every send), we keep the index continuously fresh at
-- near-zero cost:
--   * EVENT-DRIVEN: hook every LuaSourceContainer's Source-change signal plus
--     each code container's DescendantAdded/Removing. An edit pushes a tiny
--     INCREMENTAL delta (changed sources + removed paths) ~0.3s later
--     (debounced). No polling, no per-request latency — by the time any chat
--     request arrives the index is already current.
--   * SAFETY RECONCILE: a cheap signature walk every 10s catches the edges
--     events miss (in-place rename, reparent, a dropped signal). It is the
--     ONLY path that infers a "removed" set from ABSENCE, so it is STRICTLY
--     gated on a COMPLETE walk — a partial walk must never delete a real
--     script (the rev01085 phantom-delete data-loss class).
-- Every push is `incremental=true` (never `full_sync`), so the server upserts
-- the delta + deletes explicit removed_paths but NEVER reconcile-deletes absent
-- rows. Set FRESHNESS_WATCHER_ENABLED=false to disable entirely.
-- ============================================================================
local FRESHNESS_WATCHER_ENABLED = true
local FRESHNESS_DEBOUNCE_S      = 0.3
local FRESHNESS_RECONCILE_S     = 10
local FRESHNESS_CONTAINERS = {
    "ServerScriptService", "ServerStorage", "ReplicatedStorage",
    "ReplicatedFirst",     "StarterPlayer",  "StarterPack",
    "StarterGui",          "Workspace",      "Lighting",
    "Chat",                "Teams",          "SoundService",
}
local _scriptSig      = {}   -- [fullName] = signature string (last-seen source)
local _dirtyChanged   = {}   -- set: [Instance] = true  (source edited/added)
local _dirtyRemoved   = {}   -- set: [fullName]  = true  (script removed)
local _srcConns       = {}   -- [Instance] = Source-changed connection
local _containerConns = {}   -- array of DescendantAdded/Removing connections
local _flushQueued    = false

-- djb2 string hash, kept under 2^31 so the running value never exceeds the
-- 2^53 exact-integer range of a Lua double (no precision drift → stable).
local function _fresh_hash(s)
    local h = 5381
    for i = 1, #s do
        h = (h * 33 + string.byte(s, i)) % 2147483648
    end
    return h
end

-- Change signature: full hash for small scripts; length + head/tail hash for
-- big ones. An edit changes length and/or a sampled region for ~every real
-- edit; the rare middle-only same-length edit is still caught by the Source
-- EVENT — the signature only backstops events (rename/reparent/missed signal).
local function _fresh_sig(src)
    local n = #src
    if n <= 6000 then return n .. ":" .. _fresh_hash(src) end
    return n .. ":" .. _fresh_hash(string.sub(src, 1, 3000))
             .. ":" .. _fresh_hash(string.sub(src, n - 2999, n))
end

-- Plugin scaffold scripts (__PiscesV5PlaytestServer / __PiscesV5TestHarness /
-- __PiscesV5PlaytestAutoStop …) are injected+destroyed during playtests and
-- must NEVER be indexed as the user's code.
local function _is_internal_script(name)
    return type(name) == "string" and string.sub(name, 1, 9) == "__PiscesV"
end

-- Returns true ONLY on a confirmed HTTP 200. Callers MUST defer their
-- _scriptSig commits until this returns true — otherwise a failed push (e.g.
-- the server's per-key "request in progress" 409, or a transient network
-- error) would advance the signature and the lost change would never be
-- re-detected. On false, the caller leaves _scriptSig untouched and the 10s
-- reconcile re-detects + re-pushes (self-healing).
local function _post_incremental_sync(scripts, removed)
    if not plugin_state.api_key or not plugin_state.connected then return false end
    -- rev 01090b DATA-LOSS GUARD: never write/delete under a stale place_id. If
    -- the user switched to a different place in this Studio session without
    -- reconnecting, plugin_state.place_id still points at the OLD place while
    -- the walk now sees the NEW place's scripts — sending removed_paths here
    -- would delete the OLD (real, saved) place's scripts from its bucket. Skip
    -- until a reconnect refreshes place_id; the reconcile retries (sigs are
    -- only committed on a confirmed 200, so nothing is lost meanwhile).
    local ok_pid, livePid = pcall(v5_effective_place_id)
    if ok_pid and livePid ~= plugin_state.place_id then return false end
    if (#scripts == 0) and (#removed == 0) then return true end  -- no-op: blazing fast
    local headers = v5_headers()
    headers["X-Pisces-Key"] = plugin_state.api_key
    local body = HttpService:JSONEncode({
        place_id         = plugin_state.place_id,
        index_generation = os.time(),
        idempotency_key  = HttpService:GenerateGUID(false),
        incremental      = true,   -- NOT full_sync → server never reconcile-deletes
        scripts          = scripts,
        removed_paths    = removed,
    })
    local ok, resp = pcall(function()
        return HttpService:RequestAsync({
            Url     = BASE_URL .. "/sync_script_snapshots",
            Method  = "POST",
            Headers = headers,
            Body    = body,
        })
    end)
    if ok and resp and resp.StatusCode == 200 then
        ui_log("info", string.format("Reindexed %d changed, %d removed",
            #scripts, #removed))
        return true
    end
    return false
end

local function _flush_freshness()
    _flushQueued = false
    if not FRESHNESS_WATCHER_ENABLED then return end
    local scripts, removed = {}, {}
    local sigCommits = {}    -- {path=..., sig=...} applied ONLY on push success
    local removedPaths = {}  -- cleared from _scriptSig ONLY on push success
    for inst in pairs(_dirtyChanged) do
        _dirtyChanged[inst] = nil   -- consume the event (reconcile re-detects on fail)
        local oka, alive = pcall(function() return inst.Parent ~= nil end)
        local okp, path  = pcall(function() return inst:GetFullName() end)
        if oka and alive and okp and not _is_internal_script(inst.Name) then
            local oks, src = pcall(function() return inst.Source end)
            if oks and type(src) == "string" then
                scripts[#scripts + 1] = { script_path = path, source_text = src }
                sigCommits[#sigCommits + 1] = { path = path, sig = _fresh_sig(src) }
            end
        end
    end
    for path in pairs(_dirtyRemoved) do
        _dirtyRemoved[path] = nil
        removed[#removed + 1] = path
        removedPaths[#removedPaths + 1] = path
    end
    if (#scripts == 0) and (#removed == 0) then return end
    if _post_incremental_sync(scripts, removed) then
        for _, c in ipairs(sigCommits) do _scriptSig[c.path] = c.sig end
        for _, p in ipairs(removedPaths) do _scriptSig[p] = nil end
    end
    -- on failure: _scriptSig is untouched, so the safety reconcile re-detects.
end

local function _schedule_flush()
    if _flushQueued then return end
    _flushQueued = true
    task.delay(FRESHNESS_DEBOUNCE_S, _flush_freshness)
end

local function _watch_script(inst)
    if _srcConns[inst] then return end
    if _is_internal_script(inst.Name) then return end
    local ok, conn = pcall(function()
        return inst:GetPropertyChangedSignal("Source"):Connect(function()
            _dirtyChanged[inst] = true
            _schedule_flush()
        end)
    end)
    if ok and conn then _srcConns[inst] = conn end
end

local function _unwatch_script(inst)
    local c = _srcConns[inst]
    if c then pcall(function() c:Disconnect() end); _srcConns[inst] = nil end
end

-- rev 01090b: tear EVERYTHING down — disconnect all Source + container watchers
-- and drop all pending state. Called on a clean re-arm and on user-disconnect so
-- stale connections don't keep firing (and so a re-arm can't inherit a previous
-- place's _scriptSig — the place-switch data-loss path the review flagged).
local function _cleanup_freshness_watchers()
    for _, c in pairs(_srcConns) do pcall(function() c:Disconnect() end) end
    for _, c in ipairs(_containerConns) do pcall(function() c:Disconnect() end) end
    _srcConns       = {}
    _containerConns = {}
    _scriptSig      = {}
    _dirtyChanged   = {}
    _dirtyRemoved   = {}
    _flushQueued    = false
end

local function _walk_script_instances()
    local out = {}
    local had_failure = false
    for _, svc_name in ipairs(FRESHNESS_CONTAINERS) do
        local ok_svc, svc = pcall(function() return game:GetService(svc_name) end)
        if ok_svc and svc then
            local ok_desc, desc = pcall(function() return svc:GetDescendants() end)
            if ok_desc and desc then
                for _, inst in ipairs(desc) do
                    if inst:IsA("LuaSourceContainer") then out[#out + 1] = inst end
                end
            else
                had_failure = true   -- partial walk → reconcile must NOT delete
            end
        end
    end
    return out, had_failure
end

v5_install_freshness_watchers = function()
    if not FRESHNESS_WATCHER_ENABLED then return end
    -- clean slate: a re-arm (reconnect / place-switch) must NOT inherit the
    -- previous baseline's _scriptSig or leak old connections (review amendments).
    _cleanup_freshness_watchers()
    -- baseline signatures + per-script Source watchers
    local insts = _walk_script_instances()
    for _, inst in ipairs(insts) do
        if not _is_internal_script(inst.Name) then
            local okp, path = pcall(function() return inst:GetFullName() end)
            local oks, src  = pcall(function() return inst.Source end)
            if okp and oks and type(src) == "string" then
                _scriptSig[path] = _fresh_sig(src)
            end
            _watch_script(inst)
        end
    end
    -- (re)install container-level add/remove watchers (idempotent on reconnect)
    for _, c in ipairs(_containerConns) do pcall(function() c:Disconnect() end) end
    _containerConns = {}
    for _, svc_name in ipairs(FRESHNESS_CONTAINERS) do
        local ok_svc, svc = pcall(function() return game:GetService(svc_name) end)
        if ok_svc and svc then
            local ca = svc.DescendantAdded:Connect(function(inst)
                if inst:IsA("LuaSourceContainer") and not _is_internal_script(inst.Name) then
                    _watch_script(inst)
                    _dirtyChanged[inst] = true
                    _schedule_flush()
                end
            end)
            local cr = svc.DescendantRemoving:Connect(function(inst)
                if inst:IsA("LuaSourceContainer") and not _is_internal_script(inst.Name) then
                    local okp, path = pcall(function() return inst:GetFullName() end)
                    if okp and path then
                        _dirtyChanged[inst] = nil
                        _unwatch_script(inst)
                        _dirtyRemoved[path] = true
                        _schedule_flush()
                    end
                end
            end)
            _containerConns[#_containerConns + 1] = ca
            _containerConns[#_containerConns + 1] = cr
        end
    end
    print("[Pipeline] freshness watcher armed (" .. tostring(#insts) .. " scripts)")
end

-- Safety reconcile: authoritative signature diff. It is the ONLY place that
-- derives a removed-set from ABSENCE, so the removed-set is computed ONLY on a
-- COMPLETE walk (had_failure == false) — never delete a script merely missing
-- from a partial walk (rev01085).
-- 2026-07-05 (p31): catch an unsaved→unsaved place switch that happens WITHOUT
-- a reconnect. game.PlaceId stays 0 across such a switch, so the PlaceId watcher
-- never fires — but v5_effective_place_id() changes (the new DataModel's
-- ServerStorage has no nonce → a fresh one is minted). When the effective id
-- drifts from the cached one, re-point plugin_state at the new bucket, drop the
-- stale _scriptSig baseline (v5_install_freshness_watchers → _cleanup resets it)
-- and full-sync the new place. Returns true when it kicked a rebaseline so the
-- caller can bail out of the current (now stale-bucket) pass.
local function v5_maybe_rebaseline_place()
    local eff = v5_effective_place_id()
    if eff == plugin_state.place_id then return false end
    ui_log("info", "Place changed -> rebaselining index (" .. eff .. ")")
    plugin_state.place_id = eff
    v5_refresh_place_name()
    v5_resolve_published_name_async()
    task.spawn(function()
        pcall(function() v5_sync_codebase(true) end)
        pcall(v5_install_freshness_watchers)
        pcall(v5_install_tree_watchers)
    end)
    return true
end

v5_freshness_reconcile = function()
    if not FRESHNESS_WATCHER_ENABLED or not plugin_state.connected then return end
    -- p31: a place-switch with no reconnect must re-point the bucket first.
    if v5_maybe_rebaseline_place() then return end
    local insts, had_failure = _walk_script_instances()
    local seen, changed = {}, {}
    local sigCommits = {}   -- deferred until the push confirms (see _post above)
    for _, inst in ipairs(insts) do
        if not _is_internal_script(inst.Name) then
            local okp, path = pcall(function() return inst:GetFullName() end)
            if okp and path then
                seen[path] = true
                if not _srcConns[inst] then _watch_script(inst) end
                local oks, src = pcall(function() return inst.Source end)
                if oks and type(src) == "string" then
                    local sig = _fresh_sig(src)
                    if _scriptSig[path] ~= sig then
                        changed[#changed + 1] = { script_path = path, source_text = src }
                        sigCommits[#sigCommits + 1] = { path = path, sig = sig }
                    end
                end
            end
        end
    end
    local removed = {}
    if not had_failure then
        for path in pairs(_scriptSig) do
            if not seen[path] then removed[#removed + 1] = path end
        end
    end
    if (#changed == 0) and (#removed == 0) then return end
    if _post_incremental_sync(changed, removed) then
        for _, c in ipairs(sigCommits) do _scriptSig[c.path] = c.sig end
        for _, p in ipairs(removed) do _scriptSig[p] = nil end
    end
    -- on failure: _scriptSig untouched → next reconcile re-detects + retries.
end

-- M7: Heartbeat. Returns true if the server reports pending work waiting.
-- The plugin uses that signal to wake out of idle-mode and resume long-polls.
-- rev p24 (2026-05-27): only stamp last_heartbeat_at on HTTP success.
-- Previously the timestamp was set unconditionally, masking persistent
-- HTTP failures (network down) — the loop thought heartbeat succeeded
-- and never escalated to reconnect.
local function v5_heartbeat()
    local has_work = false
    local http_ok = false
    pcall(function()
        local resp = HttpService:RequestAsync({
            Url     = BASE_URL .. "/v5/heartbeat",
            Method  = "POST",
            Headers = v5_headers(),
            Body    = HttpService:JSONEncode({
                place_id   = plugin_state.place_id,
                session_id = plugin_state.session_id,
                -- p29: carry the (possibly late-resolved) real place name so
                -- the website pill updates without a reconnect.
                place_name = plugin_state.place_name,
                -- p29: injection-permission probe result — resolves AFTER
                -- connect when Studio pops the modal, so heartbeats carry it.
                injection_status = plugin_state.injection_status,
            }),
        })
        if resp and resp.StatusCode == 200 then
            http_ok = true
            if resp.Body then
                local data = nil
                pcall(function() data = HttpService:JSONDecode(resp.Body) end)
                if type(data) == "table" and data.has_work then
                    has_work = true
                end
            end
        end
    end)
    if http_ok then
        plugin_state.last_heartbeat_at = os.time()
    end
    return has_work, http_ok
end

--------------------------------------------------------------------------------
-- TOOL IMPLEMENTATIONS  (ported from V4 pisces_web_plugin.lua:724-2224)
-- Each tool returns: success (bool), result (table), source_after (str|nil),
--                    value_after (any|nil)
-- source_after / value_after power M4 server-side read-back verification.
--------------------------------------------------------------------------------

-- create_script — V4 ref: pisces_web_plugin.lua:832-896
-- p57 Tier-0 syntax gate, rule-safe (2026-11-05). Creator Store rules ban
-- compiling code at runtime, so this gate no longer compiles anything. It
-- scans the source once and checks its STRUCTURE: every string, long string,
-- comment and interpolated string is closed; every ( [ { has its partner; every
-- function / if / do / repeat has its end / until, in the right order. That is
-- the class of error model-written scripts actually ship (a missing `end`, an
-- unclosed paren or string), and it reports the exact line like the old gate.
-- It cannot see expression-level mistakes (`local = 5`, a bad operator); those
-- still surface when the script runs. Luau if-expressions (`x = if a then b
-- else c`) have no `end` and are told apart by what comes before the `if`.
-- When a case is ambiguous the gate passes the script (never blocks valid code).
local function checkLuauSyntax(source, label)
    if type(source) ~= "string" or source == "" then return nil end
    label = label or "script"
    local n = #source
    local i, line = 1, 1
    local stack = {}             -- { kind = "function"|"if"|"do"|"repeat"|"("|"["|"{", line = n }
    local prev = nil             -- previous significant token
    local ambiguous = false      -- an expression-if nested where a statement-if could also stand
    local CLOSERS = { [")"] = "(", ["]"] = "[", ["}"] = "{" }
    -- tokens after which an `if` starts an EXPRESSION (Luau if-then-else value)
    local EXPR_BEFORE = {
        ["="] = true, ["("] = true, [","] = true, ["{"] = true, ["["] = true,
        ["return"] = true, ["and"] = true, ["or"] = true, ["not"] = true,
        ["+"] = true, ["-"] = true, ["*"] = true, ["/"] = true, ["//"] = true,
        ["%"] = true, ["^"] = true, [".."] = true, ["=="] = true, ["~="] = true,
        ["<"] = true, [">"] = true, ["<="] = true, [">="] = true, ["#"] = true,
        ["+="] = true, ["-="] = true, ["*="] = true, ["/="] = true, ["//="] = true,
        ["%="] = true, ["^="] = true, ["..="] = true, ["in"] = true,
        ["then_expr"] = true, ["else_expr"] = true,
    }

    local function fail(msg, at)
        return "SYNTAX ERROR (nothing was written) - " .. label .. ":" .. tostring(at or line)
            .. ": " .. msg .. " | Fix the source and resend the full corrected script."
    end

    local function longBracketLevel(at)   -- at points to "[": returns level or nil
        local j = at + 1
        while j <= n and source:sub(j, j) == "=" do j = j + 1 end
        if source:sub(j, j) == "[" then return j - at - 1 end
        return nil
    end

    local function skipLong(at, level, what)   -- returns index after the closing ]=*], or nil + error
        local close = "]" .. string.rep("=", level) .. "]"
        local startLine = line
        local e = source:find(close, at, true)
        if not e then return nil, fail("unfinished long " .. what .. " (opened at line " .. startLine .. ")", startLine) end
        local _, nl = source:sub(at, e):gsub("\n", "")
        line = line + nl
        return e + #close
    end

    local function push(kind) stack[#stack + 1] = { kind = kind, line = line } end
    local function pop(want, word)
        local top = stack[#stack]
        if not top then return fail("'" .. word .. "' has nothing to close") end
        local ok = false
        for _, k in ipairs(want) do if top.kind == k then ok = true end end
        if not ok then
            local need = (top.kind == "(" and "')'") or (top.kind == "[" and "']'") or (top.kind == "{" and "'}'")
                or (top.kind == "repeat" and "'until'") or "'end'"
            return fail("expected " .. need .. " (to close '" .. top.kind .. "' at line " .. top.line .. ") near '" .. word .. "'")
        end
        stack[#stack] = nil
        return nil
    end

    while i <= n do
        local c = source:sub(i, i)
        if c == "\n" then
            line = line + 1; i = i + 1
        elseif c == " " or c == "\t" or c == "\r" or c == "\f" or c == "\v" then
            i = i + 1
        elseif c == "-" and source:sub(i + 1, i + 1) == "-" then
            local lvl = (source:sub(i + 2, i + 2) == "[") and longBracketLevel(i + 2) or nil
            if lvl then
                local nxt, err = skipLong(i + 2, lvl, "comment"); if not nxt then return err end
                i = nxt
            else
                local e = source:find("\n", i, true); i = e or (n + 1)
            end
        elseif c == "\"" or c == "'" then
            local j, startLine = i + 1, line
            while true do
                local d = source:sub(j, j)
                if d == "" or d == "\n" then return fail("unfinished string", startLine) end
                if d == "\\" then
                    if source:sub(j + 1, j + 1) == "\n" then line = line + 1 end
                    if source:sub(j + 1, j + 1) == "z" then   -- \z skips following whitespace incl. newlines
                        j = j + 2
                        while source:sub(j, j):match("%s") do if source:sub(j, j) == "\n" then line = line + 1 end j = j + 1 end
                    else
                        j = j + 2
                    end
                elseif d == c then break
                else j = j + 1 end
            end
            i = j + 1; prev = "string"
        elseif c == "`" then   -- interpolated string: `text {expr} text`
            local j, startLine, depth = i + 1, line, 0
            while true do
                local d = source:sub(j, j)
                if d == "" then return fail("unfinished interpolated string", startLine) end
                if d == "\n" then line = line + 1 end
                if depth == 0 then
                    if d == "\\" then j = j + 1
                    elseif d == "{" then depth = 1
                    elseif d == "`" then break end
                else
                    if d == "{" then depth = depth + 1
                    elseif d == "}" then depth = depth - 1
                    elseif d == "\"" or d == "'" then   -- a plain string inside the braces
                        local e = j + 1
                        while e <= n and source:sub(e, e) ~= d and source:sub(e, e) ~= "\n" do
                            if source:sub(e, e) == "\\" then e = e + 1 end
                            e = e + 1
                        end
                        j = e
                    elseif d == "`" then ambiguous = true end   -- nested template: too deep to follow, pass
                end
                j = j + 1
            end
            i = j + 1; prev = "string"
        elseif c == "[" and longBracketLevel(i) then
            local nxt, err = skipLong(i, longBracketLevel(i), "string"); if not nxt then return err end
            i = nxt; prev = "string"
        elseif c:match("[%a_]") then
            local e = i
            while e + 1 <= n and source:sub(e + 1, e + 1):match("[%w_]") do e = e + 1 end
            local word = source:sub(i, e)
            local afterDot = (prev == "." or prev == ":")   -- t.end / obj:do are not keywords in Luau field position? they are invalid, but never block on them
            if not afterDot then
                if word == "function" or word == "do" or word == "repeat" then
                    push(word)
                elseif word == "if" then
                    -- after a value-taking token it is an if-EXPRESSION: no `end`, it closes at its `else`
                    push((prev ~= nil and EXPR_BEFORE[prev]) and "ifexpr" or "if")
                elseif word == "then" and stack[#stack] and stack[#stack].kind == "ifexpr" then
                    word = "then_expr"   -- the branch value that follows is an expression too
                elseif word == "else" and stack[#stack] and stack[#stack].kind == "ifexpr" then
                    stack[#stack] = nil; word = "else_expr"
                elseif word == "end" then
                    local err = pop({ "function", "if", "do" }, "end"); if err then if ambiguous then return nil end return err end
                elseif word == "until" then
                    local err = pop({ "repeat" }, "until"); if err then if ambiguous then return nil end return err end
                end
            end
            prev = word; i = e + 1
        elseif c:match("%d") or (c == "." and source:sub(i + 1, i + 1):match("%d")) then
            local e = i
            while e + 1 <= n do
                local d = source:sub(e + 1, e + 1)
                if d:match("[%w_%.]") then e = e + 1
                elseif (d == "+" or d == "-") and source:sub(e, e):match("[eE]") and not source:sub(i, i + 1):match("0[xX]") then e = e + 1
                else break end
            end
            prev = "number"; i = e + 1
        else
            local three, two = source:sub(i, i + 2), source:sub(i, i + 1)
            local tok
            if three == "..." or three == "..=" or three == "//=" then tok = three
            elseif two == "==" or two == "~=" or two == "<=" or two == ">=" or two == ".." or two == "::" or two == "->"
                or two == "+=" or two == "-=" or two == "*=" or two == "/=" or two == "%=" or two == "^=" or two == "//" then tok = two
            else tok = c end
            if tok == "(" or tok == "[" or tok == "{" then
                push(tok)
            elseif CLOSERS[tok] then
                local err = pop({ CLOSERS[tok] }, tok); if err then if ambiguous then return nil end return err end
            end
            prev = tok; i = i + #tok
        end
    end
    if #stack > 0 and not ambiguous then
        local top = stack[#stack]
        local need = (top.kind == "(" and "')'") or (top.kind == "[" and "']'") or (top.kind == "{" and "'}'")
            or (top.kind == "repeat" and "'until'") or "'end'"
        return fail("expected " .. need .. " (to close '" .. top.kind .. "' at line " .. top.line .. ") near <eof>", line)
    end
    return nil
end

local function run_create_script(input)
    local scriptName = tostring(input.name or input.script_name or "")
    local parentPath = tostring(input.parent or input.location or "")
    local scriptType = tostring(input.script_type or input.class_name or input.className or "Script")
    local source     = tostring(input.source or input.code or "")

    -- rev 01080 (Fix C): HONOR `path`/`target`. Previously this function read
    -- only name/parent and defaulted to "NewScript"/"ServerScriptService",
    -- ignoring the documented `create_script(path, source)` form — so a
    -- path-only call mislanded at ServerScriptService.NewScript (the jetpack
    -- JetpackClient bug). Derive name+parent from the dotted path; the harness
    -- already does this too (V5_CREATE_SCRIPT_PATH_SPLIT) so this is a backstop.
    if scriptName == "" or parentPath == "" then
        local explicit = tostring(input.path or input.target or input.script_path or "")
        if explicit ~= "" then
            local segs = {}
            for seg in explicit:gmatch("[^%./]+") do table.insert(segs, seg) end
            if #segs > 0 then
                local nameGiven = (scriptName ~= "")
                if scriptName == "" then scriptName = segs[#segs] end
                if parentPath == "" then
                    -- rev 01081 FIX: when a name was given SEPARATELY, the path
                    -- is the PARENT container — use it WHOLE. Only strip the
                    -- trailing leaf when we DERIVED the name from the path, or
                    -- the path redundantly ends with the given name. (rev 01080
                    -- always stripped the last segment → scripts landed one
                    -- level too high, e.g. StarterPack.FlyingTool + name became
                    -- parent StarterPack.)
                    local stripLeaf = (not nameGiven)
                        or (segs[#segs]:lower() == scriptName:lower())
                    if stripLeaf then table.remove(segs) end
                    if #segs >= 1 then parentPath = table.concat(segs, ".") end
                end
            end
        end
    end
    -- No usable name anywhere → do NOT fabricate a phantom "NewScript".
    if scriptName == "" then
        return false, { error = "create_script: no name or path provided", error_code = "missing_target" }, nil, nil
    end
    -- A bare name with no parent still goes to ServerScriptService (sane default).
    if parentPath == "" then parentPath = "ServerScriptService" end

    local parent = findOrCreateParent(parentPath)
    if not parent then
        return false, { error = "Parent not found: " .. parentPath, error_code = "parent_not_found" }, nil, nil
    end

    local synErr = checkLuauSyntax(source, scriptName)
    if synErr then
        return false, { error = synErr, error_code = "syntax_error" }, nil, nil
    end

    -- rev 01104 (P11): track whether the class was EXPLICITLY requested. A bare
    -- create_script(name, source) defaults to "Script" — we must NOT use that
    -- default to "fix" an existing LocalScript/ModuleScript (that would be a
    -- silent downgrade). Only a class the model actually asked for is honored.
    local classExplicit = (input.script_type ~= nil or input.class_name ~= nil
        or input.className ~= nil)
    local className = "Script"
    local lower = scriptType:lower()
    if lower:find("local") then className = "LocalScript"
    elseif lower:find("module") then className = "ModuleScript" end

    -- Auto-rewrite if script already exists (matches V4 behaviour)
    local existing = parent:FindFirstChild(scriptName)

    -- rev 01104 (P11): WRONG-CLASS recreate. If the existing script is a
    -- different class than what was explicitly requested (e.g. a Script where
    -- the model now wants a LocalScript so it runs on the client), rewriting
    -- the source alone leaves it executing in the wrong context — a silent
    -- behavioral bug. Recreate as the right class, carrying over children and
    -- (if no new source given) the old source.
    if existing and existing:IsA("LuaSourceContainer")
        and classExplicit and existing.ClassName ~= className then
        ChangeHistoryService:SetWaypoint("Pre-Pipeline Reclass: " .. scriptName)
        local okN, newScript = pcall(function() return Instance.new(className) end)
        if okN and newScript then
            newScript.Name = scriptName
            newScript.Source = (source ~= "") and source or existing.Source
            local _moved = 0
            for _, child in ipairs(existing:GetChildren()) do
                if pcall(function() child.Parent = newScript end) then
                    _moved = _moved + 1
                end
            end
            newScript.Parent = parent
            local _oldClass = existing.ClassName
            pcall(function() existing:Destroy() end)
            ChangeHistoryService:SetWaypoint("Pipeline Reclass: " .. scriptName)
            warn(string.format("[Pipeline] reclassed '%s' %s -> %s (moved %d)",
                scriptName, _oldClass, className, _moved))
            return true, {
                path = newScript:GetFullName(), class_name = className,
                converted_to = "reclass", reclassed_from = _oldClass,
                moved_children = _moved,
            }, newScript.Source, nil
        end
    end

    if existing and existing:IsA("LuaSourceContainer") then
        if source ~= "" then
            ChangeHistoryService:SetWaypoint("Pre-Pipeline Rewrite: " .. scriptName)
            local rwOk, rwErr = pcall(function()
                if ScriptEditorService then
                    ScriptEditorService:UpdateSourceAsync(existing, function() return source end)
                else
                    existing.Source = source
                end
            end)
            ChangeHistoryService:SetWaypoint("Pipeline Rewrite: " .. scriptName)
            if not rwOk then
                return false, { error = "Rewrite failed: " .. tostring(rwErr), error_code = "rewrite_failed" }, nil, nil
            end
            local readback = existing.Source
            return true, { path = existing:GetFullName(), class_name = existing.ClassName, converted_to = "rewrite" },
                   readback, nil
        end
        return false, { error = "Script already exists: " .. existing:GetFullName(), error_code = "already_exists" }, nil, nil
    end

    ChangeHistoryService:SetWaypoint("Pre-Pipeline Create: " .. scriptName)
    local newScript = Instance.new(className)
    newScript.Name   = scriptName
    newScript.Source = source
    newScript.Parent = parent
    ChangeHistoryService:SetWaypoint("Pipeline Create: " .. scriptName)

    local readback = newScript.Source
    return true, { path = newScript:GetFullName(), class_name = className, lines = countLines(source) },
           readback, nil
end

-- fix_script — full-source replacement  (V4 ref: pisces_web_plugin.lua:792-828)
-- Note: server translates edit_script → fix_script before plugin dispatch
-- (server_tools.py:3821). The plugin only ever sees fix_script for mutations.
local function run_fix_script(input)
    local targetPath = tostring(input.target or input.path or input.script or "")
    -- p51c: models commonly send the body as new_text (codex lane); without
    -- this alias the call failed "Empty source provided" despite a full body.
    local newSource  = tostring(input.new_source or input.source or input.code
        or input.new_text or "")

    if targetPath == "" then
        return false, { error = "Missing target path", error_code = "missing_target" }, nil, nil
    end

    local script, rerrCode, rerrMsg = resolveScriptTarget(targetPath)
    if not script then
        return false, {
            error      = rerrMsg or ("Script not found: " .. targetPath),
            error_code = rerrCode or "not_found",
        }, nil, nil
    end
    if newSource == "" then
        return false, { error = "Empty source provided", error_code = "empty_source" }, nil, nil
    end

    -- rev 01104 (P2a): the model sometimes sends start_line/end_line meaning
    -- "replace just these lines". The plugin used to IGNORE them and replace
    -- the WHOLE source with the fragment - silent data loss. Splice instead.
    local startLine = tonumber(input.start_line)
    local endLine   = tonumber(input.end_line)
    if startLine and startLine >= 1 then
        local liveSource = script.Source
        local lines = {}
        for line in (liveSource .. "\n"):gmatch("([^\n]*)\n") do
            table.insert(lines, line)
        end
        local lastLine = endLine or startLine
        if lastLine > #lines then lastLine = #lines end
        if startLine <= #lines and startLine <= lastLine then
            local out = {}
            for i = 1, startLine - 1 do table.insert(out, lines[i]) end
            table.insert(out, newSource)
            for i = lastLine + 1, #lines do table.insert(out, lines[i]) end
            newSource = table.concat(out, "\n")
        else
            -- self-review of P2a: an OUT-OF-RANGE start_line used to fall
            -- through to a WHOLE-script replace with the fragment (and the
            -- shrink guard below is skipped when startLine is set) - the
            -- exact data loss this fix exists to stop. Refuse instead.
            return false, {
                error = "start_line " .. startLine .. " is out of range: "
                    .. script.Name .. " has " .. #lines .. " lines"
                    .. (endLine and (" (end_line=" .. endLine .. ")") or "")
                    .. ". Re-read the script and re-issue with a valid range, "
                    .. "or use edit_script(old_text=..., new_text=...).",
                error_code  = "bad_line_range",
                total_lines = #lines,
            }, nil, nil
        end
    end

    -- rev 01104 (P2b): shrink guard - a "full replacement" that is a tiny
    -- fraction of a big existing script is almost always a FRAGMENT the model
    -- meant as an edit. Writing it would silently delete the rest.
    local oldSource = script.Source
    local oldLineCount = countLines(oldSource)
    local replaceAll = input.replace_all == true or input.replace_all == "true"
        or input.force == true
    if not replaceAll and not startLine
        and oldLineCount >= 80 and #newSource < (#oldSource * 0.25)
    then
        return false, {
            error = "Refused: new source is " .. #newSource .. " chars but "
                .. script.Name .. " currently has " .. #oldSource .. " chars / "
                .. oldLineCount .. " lines. fix_script REPLACES THE WHOLE "
                .. "SCRIPT - sending a fragment would delete the rest. Use "
                .. "edit_script(old_text=..., new_text=...) for a partial "
                .. "change, or resend the COMPLETE source (or pass "
                .. "replace_all=true if the big shrink is intended).",
            error_code = "suspected_truncation",
            old_lines  = oldLineCount,
            new_chars  = #newSource,
        }, nil, nil
    end

    -- p28: gate the FINAL source (after any start_line splice) so a bad splice
    -- or a syntactically-broken replacement never lands in the place.
    local synErr = checkLuauSyntax(newSource, targetPath)
    if synErr then
        return false, { error = synErr, error_code = "syntax_error" }, nil, nil
    end

    ChangeHistoryService:SetWaypoint("Pre-Pipeline: " .. script.Name)
    local ok, err = pcall(function()
        if ScriptEditorService then
            ScriptEditorService:UpdateSourceAsync(script, function() return newSource end)
        else
            script.Source = newSource
        end
    end)
    if not ok then
        return false, { error = "Failed to update: " .. tostring(err), error_code = "write_failed" }, nil, nil
    end
    ChangeHistoryService:SetWaypoint("Pipeline: " .. script.Name)

    local readback = script.Source
    return true, { path = script:GetFullName(), lines = countLines(newSource) }, readback, nil
end

-- p29 (2026-07-02): edit_script SELF-CORRECTION. Prod sessions show models
-- burning 5+ paid legs on consecutive "old_text not found" retries (the model
-- edits from a stale/reformatted snapshot; whitespace drifts). Two upgrades:
--   1. WHITESPACE-TOLERANT fallback — per-line trimmed matching; a unique run
--      of matching lines is spliced exactly (same syntax gate + write path).
--   2. HINT on real misses — the closest matching region WITH LINE NUMBERS,
--      so the model can immediately re-anchor or switch to fix_script ranges
--      instead of retrying blind.
local function _pv5_trim(s)
    return (tostring(s):gsub("^%s+", ""):gsub("%s+$", ""))
end

local function _pv5_lines(s)
    local t = {}
    for line in (tostring(s):gsub("\r\n", "\n") .. "\n"):gmatch("(.-)\n") do
        table.insert(t, line)
    end
    -- the trailing sentinel "\n" adds one empty line; drop it
    if #t > 0 and t[#t] == "" then table.remove(t, #t) end
    return t
end

-- Returns (startLine, runLen) for a UNIQUE trimmed-line match, else nil.
local function _pv5_fuzzy_line_match(srcLines, oldLines)
    local o = {}
    for _, l in ipairs(oldLines) do table.insert(o, _pv5_trim(l)) end
    while #o > 0 and o[1] == "" do table.remove(o, 1) end
    while #o > 0 and o[#o] == "" do table.remove(o, #o) end
    if #o == 0 then return nil end
    local first = nil
    for i = 1, #srcLines - #o + 1 do
        local okm = true
        for j = 1, #o do
            if _pv5_trim(srcLines[i + j - 1]) ~= o[j] then okm = false; break end
        end
        if okm then
            if first then return nil end  -- ambiguous → don't guess
            first = i
        end
    end
    if first then return first, #o end
    return nil
end

-- edit_script — old_text / new_text anchor replacement
-- (V4 dispatches edit_script as fix_script, but V5 spec supports it natively
--  to allow the plugin to catch the ACK + read-back contract regardless.)
local function run_edit_script(input)
    local targetPath = tostring(input.target or input.path or "")
    local oldText    = tostring(input.old_text or input.old or "")
    local newText    = tostring(input.new_text or input.new or "")

    if targetPath == "" or oldText == "" then
        return false, { error = "edit_script requires target and old_text", error_code = "missing_args" }, nil, nil
    end

    local script, rerrCode, rerrMsg = resolveScriptTarget(targetPath)
    if not script then
        return false, {
            error      = rerrMsg or ("Script not found: " .. targetPath),
            error_code = rerrCode or "not_found",
        }, nil, nil
    end

    local src = script.Source
    local idx = string.find(src, oldText, 1, true)
    local _fuzzy_note = nil
    if not idx then
        -- p29 upgrade 1: whitespace-tolerant per-line rematch. On a unique
        -- match, rebuild oldText as the EXACT current source of those lines so
        -- the normal splice/ambiguity/syntax path below runs unchanged.
        local srcLines = _pv5_lines(src)
        local startL, runLen = _pv5_fuzzy_line_match(srcLines, _pv5_lines(oldText))
        if startL then
            local exact = table.concat(srcLines, "\n", startL, startL + runLen - 1)
            local eIdx = string.find(src, exact, 1, true)
            if eIdx then
                oldText = exact
                idx = eIdx
                _fuzzy_note = "old_text matched via whitespace-tolerant line "
                    .. "matching at line " .. startL .. " (send exact current "
                    .. "source next time)"
            end
        end
        if not idx then
            -- p29 upgrade 2: locate the closest region and return it WITH
            -- line numbers so the next attempt anchors correctly in ONE leg.
            local anchor = nil
            for _, l in ipairs(_pv5_lines(oldText)) do
                local t = _pv5_trim(l)
                if #t >= 6 then anchor = t; break end
            end
            local hint = ""
            if anchor then
                for i, l in ipairs(srcLines) do
                    if l:find(anchor, 1, true) or
                       (#anchor > 20 and anchor:find(_pv5_trim(l), 1, true)
                        and #_pv5_trim(l) > 10) then
                        local lo = math.max(1, i - 3)
                        local hi = math.min(#srcLines, i + 8)
                        local seg = {}
                        for k = lo, hi do
                            table.insert(seg, k .. ": " .. srcLines[k])
                        end
                        hint = " CLOSEST MATCH around line " .. i .. ":\n"
                            .. table.concat(seg, "\n") .. "\n"
                        break
                    end
                end
            end
            return false, { error = "old_text not found in " .. targetPath
                .. " (script has " .. #srcLines .. " lines; exact AND "
                .. "whitespace-tolerant matching both failed)."
                .. (hint ~= "" and hint
                    or " No similar line found - your snapshot is stale; "
                    .. "re-read this script (read_scripts) before editing.")
                .. " Anchor old_text on the CURRENT source shown above, or "
                .. "use fix_script(target, start_line, end_line, source) "
                .. "with the line numbers.",
                error_code = "no_match" }, nil, nil
        end
    end
    -- Ambiguity guard: if old_text appears more than once, reject
    local second = string.find(src, oldText, idx + 1, true)
    if second then
        return false, {
            error      = "old_text is ambiguous (found at multiple positions). Lengthen it to be unique.",
            error_code = "edit_script_ambiguous",
        }, nil, nil
    end

    local newSrc = string.sub(src, 1, idx - 1) .. newText .. string.sub(src, idx + #oldText)

    -- p28: compile-check the RESULT of the splice — but only refuse when the
    -- edit INTRODUCES breakage (old source compiled, new doesn't). A script
    -- that is already broken may legitimately need multiple repair edits.
    local synErr = checkLuauSyntax(newSrc, targetPath)
    if synErr and checkLuauSyntax(src, targetPath) == nil then
        return false, { error = synErr .. " (the edit would have broken a currently-valid script; nothing was changed)",
                        error_code = "syntax_error" }, nil, nil
    end

    ChangeHistoryService:SetWaypoint("Pre-Pipeline Edit: " .. script.Name)
    local ok, err = pcall(function()
        if ScriptEditorService then
            ScriptEditorService:UpdateSourceAsync(script, function() return newSrc end)
        else
            script.Source = newSrc
        end
    end)
    if not ok then
        return false, { error = "Failed to apply edit: " .. tostring(err), error_code = "write_failed" }, nil, nil
    end
    ChangeHistoryService:SetWaypoint("Pipeline Edit: " .. script.Name)

    local readback = script.Source
    return true, { path = script:GetFullName(), note = _fuzzy_note }, readback, nil
end

-- delete_script  (V4 ref: pisces_web_plugin.lua:899-910)
local function run_delete_script(input)
    local targetPath = tostring(input.target or input.path or "")
    local script, rerrCode, rerrMsg = resolveScriptTarget(targetPath)
    -- rev 01104 (P3): NEVER destroy a coin-flip match — deleting the wrong
    -- "Config" is unrecoverable. Surface the ambiguity instead.
    if not script and rerrCode == "ambiguous_target" then
        return false, { error = rerrMsg, error_code = rerrCode }, nil, nil
    end
    local existed = script ~= nil

    if script then
        local fullPath = script:GetFullName()
        ChangeHistoryService:SetWaypoint("Pre-Pipeline Delete: " .. script.Name)
        script:Destroy()
        ChangeHistoryService:SetWaypoint("Pipeline Delete")
        return true, { path = fullPath, existed_before = true, deleted_now = true }, nil, nil
    end
    -- Script not found — not an error per spec (idempotent delete)
    return true, { path = targetPath, existed_before = false, deleted_now = false }, nil, nil
end

-- p29: RECURSIVE CHILDREN. One create_instance call can now build an entire
-- subtree ({class_name, name, properties, children} nested specs) — a styled
-- UI panel or a multi-part prop no longer costs one round-trip per instance.
-- Idempotent like the top level: a same-name+class child is reused (props
-- re-applied) instead of duplicated.
local _CHILD_MAX_DEPTH = 6
-- p39: 60 → 800. Map pushes were CHUNK-limited to 52 nodes/call by the old
-- cap → a 2000-part map cost ~46 round-trips (owner: "pushing to studio
-- takes a hell of a long time"). The server gates big packets on plugin
-- version ≥ p39, so old plugins still get 52-node chunks.
local _CHILD_MAX_NODES = 800

local function _build_child_tree(parentInst, children, depth, stats)
    if type(children) ~= "table" then return end
    if depth > _CHILD_MAX_DEPTH then
        table.insert(stats.fails, "max nesting depth (" .. _CHILD_MAX_DEPTH
            .. ") exceeded under " .. parentInst.Name)
        return
    end
    for _, spec in ipairs(children) do
        if stats.created >= _CHILD_MAX_NODES then
            table.insert(stats.fails,
                "child cap (" .. _CHILD_MAX_NODES .. ") reached; split into a second call")
            return
        end
        if type(spec) == "table" then
            local cls = tostring(spec.class_name or spec.className or spec.class or "Part")
            local nm  = tostring(spec.name or cls)
            local props = spec.properties or spec.props or spec.attributes
            local child = parentInst:FindFirstChild(nm)
            if not (child and child.ClassName == cls) then
                local okc, newc = pcall(function() return Instance.new(cls) end)
                if okc and newc then
                    newc.Name = nm
                    child = newc
                else
                    table.insert(stats.fails, nm .. ": cannot create class " .. cls)
                    child = nil
                end
            end
            if child then
                if type(props) == "table" then
                    for pn, pv in _propPairs(props) do
                        local norm = normalizePropertyName(pn)
                        local okp, errp = pcall(function()
                            child[norm] = coercePropertyValue(child, norm, pv)
                        end)
                        if not okp then
                            table.insert(stats.fails,
                                nm .. "." .. norm .. ": " .. tostring(errp))
                        end
                    end
                end
                if child.Parent ~= parentInst then child.Parent = parentInst end
                stats.created = stats.created + 1
                _build_child_tree(child, spec.children, depth + 1, stats)
            end
        end
    end
end

local function _apply_children(inst, input, resOut)
    local kids = input.children
    if type(kids) ~= "table" or #kids == 0 then return end
    ChangeHistoryService:SetWaypoint("Pre-Pipeline Children: " .. inst.Name)
    local stats = { created = 0, fails = {} }
    _build_child_tree(inst, kids, 1, stats)
    ChangeHistoryService:SetWaypoint("Pipeline Children: " .. inst.Name)
    resOut.children_created = stats.created
    if #stats.fails > 0 then
        resOut.child_fails = stats.fails
        warn(string.format("[Pipeline] %s child fails: %s",
            inst.Name, table.concat(stats.fails, "; ")))
    end
end

-- create_instance  (V4 ref: pisces_web_plugin.lua:1027-1048)
local function run_create_instance(input)
    local className    = tostring(input.class_name or input.className or input.class or "Part")
    local instanceName = tostring(input.name or className)
    local parentPath   = tostring(input.parent or "Workspace")
    -- 2026-05-25 (p15): also accept `props` and `attributes` as aliases for
    -- `properties` since models often guess different keys. Normalise here so
    -- the property-loop below sees one canonical key.
    if type(input.properties) ~= "table" then
        if type(input.props) == "table" then
            input.properties = input.props
        elseif type(input.attributes) == "table" then
            input.properties = input.attributes
        end
    end

    local parent, vivified = findOrCreateParent(parentPath)
    if not parent then
        return false, { error = "Parent not found: " .. parentPath, error_code = "parent_not_found" }, nil, nil
    end
    if vivified then
        warn("[Pipeline] vivified missing container(s) as Folder: "
            .. table.concat(vivified, ", "))
    end

    -- 2026-05-24 (rev 00971) idempotency: if an instance with this name +
    -- ClassName already exists under parent, return it instead of creating
    -- a duplicate. The harness frequently re-emits create_instance for the
    -- Animations Folder + RemoteEvents across iters (e.g. when the snapshot
    -- of present_paths is stale, or the model retries). Without this, Studio
    -- ends up with "Animations", "Animations2", "Animations3" and the clip
    -- paths break.
    local existing = parent:FindFirstChild(instanceName)

    -- 2026-05-29 (rev 01057) FOLDER UPGRADE. When a child was dispatched before
    -- its container, findOrCreateParent vivified a *Folder* placeholder for the
    -- missing segment (the "make me a pistol → it built a Folder, not a Tool"
    -- bug; the Handle ended up a Folder full of Sounds). When the real
    -- create_instance for that container finally arrives with a different,
    -- non-Folder class, upgrade in place: build the correct class, reparent the
    -- folder's children onto it, destroy the folder. Also collapses the
    -- duplicate-Handle case (a Handle Folder of sounds + a separate Handle Part)
    -- into one correct Part. The server-side path topo-sort (rev 01057) makes
    -- this rare, but it's the belt to that suspenders.
    if existing and existing.ClassName == "Folder" and className ~= "Folder" then
        -- rev 01104 (P10): waypoint the upgrade so Ctrl+Z / AI-undo captures it.
        ChangeHistoryService:SetWaypoint("Pre-Pipeline Upgrade: " .. instanceName)
        local okU, newInst = pcall(function() return Instance.new(className) end)
        if okU and newInst then
            newInst.Name = instanceName
            local _upFails = {}
            if type(input.properties) == "table" then
                for propName, propVal in _propPairs(input.properties) do
                    local norm = normalizePropertyName(propName)
                    local okp, errp = pcall(function()
                        newInst[norm] = coercePropertyValue(newInst, norm, propVal)
                    end)
                    if not okp then table.insert(_upFails, norm .. ": " .. tostring(errp)) end
                end
            end
            newInst.Parent = parent
            local _moved = 0
            for _, child in ipairs(existing:GetChildren()) do
                local okm = pcall(function() child.Parent = newInst end)
                if okm then _moved = _moved + 1 end
            end
            pcall(function() existing:Destroy() end)
            local upPath = newInst:GetFullName()
            warn(string.format(
                "[Pipeline] upgraded Folder '%s' -> %s (moved %d children)",
                instanceName, className, _moved))
            local upOut = { path = upPath, class_name = className,
                            upgraded_from = "Folder", moved_children = _moved,
                            property_fails = _upFails }
            _apply_children(newInst, input, upOut)
            return true, upOut, nil, upPath
        end
    end

    -- p28 (2026-07-01) Tool.Handle upsert: Roblox binds exactly ONE BasePart
    -- named Handle per Tool. If a Handle BasePart already exists and a create
    -- arrives with a DIFFERENT BasePart subclass (Part vs MeshPart etc.), a
    -- sibling duplicate would break equip physics — apply the properties to
    -- the existing Handle instead. (Same-class re-emits hit the reuse branch
    -- below; a vivified Folder hits the upgrade branch above.)
    if existing and instanceName == "Handle" and parent:IsA("Tool")
        and existing:IsA("BasePart") and existing.ClassName ~= className then
        local _hFails = {}
        if type(input.properties) == "table" and next(input.properties) ~= nil then
            ChangeHistoryService:SetWaypoint("Pre-Pipeline Handle Update: " .. instanceName)
            for propName, propVal in _propPairs(input.properties) do
                local norm = normalizePropertyName(propName)
                local okh, errh = pcall(function()
                    existing[norm] = coercePropertyValue(existing, norm, propVal)
                end)
                if not okh then table.insert(_hFails, norm .. ": " .. tostring(errh)) end
            end
            ChangeHistoryService:SetWaypoint("Pipeline Handle Update: " .. instanceName)
        end
        local hPath = existing:GetFullName()
        local hOut = { path = hPath, class_name = existing.ClassName, reused = true,
                       note = "Tool already has a Handle (" .. existing.ClassName
                           .. "); a Tool uses exactly one - properties were applied to it",
                       property_fails = _hFails }
        _apply_children(existing, input, hOut)
        return true, hOut, nil, hPath
    end

    if existing and existing.ClassName == className then
        -- Apply any new properties to the existing instance — caller may be
        -- updating attributes (Anchored, Color, etc.) on a re-emit.
        local _propFails = {}
        local _hasProps = type(input.properties) == "table" and next(input.properties) ~= nil
        -- rev 01104 (P10): waypoint the reuse-with-property-update so Ctrl+Z /
        -- AI-undo captures it (a re-emit that recolors/anchors an existing
        -- part was previously invisible to undo).
        if _hasProps then
            ChangeHistoryService:SetWaypoint("Pre-Pipeline Update: " .. instanceName)
        end
        if type(input.properties) == "table" then
            for propName, propVal in _propPairs(input.properties) do
                local norm = normalizePropertyName(propName)
                local ok, err = pcall(function() existing[norm] = coercePropertyValue(existing, norm, propVal) end)
                if not ok then table.insert(_propFails, norm .. ": " .. tostring(err)) end
            end
        end
        if _hasProps then
            ChangeHistoryService:SetWaypoint("Pipeline Update: " .. instanceName)
        end
        if #_propFails > 0 then
            warn(string.format("[Pipeline] %s property fails (reuse): %s",
                instanceName, table.concat(_propFails, "; ")))
        end
        local instancePath = existing:GetFullName()
        local ruOut = { path = instancePath, class_name = className, reused = true,
                        property_fails = _propFails }
        _apply_children(existing, input, ruOut)
        return true, ruOut, nil, instancePath
    end

    ChangeHistoryService:SetWaypoint("Pre-Pipeline Instance: " .. instanceName)
    local ok, inst = pcall(function() return Instance.new(className) end)
    if not ok or not inst then
        return false, { error = "Cannot create class: " .. className, error_code = "invalid_class" }, nil, nil
    end

    inst.Name = instanceName
    local _propFails = {}
    if type(input.properties) == "table" then
        for propName, propVal in _propPairs(input.properties) do
            local norm = normalizePropertyName(propName)
            local ok, err = pcall(function() inst[norm] = coercePropertyValue(inst, norm, propVal) end)
            if not ok then table.insert(_propFails, norm .. ": " .. tostring(err)) end
        end
    end
    inst.Parent = parent
    ChangeHistoryService:SetWaypoint("Pipeline Instance: " .. instanceName)

    if #_propFails > 0 then
        warn(string.format("[Pipeline] %s property fails: %s",
            instanceName, table.concat(_propFails, "; ")))
    end

    local instancePath = inst:GetFullName()
    -- M4: value_after = full path confirms the instance actually exists
    local resOut = { path = instancePath, class_name = className,
                     property_fails = _propFails }
    if vivified then
        resOut.vivified_containers = vivified
        resOut.note = "Missing container(s) on the parent path were auto-created "
            .. "as FOLDERS: " .. table.concat(vivified, ", ")
            .. ". If any should be a Model/Tool/other class, create it "
            .. "explicitly (create_instance upgrades a same-name Folder in place)."
    end
    _apply_children(inst, input, resOut)
    return true, resOut, nil, instancePath
end

-- set_property  (V4 ref: pisces_web_plugin.lua:1180-1196)
-- p28: ATTRIBUTE fallback. Models constantly "set" custom data as properties
-- (IsTrainingDummy, CurrentHealth, Owner...) which throws "not a valid member".
-- The Roblox idiom for custom data IS Attributes — when a set fails with
-- not-a-valid-member and the value is a primitive, set it as an Attribute and
-- SAY SO in the result (so a typo'd real property is still visible, not
-- silently swallowed). Returns true when the fallback applied.
local function trySetAttributeFallback(inst, propName, value, err)
    local es = tostring(err or "")
    if not (es:find("not a valid member", 1, true)
        or es:find("is not a valid member", 1, true)) then
        return false
    end
    local vt = type(value)
    if not (vt == "string" or vt == "number" or vt == "boolean") then
        return false
    end
    local okA = pcall(function() inst:SetAttribute(propName, value) end)
    return okA
end

-- p29 (2026-07-02): AUTO-VIVIFY Lighting post-processing singletons. Prod
-- pattern: models set_property on Lighting.BloomEffect / SunRaysEffect /
-- DepthOfFieldEffect before creating them → 3 benign-but-wasted failed legs
-- per lighting pass. These are argless singleton classes whose instance name
-- conventionally equals the class — creating one on demand is always what the
-- model meant. Narrow allowlist; anything else still errors not_found.
local _LIGHTING_SINGLETONS = {
    BloomEffect = true, SunRaysEffect = true, DepthOfFieldEffect = true,
    ColorCorrectionEffect = true, BlurEffect = true, Atmosphere = true,
}

local function _vivify_lighting_effect(targetPath)
    local segs = {}
    for s in tostring(targetPath):gsub("/", "."):gmatch("[^%.]+") do
        table.insert(segs, s)
    end
    if #segs ~= 2 then return nil end
    local root, leaf = segs[1], segs[2]
    if root:lower() ~= "lighting" or not _LIGHTING_SINGLETONS[leaf] then
        return nil
    end
    local Lighting = game:GetService("Lighting")
    local okC, eff = pcall(function()
        local e = Instance.new(leaf)
        e.Parent = Lighting
        return e
    end)
    if okC and eff then
        warn("[Pipeline] auto-created Lighting." .. leaf .. " for set_property")
        return eff
    end
    return nil
end

local function run_set_property(input)
    local targetPath   = tostring(input.target or input.instance or input.path or "")
    local propertyName = normalizePropertyName(input.property or input.property_name or "")
    local value        = input.value

    local inst = findInstanceByPath(targetPath)
    if not inst then
        inst = _vivify_lighting_effect(targetPath)
    end
    if not inst then
        return false, { error = "Instance not found: " .. targetPath, error_code = "not_found" }, nil, nil
    end

    -- rev 01104 (P12): a multi-key `properties`/`props` dict in ONE call. The
    -- server-side fold (S8) only collapses a SINGLE-key dict to property/value;
    -- a 2+ key dict reaches the plugin intact and used to be dropped (only the
    -- scalar `property`/`value` was read). Apply every entry.
    local propsDict = nil
    if type(input.properties) == "table" then propsDict = input.properties
    elseif type(input.props) == "table" then propsDict = input.props end
    if propsDict and next(propsDict) ~= nil then
        ChangeHistoryService:SetWaypoint("Pre-Pipeline Props: " .. inst.Name)
        local fails, setCount = {}, 0
        local attrsSet = {}
        for pName, pVal in _propPairs(propsDict) do
            local norm = normalizePropertyName(pName)
            local ok, err = pcall(function()
                inst[norm] = coercePropertyValue(inst, norm, pVal)
            end)
            if ok then setCount = setCount + 1
            elseif trySetAttributeFallback(inst, norm, pVal, err) then
                setCount = setCount + 1
                table.insert(attrsSet, norm)
            else table.insert(fails, norm .. ": " .. tostring(err)) end
        end
        ChangeHistoryService:SetWaypoint("Pipeline Props: " .. inst.Name)
        if setCount == 0 and #fails > 0 then
            return false, {
                error      = "All property sets failed: " .. table.concat(fails, "; "),
                error_code = "set_failed",
            }, nil, nil
        end
        local resTbl = {
            target = inst:GetFullName(), set_count = setCount,
            property_fails = fails,
        }
        if #attrsSet > 0 then
            resTbl.set_as_attributes = attrsSet
            resTbl.note = "Not real properties of " .. inst.ClassName
                .. " - stored as ATTRIBUTES instead (read with GetAttribute): "
                .. table.concat(attrsSet, ", ")
        end
        return true, resTbl, nil, inst:GetFullName()
    end

    if propertyName == "" then
        return false, { error = "Missing property name", error_code = "missing_property" }, nil, nil
    end

    ChangeHistoryService:SetWaypoint("Pre-Pipeline Prop: " .. inst.Name)
    local coerced = coercePropertyValue(inst, propertyName, value)
    local ok, err = pcall(function() inst[propertyName] = coerced end)
    -- p38: instance-REFERENCE property that coercePropertyValue missed. Its
    -- ref detection needs typeof(currentVal)=="Instance" or a hardcoded name
    -- list, so an UNSET reference prop outside the list (SoundGroup on a
    -- fresh Sound) fell through to a raw string assign → "SoundGroup
    -- expected, got string" (prod f5878d63). Resolve the string as a path
    -- and retry once; an unresolvable path gets a precise error instead of
    -- the misleading type mismatch (prod 767c0c5e: typo'd value path).
    if not ok and type(value) == "string"
        and tostring(err):find("expected, got string") then
        local refInst = findInstanceByPath(value)
        if refInst then
            ok, err = pcall(function() inst[propertyName] = refInst end)
        else
            return false, {
                error = "Failed to set " .. propertyName .. ": it expects an "
                    .. "INSTANCE reference and the value path '" .. value
                    .. "' does not resolve to any instance - check the path "
                    .. "for typos (exact, case-sensitive full path).",
                error_code = "ref_path_not_found",
            }, nil, nil
        end
    end
    if not ok then
        if trySetAttributeFallback(inst, propertyName, value, err) then
            ChangeHistoryService:SetWaypoint("Pipeline Attr: " .. inst.Name)
            return true, {
                target = inst:GetFullName(), property = propertyName,
                set_as_attribute = true,
                note = propertyName .. " is not a real property of "
                    .. inst.ClassName
                    .. " - stored as an ATTRIBUTE instead (read it with "
                    .. "inst:GetAttribute(\"" .. propertyName .. "\"))",
            }, nil, tostring(value)
        end
        return false, { error = "Failed to set " .. propertyName .. ": " .. tostring(err), error_code = "set_failed" }, nil, nil
    end
    ChangeHistoryService:SetWaypoint("Pipeline Prop: " .. inst.Name)

    -- M4: read the property back and return the actual value
    local actualValue = nil
    pcall(function()
        local raw = inst[propertyName]
        if typeof(raw) == "Vector3" then
            actualValue = string.format("%g,%g,%g", raw.X, raw.Y, raw.Z)
        elseif typeof(raw) == "Color3" then
            actualValue = string.format("%d,%d,%d",
                math.floor(raw.R * 255 + 0.5),
                math.floor(raw.G * 255 + 0.5),
                math.floor(raw.B * 255 + 0.5))
        elseif typeof(raw) == "CFrame" then
            local p = raw.Position
            actualValue = string.format("CFrame(%g,%g,%g)", p.X, p.Y, p.Z)
        else
            actualValue = tostring(raw)
        end
    end)
    return true, { target = inst:GetFullName(), property = propertyName }, nil, actualValue
end

-- create_animation — server-side tool; the plugin MUST NOT re-execute it
-- if it somehow lands here. Log a clear error.
local function run_create_animation(_input)
    warn("[Pipeline] create_animation reached plugin — this is a server-side tool. " ..
         "Check server routing. Returning error so server can re-dispatch.")
    return false, {
        error      = "create_animation is server-side; should never reach plugin",
        error_code = "wrong_executor",
    }, nil, nil
end

-- rev 01090 (2026-06-03): playtest re-entry guard. The user reported "the
-- playtest runs twice and the second one doesn't stop — it leaves me stuck in
-- a playtest". The harness no longer TRIGGERS a second playtest, but as
-- belt-and-suspenders a run_playtest that arrives while one is still inside its
-- play window is refused here — a second ExecutePlayModeAsync races the first's
-- auto-stop and strands Studio in Play mode. Timestamp-based (not a bare bool)
-- so a crashed/aborted playtest can't permanently wedge the flag: it
-- auto-expires after the play window + margin, and cleanup() clears it on every
-- normal/early-error return.
local _playtestActiveUntil = 0

--------------------------------------------------------------------------------
-- rev 01105 (P1b): console-capture hygiene shared by run_playtest / run_test.
-- Three real-world failure modes the rev 01104 head/tail ring still missed:
--   1. ONE giant line — print(HttpService:JSONEncode(bigTable)) is a single
--      LogService message that can be 50KB+. It ate the whole char-based
--      head/tail window (squeezing out every actual error line), held
--      unbounded memory in the ring, and the final :sub() split it mid-line
--      and mid-UTF-8.
--   2. An error LOOP (e.g. a bad RunService.Heartbeat handler) emits the SAME
--      line 60x/sec — 200 ring slots full of one message, zero diversity.
--   3. Char-based final truncation cut lines mid-way.
-- Fixes: per-line cap at CAPTURE time (also bounds Studio memory), adjacent
-- dedup with (xN) repeat counts, entry-boundary final truncation that never
-- splits a line.
--------------------------------------------------------------------------------
local PT_LINE_MAX = 600

local function _ptUtf8Head(s, n)
    -- first <=n bytes without splitting a UTF-8 codepoint
    local i = n
    while i > 0 do
        local b = s:byte(i + 1)
        if b and b >= 0x80 and b < 0xC0 then i = i - 1 else break end
    end
    return s:sub(1, i)
end

local function _ptUtf8Tail(s, n)
    -- last <=n bytes without splitting a UTF-8 codepoint
    local i = #s - n + 1
    while i <= #s do
        local b = s:byte(i)
        if b and b >= 0x80 and b < 0xC0 then i = i + 1 else break end
    end
    return s:sub(i)
end

local function _ptCapLine(line)
    if #line <= PT_LINE_MAX then return line end
    return _ptUtf8Head(line, 400)
        .. " ...[" .. (#line - 550) .. " chars elided]... "
        .. _ptUtf8Tail(line, 150)
end

-- Capture sink: feed(message, messageType) stores capped+deduped entries in a
-- head array + chronological tail ring; render(charMax, headBudget, tailBudget)
-- joins them with an ENTRY-boundary head+tail truncation.
local function _ptNewCapture(headMax, tailMax)
    local cap = {
        head = {}, tail = {}, tailNext = 1,
        entries = 0,        -- entries stored (post-dedup)
        messages = 0,       -- raw messages seen
        errors = 0, warnings = 0,
        last = nil,         -- most recently stored entry (dedup target)
    }
    function cap.feed(message, messageType)
        local t = "Info"
        if messageType == Enum.MessageType.MessageWarning then t = "Warning"
        elseif messageType == Enum.MessageType.MessageError then t = "Error" end
        if t == "Error" then cap.errors = cap.errors + 1
        elseif t == "Warning" then cap.warnings = cap.warnings + 1 end
        cap.messages = cap.messages + 1
        local line = _ptCapLine("[" .. t .. "] " .. tostring(message))
        if cap.last and cap.last.l == line then
            -- repeat of the previous entry — bump its count, no new slot.
            -- An error loop now reads "...(x600)" instead of filling the ring.
            cap.last.n = cap.last.n + 1
            return
        end
        local e = { l = line, n = 1 }
        cap.last = e
        cap.entries = cap.entries + 1
        if #cap.head < headMax then
            table.insert(cap.head, e)
        else
            cap.tail[cap.tailNext] = e
            cap.tailNext = (cap.tailNext % tailMax) + 1
        end
    end
    function cap.render(charMax, headBudget, tailBudget)
        local function rend(e)
            if e.n > 1 then return e.l .. " (x" .. e.n .. ")" end
            return e.l
        end
        local lines = {}
        local omitIdx, omitN = nil, 0
        for _, e in ipairs(cap.head) do table.insert(lines, rend(e)) end
        if cap.entries > #cap.head then
            local written = cap.entries - #cap.head
            local tailCount = math.min(written, tailMax)
            local dropped = written - tailCount
            if dropped > 0 then
                table.insert(lines,
                    "...[" .. dropped .. " console entries omitted]...")
                omitIdx, omitN = #lines, dropped
            end
            for i = 1, tailCount do
                local idx = ((cap.tailNext - 1 - tailCount + i - 1) % tailMax) + 1
                table.insert(lines, rend(cap.tail[idx]))
            end
        end
        local out = table.concat(lines, "\n")
        if #out <= charMax then return out end
        -- entry-boundary head+tail fold (errors live at the END). Entries are
        -- capped at ~640 rendered chars, so both windows always fit whole lines.
        local hi, used, headParts = 0, 0, {}
        for i = 1, #lines do
            local L = #lines[i] + 1
            if used + L > headBudget then break end
            used = used + L; hi = i
            table.insert(headParts, lines[i])
        end
        local ti, tused, tailParts = #lines + 1, 0, {}
        for i = #lines, hi + 1, -1 do
            local L = #lines[i] + 1
            if tused + L > tailBudget then break end
            tused = tused + L; ti = i
            table.insert(tailParts, 1, lines[i])
        end
        local cut = ti - hi - 1
        if cut <= 0 then return out end
        -- if the ring's own "...entries omitted..." marker fell inside the
        -- cut region, merge its count so nothing is silently understated.
        local mark = "...[" .. cut .. " console lines truncated"
        if omitIdx and omitIdx > hi and omitIdx < ti then
            mark = mark .. "; " .. omitN .. " more entries omitted earlier"
        end
        return table.concat(headParts, "\n")
            .. "\n" .. mark .. "]...\n"
            .. table.concat(tailParts, "\n")
    end
    return cap
end

--------------------------------------------------------------------------------
-- p30: PLAY-SESSION CONSOLE RELAY.
-- On most Studio builds the EDIT DataModel's LogService.MessageOut never
-- receives play-session output — 74-91% of prod playtests came back with an
-- empty console while the game clearly printed (asserts, infinite-yield
-- warnings and real errors all lost). Studio loads this plugin a second time
-- INSIDE the Play Solo session; that instance's LogService does see the run.
-- When we detect we're the play-session instance, capture everything and
-- flush it to plugin settings (shared on disk) so the edit instance can read
-- it back after RunService:Stop(). The edit side only trusts a blob whose
-- timestamp falls inside the current playtest window, and clears the key
-- before every run — a stale relay can never masquerade as fresh output.
--------------------------------------------------------------------------------
if RunService:IsRunning() then
    task.spawn(function()
        local relayCap = _ptNewCapture(120, 80)
        local relayMarkers = {}
        local relayStarted = os.time()
        -- p53 (2026-10-25): the server and client play copies used to share
        -- one key, so whichever flushed last erased the other (L0: server
        -- prints lost). Each copy now has its own key; the edit side merges.
        local relayKey = RunService:IsServer() and "pisces_pt_relay"
            or "pisces_pt_relay_c"
        -- p54: in a run_playtest window (armed by the edit side moments ago)
        -- the server copy owns two stops: early, 4 s after the harness prints
        -- PISCES_PLAYTEST_DONE, and a backup at duration + 15 s in case the
        -- injected auto-stop script never ran. The interactive lane is never
        -- armed, so it is never stopped from here.
        local arm = nil
        if RunService:IsServer() then
            pcall(function()
                local a = plugin:GetSetting("pisces_pt_arm")
                if type(a) == "table" and (tonumber(a.at) or 0) >= relayStarted - 60 then
                    arm = a
                end
            end)
        end
        local stopping = false
        local function endTest(why)
            if stopping then return end
            stopping = true
            print("[Pipeline] playtest stop: " .. why)
            pcall(function()
                game:GetService("StudioTestService"):EndTest({ completed = true })
            end)
        end
        if arm then
            task.delay((tonumber(arm.dur) or 30) + 15, function()
                endTest("backup timer")
            end)
        end
        local function relayTake(message, messageType)
            relayCap.feed(message, messageType)
            local msgStr = tostring(message)
            if msgStr:sub(1, 7) == "PISCES_" and #relayMarkers < 80 then
                table.insert(relayMarkers, msgStr)
            end
            if msgStr:find("PISCES_PLAYTEST_DONE", 1, true) then
                if arm and arm.early and not stopping then
                    task.delay(4, function() endTest("harness done") end)
                elseif not RunService:IsServer() then
                    -- p55: the client harness (the usual place for DONE) can't
                    -- end the test; tell the server copy through settings.
                    pcall(function() plugin:SetSetting("pisces_pt_done", os.time()) end)
                end
            end
        end
        -- p53: game scripts start before this copy loads, so their first
        -- prints (often every PISCES_ASSERT) were already gone. Backfill from
        -- this DataModel's log history, bounded to the current run.
        pcall(function()
            -- the edit side stamps the arm time; never take lines from before it
            local armAt = tonumber(plugin:GetSetting("pisces_pt_arm_at"))
            if not armAt or armAt < relayStarted - 120 then armAt = relayStarted - 20 end
            for _, e in ipairs(LogService:GetLogHistory()) do
                local ts = tonumber(e.timestamp) or 0
                if ts >= armAt - 1 then
                    relayTake(e.message, e.messageType)
                end
            end
        end)
        local okConn = pcall(function()
            LogService.MessageOut:Connect(relayTake)
        end)
        if not okConn then return end
        local function flush(final)
            pcall(function()
                plugin:SetSetting(relayKey, {
                    at           = relayStarted,
                    console      = relayCap.render(12000, 4000, 8000),
                    errors       = relayCap.errors,
                    warnings     = relayCap.warnings,
                    output_count = relayCap.messages,
                    markers      = relayMarkers,
                    done         = final and true or false,
                })
            end)
        end
        -- periodic flush (survives a hard play-session teardown) + a final
        -- flush on Unloading (fires when the user/auto-stop ends the run).
        pcall(function() plugin.Unloading:Connect(function() flush(true) end) end)
        local clientDoneSeen = false
        while true do
            task.wait(2)
            flush(false)
            if arm and arm.early and not stopping and not clientDoneSeen then
                local okD, doneAt = pcall(function()
                    return plugin:GetSetting("pisces_pt_done")
                end)
                if okD and (tonumber(doneAt) or 0) >= (tonumber(arm.at) or 0) then
                    clientDoneSeen = true
                    task.delay(4, function() endTest("client harness done") end)
                end
            end
        end
    end)
end

--------------------------------------------------------------------------------
-- PLAYTEST V2 — INTERACTIVE DRIVER (p51, 2026-08-15; PLAYTEST_V2_PLAN.md)
-- Beta-proven in PiscesPlaytestBeta.lua v0.1-0.7. Two halves:
--   EDIT copy : playtest_start tool — launches a persistent Play session via
--               StudioTestService:ExecutePlayModeAsync (no injected harness,
--               no fixed window) and hands session config to the play copy
--               through plugin settings (GetTestArgs HANGS in play plugin
--               ctx — field result, do not use).
--   PLAY copy : boots a driver that polls /v5/poll?ctx=play and serves
--               playtest_act jobs {verb, args}. The server's claim filter
--               routes ONLY playtest_act to ctx=play pollers, so the two
--               copies never steal each other's work.
-- Field laws baked in (beta spikes):
--   * play plugin copy is SERVER context: PromptShown/InputHoldBegin are
--     client-only no-ops there; PromptTriggered DOES fire server-side and is
--     the interact success oracle.
--   * runtime code compiling is BLOCKED in play plugin ctx → verbs only, never code.
--   * CreateVirtualInput WORKS in play ctx; SendKey(isDown, KeyCode) — bool
--     first. Real trusted input (prompts, movement) rides it.
--   * CaptureService pixels are walled off (temp textures can't enter
--     EditableImage) → vision = povshot (1 raycast/pixel render) + map
--     (overhead raycast grid), both server-safe.
--   * A verb executor must ALWAYS post a result; a dying session eats jobs,
--     so the agent-side deadline is the final backstop.
--------------------------------------------------------------------------------
local PT2_start_session
do
    local PT2_SETTING = "pisces_pt2_session"
    local PT2_MAX_DEFAULT = 300

    ----------------------------------------------------------------------
    -- EDIT half: the playtest_start tool
    ----------------------------------------------------------------------
    PT2_start_session = function(input)
        if RunService:IsRunning() then
            return false, {
                error      = "already inside a play session — playtest_start "
                    .. "must run from edit mode (use playtest_act "
                    .. "{verb='end_session'} to leave the current one)",
                error_code = "already_running",
            }, nil, nil
        end
        local okSTS, sts = pcall(function()
            return game:GetService("StudioTestService")
        end)
        if not okSTS or not sts or type(sts.ExecutePlayModeAsync) ~= "function" then
            return false, {
                error      = "this Studio build has no StudioTestService — "
                    .. "interactive playtests need a 2026+ Studio",
                error_code = "no_studio_test_service",
            }, nil, nil
        end
        local nowClock = os.clock()
        if nowClock < _playtestActiveUntil then
            return false, {
                error      = "a playtest is already running this turn; wait "
                    .. "for it to finish or stop it first",
                error_code = "playtest_already_running",
            }, nil, nil
        end
        local maxS = math.clamp(
            math.floor(tonumber(input.max_seconds or input.timeout) or PT2_MAX_DEFAULT),
            60, 900)
        local sid = "pt2-" .. tostring(os.time()) .. "-"
            .. tostring(math.random(10000, 99999))
        pcall(function()
            plugin:SetSetting(PT2_SETTING,
                { sid = sid, max_s = maxS, at = os.time() })
        end)
        _playtestActiveUntil = nowClock + maxS + 30
        task.spawn(function()
            local okRun, errRun = pcall(function()
                return sts:ExecutePlayModeAsync({ pisces_pt2 = sid })
            end)
            -- session over (EndTest, user stop, or crash): release the guard
            -- so run_playtest / another start can proceed.
            _playtestActiveUntil = 0
            pcall(function() plugin:SetSetting(PT2_SETTING, nil) end)
            if not okRun then
                warn("[Pipeline] playtest session launch failed: "
                    .. tostring(errRun))
            end
        end)
        return true, {
            tool       = "playtest_start",
            session_id = sid,
            max_seconds = maxS,
            summary    = "Interactive playtest session launching. The driver "
                .. "boots inside the play session in ~5-10s; drive it with "
                .. "playtest_act {verb=..., args=...}. Verbs: snapshot, "
                .. "find, props, walk, interact, press, jump, map, povshot, "
                .. "timeline, end_session. The session auto-stops after "
                .. tostring(maxS) .. "s — ALWAYS finish with "
                .. "playtest_act {verb='end_session'}.",
        }, nil, nil
    end

    ----------------------------------------------------------------------
    -- PLAY half: the driver. Everything below only arms in a play session.
    -- (Wrapping `if`, not an early return — `return` mid-do-block is a
    -- Luau syntax error.)
    ----------------------------------------------------------------------
    if RunService:IsRunning() then

    local Players2   = game:GetService("Players")
    local PPS2       = game:GetService("ProximityPromptService")
    local Pathfind2  = game:GetService("PathfindingService")
    local UIS2       = game:GetService("UserInputService")
    local Lighting2  = game:GetService("Lighting")

    -- timeline event tap ---------------------------------------------------
    local T0 = os.clock()
    local TIMELINE = {}
    local function ev(kind, data)
        data = data or {}
        data.t = math.floor((os.clock() - T0) * 100 + 0.5) / 100
        data.kind = kind
        TIMELINE[#TIMELINE + 1] = data
        if #TIMELINE > 4000 then
            for _ = 1, 500 do table.remove(TIMELINE, 1) end
        end
    end
    pcall(function()
        PPS2.PromptShown:Connect(function(p)
            ev("prompt_shown", { path = p:GetFullName() })
        end)
        PPS2.PromptTriggered:Connect(function(p, plr)
            ev("prompt_triggered", { path = p:GetFullName(),
                                     player = plr and plr.Name or "?" })
        end)
    end)
    pcall(function()
        LogService.MessageOut:Connect(function(msg, mtype)
            if mtype == Enum.MessageType.MessageError
                or mtype == Enum.MessageType.MessageWarning then
                ev("console", { level = tostring(mtype.Name),
                                text = string.sub(tostring(msg), 1, 300) })
            end
        end)
        game:GetService("ScriptContext").Error:Connect(function(msg, stack)
            ev("script_error", { text = string.sub(tostring(msg), 1, 300),
                                 stack = string.sub(tostring(stack), 1, 400) })
        end)
    end)
    local function anyPlayer()
        return Players2.LocalPlayer or Players2:GetPlayers()[1]
    end
    task.spawn(function()
        pcall(function()
            local lp = anyPlayer()
            if not lp then
                Players2.PlayerAdded:Wait()
                lp = anyPlayer()
            end
            if not lp then return end
            local function hookChar(char)
                ev("character_added", { name = char.Name })
                local hum = char:WaitForChild("Humanoid", 10)
                if hum then
                    hum.StateChanged:Connect(function(_, new)
                        ev("humanoid_state", { state = tostring(new.Name) })
                    end)
                    hum.Died:Connect(function() ev("died", {}) end)
                end
            end
            if lp.Character then hookChar(lp.Character) end
            lp.CharacterAdded:Connect(hookChar)
        end)
    end)

    -- verb helpers ---------------------------------------------------------
    local function getChar(timeoutSec)
        local deadline = os.clock() + (timeoutSec or 10)
        while os.clock() < deadline do
            local lp = anyPlayer()
            local c = lp and lp.Character
            if c and c:FindFirstChild("HumanoidRootPart")
                and c:FindFirstChildOfClass("Humanoid") then
                return c
            end
            task.wait(0.2)
        end
        return nil, "character never appeared"
    end
    local function resolvePath(fullName)
        local node = game
        for seg in string.gmatch(tostring(fullName), "[^%.]+") do
            if node == game and seg == "game" then
                -- skip leading "game"
            elseif node == game and seg == "Workspace" then
                node = workspace
            else
                node = node:FindFirstChild(seg)
                if not node then return nil, "no child '" .. seg .. "'" end
            end
        end
        return node
    end
    local function targetPos(target)
        if typeof(target) == "Vector3" then return target end
        if type(target) == "table" and target[1] then
            return Vector3.new(tonumber(target[1]) or 0,
                tonumber(target[2]) or 0, tonumber(target[3]) or 0)
        end
        local inst = target
        if type(target) == "string" then inst = resolvePath(target) end
        if typeof(inst) == "Instance" then
            if inst:IsA("BasePart") then return inst.Position end
            if inst:IsA("Model") then return inst:GetPivot().Position end
            local pp = inst:FindFirstAncestorWhichIsA("BasePart")
            if pp then return pp.Position end
        end
        return nil
    end
    local function timelineSince(since_t)
        local out = {}
        for _, e in ipairs(TIMELINE) do
            if not since_t or e.t >= since_t then out[#out + 1] = e end
        end
        while #out > 200 do table.remove(out, 1) end
        return out
    end
    local function nowT()
        return math.floor((os.clock() - T0) * 100 + 0.5) / 100
    end
    local function doWalk(target, timeoutSec)
        local char, errc = getChar(5)
        if not char then return { ok = false, reason = errc } end
        local dest = targetPos(target)
        if not dest then return { ok = false, reason = "unresolvable target" } end
        local deadline = os.clock() + math.clamp(tonumber(timeoutSec) or 30, 5, 60)
        ev("walk_start", { dest = { math.floor(dest.X), math.floor(dest.Y),
                                    math.floor(dest.Z) } })
        local repaths = 0
        while os.clock() < deadline do
            char = getChar(2)
            if not char then return { ok = false, reason = "lost character" } end
            local hrp = char.HumanoidRootPart
            local hum = char:FindFirstChildOfClass("Humanoid")
            if (hrp.Position - dest).Magnitude < 6 then
                ev("walk_arrived", {})
                return { ok = true, dist = (hrp.Position - dest).Magnitude,
                         repaths = repaths }
            end
            local path = Pathfind2:CreatePath({
                AgentRadius = 2.5, AgentHeight = 5, AgentCanJump = true })
            local okc = pcall(function()
                path:ComputeAsync(hrp.Position, dest)
            end)
            if not okc or path.Status ~= Enum.PathStatus.Success then
                hum:MoveTo(dest)
                local before = hrp.Position
                task.wait(2)
                char = getChar(2)
                if not char then return { ok = false, reason = "lost character" } end
                if (char.HumanoidRootPart.Position - before).Magnitude < 1.5 then
                    return { ok = false,
                             reason = "no path and direct walk stuck",
                             at = { math.floor(before.X), math.floor(before.Y),
                                    math.floor(before.Z) } }
                end
            else
                for _, wp in ipairs(path:GetWaypoints()) do
                    char = getChar(2)
                    if not char then return { ok = false, reason = "lost character" } end
                    hum = char:FindFirstChildOfClass("Humanoid")
                    if wp.Action == Enum.PathWaypointAction.Jump then
                        hum.Jump = true
                    end
                    hum:MoveTo(wp.Position)
                    local before = char.HumanoidRootPart.Position
                    local reached = hum.MoveToFinished:Wait()
                    if os.clock() > deadline then
                        return { ok = false, reason = "timeout mid-path" }
                    end
                    if not reached and
                        (char.HumanoidRootPart.Position - before).Magnitude < 1 then
                        repaths += 1
                        if repaths > 5 then
                            return { ok = false, reason = "stuck (5 re-paths)" }
                        end
                        break
                    end
                end
            end
        end
        return { ok = false, reason = "timeout" }
    end
    -- p58: mouse. A mouse button is a real input event at a screen point
    -- (default: the middle of the screen, where a locked cursor sits).
    local MOUSE_BUTTONS = {
        mousebutton1 = Enum.UserInputType.MouseButton1, mouseleftbutton = Enum.UserInputType.MouseButton1,
        leftclick = Enum.UserInputType.MouseButton1, left = Enum.UserInputType.MouseButton1,
        mousebutton2 = Enum.UserInputType.MouseButton2, mouserightbutton = Enum.UserInputType.MouseButton2,
        rightclick = Enum.UserInputType.MouseButton2, right = Enum.UserInputType.MouseButton2,
        mousebutton3 = Enum.UserInputType.MouseButton3, mousemiddlebutton = Enum.UserInputType.MouseButton3,
        middle = Enum.UserInputType.MouseButton3,
    }
    local function mousePoint(x, y)
        local nx, ny = tonumber(x), tonumber(y)
        if nx and ny then return Vector2.new(nx, ny), true end
        local cam = workspace.CurrentCamera
        local vp = cam and cam.ViewportSize or Vector2.new(800, 600)
        return Vector2.new(math.floor(vp.X / 2), math.floor(vp.Y / 2)), false
    end
    local function doMouse(buttonName, holdSec, x, y)
        local btn = MOUSE_BUTTONS[string.lower(tostring(buttonName or "left"))]
        if not btn then
            return { ok = false, reason = "unknown mouse button " .. tostring(buttonName) }
        end
        local okv, vi = pcall(function() return UIS2:CreateVirtualInput() end)
        if not okv or not vi then
            return { ok = false, reason = "CreateVirtualInput failed: " .. tostring(vi) }
        end
        local pt, given = mousePoint(x, y)
        local ok2, e2 = pcall(function()
            if given and UIS2.MouseBehavior == Enum.MouseBehavior.Default then
                vi:SendMousePosition(pt)
                task.wait(0.05)
            end
            vi:SendMouseButton(pt, btn, true)
            task.wait(math.clamp(tonumber(holdSec) or 0.1, 0.02, 5))
            vi:SendMouseButton(pt, btn, false)
        end)
        return { ok = ok2, err = if ok2 then nil else tostring(e2), mouse = true,
                 at = { pt.X, pt.Y } }
    end
    local function doMouseMove(a)
        local okv, vi = pcall(function() return UIS2:CreateVirtualInput() end)
        if not okv or not vi then
            return { ok = false, reason = "CreateVirtualInput failed: " .. tostring(vi) }
        end
        local locked = UIS2.MouseBehavior ~= Enum.MouseBehavior.Default
        local ok2, e2 = pcall(function()
            if tonumber(a.dx) or tonumber(a.dy) then
                -- turning the camera: only possible while the game holds the cursor
                vi:SendMouseDelta(Vector2.new(tonumber(a.dx) or 0, tonumber(a.dy) or 0))
            else
                vi:SendMousePosition((mousePoint(a.x, a.y)))
            end
        end)
        return { ok = ok2, err = if ok2 then nil else tostring(e2), mouse = true,
                 cursor_locked = locked }
    end
    local function doPress(keyName, holdSec, x, y)
        if MOUSE_BUTTONS[string.lower(tostring(keyName or ""))] then
            return doMouse(keyName, holdSec, x, y)
        end
        local kc = Enum.KeyCode[tostring(keyName or "E")]
        if not kc then
            return { ok = false, reason = "unknown key " .. tostring(keyName) }
        end
        local okv, vi = pcall(function() return UIS2:CreateVirtualInput() end)
        if not okv or not vi then
            return { ok = false, reason = "CreateVirtualInput failed: " .. tostring(vi) }
        end
        local ok2, e2 = pcall(function()
            vi:SendKey(true, kc)
            task.wait(math.clamp(tonumber(holdSec) or 0.1, 0.02, 5))
            vi:SendKey(false, kc)
        end)
        return { ok = ok2, err = if ok2 then nil else tostring(e2) }
    end

    -- verbs ------------------------------------------------------------------
    local VERBS = {}
    function VERBS.snapshot(_a)
        local out = { t = nowT(), is_server = RunService:IsServer(),
                      is_client = RunService:IsClient() }
        pcall(function()
            local lp = anyPlayer()
            out.player = lp and lp.Name or nil
            out.player_count = #Players2:GetPlayers()
            local c = lp and lp.Character
            if c and c:FindFirstChild("HumanoidRootPart") then
                local p = c.HumanoidRootPart.Position
                out.char_pos = { math.floor(p.X + 0.5), math.floor(p.Y + 0.5),
                                 math.floor(p.Z + 0.5) }
            end
        end)
        return out
    end
    function VERBS.find(a)
        local root = workspace
        if type(a.root) == "string" and a.root ~= "" then
            root = resolvePath(a.root) or workspace
        end
        local needle = string.lower(tostring(a.name or ""))
        if needle == "" then return { ok = false, reason = "args.name required" } end
        local out = {}
        for _, inst in ipairs(root:GetDescendants()) do
            if #out >= 20 then break end
            if (not a.class or (pcall(function() return inst:IsA(a.class) end)
                    and inst:IsA(a.class)))
                and string.find(string.lower(inst.Name), needle, 1, true) then
                local pos = nil
                pcall(function()
                    local p
                    if inst:IsA("BasePart") then p = inst.Position
                    elseif inst:IsA("Model") then p = inst:GetPivot().Position
                    else
                        local pp = inst:FindFirstAncestorWhichIsA("BasePart")
                        p = pp and pp.Position or nil
                    end
                    if p then pos = { math.floor(p.X + 0.5),
                        math.floor(p.Y + 0.5), math.floor(p.Z + 0.5) } end
                end)
                out[#out + 1] = { path = inst:GetFullName(),
                                  class = inst.ClassName, pos = pos }
            end
        end
        return out
    end
    function VERBS.props(a)
        local inst, errp = resolvePath(a.path or a.target or "")
        if not inst then return { ok = false, reason = errp } end
        local out = { ok = true, path = inst:GetFullName(),
                      class = inst.ClassName }
        for _, k in ipairs({ "Name", "Anchored", "CanCollide", "CanTouch",
            "Transparency", "Position", "Size", "AssemblyLinearVelocity",
            "ActionText", "ObjectText", "HoldDuration",
            "MaxActivationDistance", "RequiresLineOfSight", "Enabled",
            "Exclusivity", "KeyboardKeyCode", "Value", "Text", "Visible" }) do
            pcall(function()
                local v = (inst :: any)[k]
                if v ~= nil and type(v) ~= "function" then
                    out[k] = tostring(v)
                end
            end)
        end
        local attrs = {}
        pcall(function()
            for k, v in pairs(inst:GetAttributes()) do attrs[k] = tostring(v) end
        end)
        out.attributes = attrs
        return out
    end
    function VERBS.walk(a)
        return doWalk(a.target or a.path, a.timeout)
    end
    function VERBS.press(a)
        return doPress(a.key, a.hold, a.x, a.y)
    end
    function VERBS.click(a)
        return doMouse(a.button or "left", a.hold, a.x, a.y)
    end
    function VERBS.mouse_move(a)
        return doMouseMove(a)
    end
    function VERBS.jump(_a)
        local c, e = getChar(3)
        if not c then return { ok = false, reason = e } end
        c:FindFirstChildOfClass("Humanoid").Jump = true
        return { ok = true }
    end
    function VERBS.timeline(a)
        return timelineSince(tonumber(a.since))
    end
    function VERBS.interact(a)
        local prompt = a.prompt or a.target
        if type(prompt) == "string" then prompt = resolvePath(prompt) end
        if typeof(prompt) ~= "Instance" or not prompt:IsA("ProximityPrompt") then
            return { ok = false, reason = "prompt path did not resolve to a ProximityPrompt" }
        end
        local w = doWalk(prompt, a.timeout)
        if not w.ok then
            return { ok = false, reason = "walk failed: " .. tostring(w.reason) }
        end
        local char = getChar(3)
        local pp = targetPos(prompt)
        if char and pp then
            local hrp = char.HumanoidRootPart
            local maxd = tonumber(prompt.MaxActivationDistance) or 10
            if (hrp.Position - pp).Magnitude > maxd * 0.5 then
                local hum = char:FindFirstChildOfClass("Humanoid")
                hum:MoveTo(pp + (hrp.Position - pp).Unit * math.min(3, maxd * 0.35))
                hum.MoveToFinished:Wait()
            end
        end
        task.wait(0.5)
        local t_arrive = nowT()
        local keyName = "E"
        pcall(function() keyName = prompt.KeyboardKeyCode.Name end)
        if keyName == "Unknown" then keyName = "E" end
        local hold = (tonumber(prompt.HoldDuration) or 0) + 0.4
        local pressed = doPress(keyName, hold)
        task.wait(1.2)
        local tl = timelineSince(t_arrive)
        local triggered = false
        for _, e in ipairs(tl) do
            if e.kind == "prompt_triggered" then triggered = true end
        end
        return { ok = pressed.ok and triggered, key = keyName,
                 held_s = hold, press = pressed,
                 prompt_triggered = triggered, timeline = tl }
    end

    -- vision -----------------------------------------------------------------
    local B64CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
    local function b64encode(buf, len)
        local out = buffer.create(math.ceil(len / 3) * 4)
        local oi, i = 0, 0
        while i + 2 < len do
            local n = buffer.readu8(buf, i) * 65536
                + buffer.readu8(buf, i + 1) * 256 + buffer.readu8(buf, i + 2)
            buffer.writeu8(out, oi,     string.byte(B64CHARS, math.floor(n / 262144) + 1))
            buffer.writeu8(out, oi + 1, string.byte(B64CHARS, math.floor(n / 4096) % 64 + 1))
            buffer.writeu8(out, oi + 2, string.byte(B64CHARS, math.floor(n / 64) % 64 + 1))
            buffer.writeu8(out, oi + 3, string.byte(B64CHARS, n % 64 + 1))
            oi += 4
            i += 3
            if i % 6144 == 0 then task.wait() end
        end
        local rem = len - i
        if rem == 1 then
            local n = buffer.readu8(buf, i) * 65536
            buffer.writeu8(out, oi,     string.byte(B64CHARS, math.floor(n / 262144) + 1))
            buffer.writeu8(out, oi + 1, string.byte(B64CHARS, math.floor(n / 4096) % 64 + 1))
            buffer.writeu8(out, oi + 2, 61)
            buffer.writeu8(out, oi + 3, 61)
            oi += 4
        elseif rem == 2 then
            local n = buffer.readu8(buf, i) * 65536
                + buffer.readu8(buf, i + 1) * 256
            buffer.writeu8(out, oi,     string.byte(B64CHARS, math.floor(n / 262144) + 1))
            buffer.writeu8(out, oi + 1, string.byte(B64CHARS, math.floor(n / 4096) % 64 + 1))
            buffer.writeu8(out, oi + 2, string.byte(B64CHARS, math.floor(n / 64) % 64 + 1))
            buffer.writeu8(out, oi + 3, 61)
            oi += 4
        end
        return buffer.tostring(out)
    end
    function VERBS.map(a)
        local res  = math.clamp(math.floor(tonumber(a.res) or 40), 8, 64)
        local half = math.clamp(tonumber(a.half) or 60, 10, 512)
        local char = getChar(1)
        local cx, cz = 0, 0
        if type(a.center) == "table" then
            cx = tonumber(a.center[1]) or 0
            cz = tonumber(a.center[2]) or 0
        elseif char then
            local p = char.HumanoidRootPart.Position
            cx, cz = p.X, p.Z
        end
        local params = RaycastParams.new()
        params.FilterType = Enum.RaycastFilterType.Exclude
        params.FilterDescendantsInstances = char and { char } or {}
        params.RespectCanCollide = true
        local names, nameIdx, rows = {}, {}, {}
        local step = 2 * half / res
        for iy = 0, res - 1 do
            local row = {}
            for ix = 0, res - 1 do
                local wx = cx - half + (ix + 0.5) * step
                local wz = cz - half + (iy + 0.5) * step
                local hit = workspace:Raycast(Vector3.new(wx, 500, wz),
                    Vector3.new(0, -1000, 0), params)
                if hit and hit.Instance then
                    local nm = hit.Instance.Name
                    local idx = nameIdx[nm]
                    if not idx then
                        names[#names + 1] = nm
                        idx = #names
                        nameIdx[nm] = idx
                    end
                    local c = hit.Instance.Color or Color3.new(0.5, 0.5, 0.5)
                    row[#row + 1] = { idx, math.floor(hit.Position.Y + 0.5),
                        math.floor(c.R * 255), math.floor(c.G * 255),
                        math.floor(c.B * 255) }
                else
                    row[#row + 1] = 0
                end
            end
            rows[#rows + 1] = row
            if iy % 8 == 7 then task.wait() end
        end
        local out = { ok = true, center = { math.floor(cx), math.floor(cz) },
                      half = half, res = res, names = names, rows = rows }
        if char then
            local p = char.HumanoidRootPart.Position
            out.char = { math.floor(p.X * 10) / 10, math.floor(p.Y * 10) / 10,
                         math.floor(p.Z * 10) / 10 }
        end
        return out
    end
    function VERBS.povshot(a)
        local w = math.clamp(math.floor(tonumber(a.w) or 240), 32, 480)
        local h = math.clamp(math.floor(tonumber(a.h) or 135), 32, 270)
        local fov = math.rad(math.clamp(tonumber(a.fov) or 70, 20, 120))
        local fromV, atV
        if type(a.from) == "table" then
            fromV = Vector3.new(tonumber(a.from[1]) or 0,
                tonumber(a.from[2]) or 0, tonumber(a.from[3]) or 0)
        end
        if type(a.at) == "table" then
            atV = Vector3.new(tonumber(a.at[1]) or 0,
                tonumber(a.at[2]) or 0, tonumber(a.at[3]) or 0)
        end
        if not fromV or not atV then
            local char = getChar(2)
            if not char then
                return { ok = false, reason = "no character and no from/at given" }
            end
            local hrp = char.HumanoidRootPart
            atV = atV or (hrp.Position + Vector3.new(0, 1.5, 0))
            fromV = fromV or (hrp.Position - hrp.CFrame.LookVector * 10
                + Vector3.new(0, 5, 0))
        end
        local cam = CFrame.lookAt(fromV, atV)
        local params = RaycastParams.new()
        params.FilterType = Enum.RaycastFilterType.Exclude
        params.FilterDescendantsInstances = {}
        params.RespectCanCollide = false
        local sun = Lighting2:GetSunDirection()
        local aspect = w / h
        local halfTan = math.tan(fov / 2)
        local rgb = buffer.create(w * h * 3)
        local oi = 0
        for py = 0, h - 1 do
            local ny = (1 - 2 * (py + 0.5) / h) * halfTan
            for px = 0, w - 1 do
                local nx = (2 * (px + 0.5) / w - 1) * halfTan * aspect
                local dir = cam:VectorToWorldSpace(Vector3.new(nx, ny, -1)).Unit
                local hit = workspace:Raycast(fromV, dir * 600, params)
                local r, g, b
                if hit and hit.Instance then
                    local okc2, c = pcall(function() return hit.Instance.Color end)
                    if not okc2 or not c then c = Color3.fromRGB(128, 128, 128) end
                    local shade = 0.45 + 0.55 * math.max(0, hit.Normal:Dot(sun))
                    local fade = math.clamp(1 - (hit.Distance / 600) * 0.45, 0.55, 1)
                    local k = shade * fade * 255
                    r = math.floor(math.clamp(c.R * k, 0, 255))
                    g = math.floor(math.clamp(c.G * k, 0, 255))
                    b = math.floor(math.clamp(c.B * k, 0, 255))
                else
                    local t = math.clamp((ny / halfTan) * 0.5 + 0.5, 0, 1)
                    r = math.floor(196 - 90 * t)
                    g = math.floor(220 - 62 * t)
                    b = math.floor(240 - 8 * t)
                end
                buffer.writeu8(rgb, oi, r)
                buffer.writeu8(rgb, oi + 1, g)
                buffer.writeu8(rgb, oi + 2, b)
                oi += 3
            end
            if py % 8 == 7 then task.wait() end
        end
        return { ok = true, w = w, h = h, fmt = "rgb8_b64",
                 b64 = b64encode(rgb, w * h * 3), via = "raycast_pov",
                 cam = { math.floor(fromV.X), math.floor(fromV.Y),
                         math.floor(fromV.Z) } }
    end
    function VERBS.end_session(_a)
        local ok, err = pcall(function()
            game:GetService("StudioTestService"):EndTest({ by = "driver" })
        end)
        return { ok = ok, err = if ok then nil else tostring(err),
                 summary = ok and "play session ending; Studio returns to edit mode"
                     or nil }
    end

    -- session config + auto-stop (only for driver-launched sessions) --------
    task.spawn(function()
        local cfg = nil
        pcall(function() cfg = plugin:GetSetting(PT2_SETTING) end)
        if type(cfg) ~= "table" or type(cfg.max_s) ~= "number" then return end
        if os.time() - (tonumber(cfg.at) or 0) > cfg.max_s + 120 then return end
        task.wait(cfg.max_s)
        pcall(function()
            game:GetService("StudioTestService"):EndTest({ by = "auto_stop" })
        end)
    end)

    -- driver poll loop (ctx=play lane) ---------------------------------------
    task.spawn(function()
        -- e2e 2026-08-16: Studio loads the plugin TWICE inside a play
        -- session (server VM + client VM). Only the server copy may drive:
        -- prompt_triggered (the interact oracle) fires server-side, and two
        -- pollers on one lane just race each other for claims.
        if not RunService:IsServer() then return end
        -- plugin_state.api_key is populated from settings by top-level code
        -- far BELOW this block, and task.spawn runs synchronously up to the
        -- first yield — a one-shot emptiness check here always sees "" and
        -- kills the driver at boot. Wait for the key instead.
        local keyDeadline = os.clock() + 30
        while tostring(plugin_state.api_key or "") == "" do
            if os.clock() > keyDeadline then return end
            task.wait(0.25)
        end
        print("[Pipeline] playtest driver alive (interactive session lane)")
        local failures = 0
        while true do
            if not RunService:IsRunning() then return end
            local ok, resp = pcall(function()
                return HttpService:RequestAsync({
                    Url     = BASE_URL .. "/v5/poll?batch=2&ctx=play",
                    Method  = "GET",
                    Headers = v5_headers(),
                    Timeout = POLL_HTTP_TIMEOUT_S,
                })
            end)
            if not ok or not resp or resp.StatusCode ~= 200 then
                failures += 1
                task.wait(math.min(2 + failures, 15))
            else
                failures = 0
                local data = nil
                pcall(function() data = HttpService:JSONDecode(resp.Body) end)
                local work = (type(data) == "table" and type(data.work) == "table")
                    and data.work or {}
                for _, item in ipairs(work) do
                    local call_id = tostring(item.call_id or "")
                    if call_id ~= "" then
                        v5_ack(call_id)
                        task.spawn(function()
                            local input = type(item.input) == "table" and item.input or {}
                            local verb = tostring(input.verb or "")
                            local args = type(input.args) == "table" and input.args or {}
                            local okv, res = pcall(function()
                                local fn = VERBS[verb]
                                if not fn then
                                    error("unknown verb '" .. verb
                                        .. "' — have: snapshot, find, props, "
                                        .. "walk, interact, press, jump, map, "
                                        .. "povshot, timeline, end_session")
                                end
                                return fn(args)
                            end)
                            if okv then
                                v5_post_result(call_id, true, res, "playtest_act")
                            else
                                v5_post_result(call_id, false, {
                                    error      = tostring(res),
                                    error_code = "playtest_verb_error",
                                }, "playtest_act")
                            end
                        end)
                    end
                end
            end
        end
    end)

    end -- if RunService:IsRunning()
end

-- run_playtest  (V4 ref: pisces_web_plugin.lua:1469-1598)
-- Phase 1: minimal implementation — runs Play Solo via StudioTestService,
-- captures console output, returns error count. Not all Studio builds expose
-- StudioTestService.ExecutePlayModeAsync; we degrade gracefully.
-- p55 (2026-10-25): one PISCES_ASSERT line -> passed? The verdict FIELD
-- decides. The playtesting skill's own format is
-- PISCES_ASSERT|name|<true/false>|expected=..|actual=.., and the old substring
-- rule ("=FALSE" anywhere) failed every PASSING check whose expected/actual
-- was false (codebench: a correct canTouch=false came back as a failed
-- assert). Same rule as the server recount (loop._pt_assert_passed).
local _PT_PASS_WORDS = { ["true"] = true, pass = true, passed = true, ok = true, yes = true, ["1"] = true }
local _PT_FAIL_WORDS = { ["false"] = true, fail = true, failed = true, no = true, ["0"] = true }
local function _ptAssertPassed(line)
    local i = line:find("PISCES_ASSERT", 1, true)
    local body = i and line:sub(i + 13) or line
    if body:sub(1, 1) == "|" then
        local fields = string.split(body:sub(2), "|")
        if #fields >= 2 then
            local v = fields[2]:match("^%s*(.-)%s*$"):lower()
            if _PT_PASS_WORDS[v] then return true end
            if _PT_FAIL_WORDS[v] then return false end
        end
    end
    local w = body:match("^[%s:|]*([^%s]+)")
    if w then
        w = w:gsub("[:|,%.]+$", ""):lower()
        if _PT_PASS_WORDS[w] then return true end
        if _PT_FAIL_WORDS[w] then return false end
    end
    local upper = line:upper()
    return not (upper:find("|FALSE", 1, true) or upper:find("FAIL", 1, true)
        or upper:find("=FALSE", 1, true) or upper:find("= FALSE", 1, true))
end

local function run_playtest(input)
    -- p29 (2026-07-02): COORDINATE-DRIVEN NAVIGATION. visit_targets is a list
    -- of places the avatar must physically WALK to during the run — each entry
    -- a full instance path string ("Workspace.ShopNPC"), a {x,y,z} coordinate,
    -- or {path=..., x/y/z=...} (embedded editor-time coords as fallback for
    -- paths that fail to resolve inside the play copy). A built-in
    -- PathfindingService navigator drives the character to each in order,
    -- fires any ProximityPrompt it arrives at, and prints one structured
    -- PISCES_NAV:: line per target that the result assembly decodes — so
    -- "did the player actually get there?" is a measured fact, not a guess.
    local navTargets = {}
    do
        local raw = input.visit_targets or input.nav_targets or input.waypoints
        if type(raw) == "table" then
            for i, t in ipairs(raw) do
                if #navTargets >= 8 then break end
                if type(t) == "string" and t ~= "" then
                    table.insert(navTargets, { label = t, path = t })
                elseif type(t) == "table" then
                    local entry = {}
                    entry.path = (type(t.path) == "string" and t.path ~= "") and t.path
                        or ((type(t.target) == "string" and t.target ~= "") and t.target or nil)
                    local x = tonumber(t.x or (t.position and t.position[1]))
                    local y = tonumber(t.y or (t.position and t.position[2]))
                    local z = tonumber(t.z or (t.position and t.position[3]))
                    if x and y and z then entry.x, entry.y, entry.z = x, y, z end
                    entry.label = tostring(t.label or entry.path
                        or (x and ("(" .. x .. "," .. y .. "," .. z .. ")") or ("target" .. i)))
                    if entry.path or entry.x then table.insert(navTargets, entry) end
                end
            end
        end
    end

    -- 2026-05-30: playtests run a REAL 30s play window (user: "make playtests
    -- last 30 seconds like actually playing"). p29: navigation needs walking
    -- time — extend the window ~6s per target, ceiling 60s (still far below
    -- the 240s plugin watchdog / server lease for run_playtest).
    local _dur_base = math.min(math.max(tonumber(input.duration) or 30, 30), 30)
    local duration  = (#navTargets > 0)
        and math.min(_dur_base + 6 * #navTargets, 60) or _dur_base
    local suiteName   = tostring(input.suite_name or "v5_playtest")
    local serverSrc   = tostring(input.harness_server or input.source or "")
    local clientSrc   = tostring(input.harness_client or "")

    if serverSrc == "" then serverSrc = 'print("[Pipeline] Playtest server start")' end
    if clientSrc == "" then clientSrc = 'print("[Pipeline] Playtest client start")' end

    -- p28: a harness with a syntax error burns a whole 30s Play Solo run and
    -- comes back as a confusing runtime failure. Compile-check both up front.
    local synErr = checkLuauSyntax(serverSrc, "harness_server")
        or checkLuauSyntax(clientSrc, "harness_client")
    if synErr then
        return false, {
            error      = "Playtest NOT started - " .. synErr,
            error_code = "harness_syntax_error",
        }, nil, nil
    end

    -- re-entry guard (see _playtestActiveUntil): refuse a second overlapping
    -- playtest instead of entering play mode again and racing the auto-stop.
    local nowClock = os.clock()
    if nowClock < _playtestActiveUntil then
        return false, {
            error      = "a playtest is already running this turn; refusing to "
                .. "start a second one (it would leave Studio stuck in play mode)",
            error_code = "playtest_already_running",
            mode       = "already_running",
        }, nil, nil
    end

    -- rev 01104 (P1): count errors/warnings UNCONDITIONALLY and keep a
    -- head+tail window of console lines. The old single 200-entry cap stopped
    -- BOTH capture and counting — a game that printed 200 Info lines early hid
    -- every later error, so the playtest returned error_count=0 (fake ok).
    -- Errors cluster at the END of a run; the tail ring preserves them.
    -- rev 01105 (P1b): per-line cap + (xN) dedup + entry-boundary truncation
    -- via the shared _ptNewCapture sink (see header above it).
    local capture = _ptNewCapture(120, 80)
    -- p28: PISCES_ marker lines (asserts, visual probe, done sentinel) are the
    -- structured verdict — collect them RAW in a dedicated side channel so the
    -- head/tail ring and dedup can never drop or mangle them.
    local markers = {}
    -- 2026-07-09 (audit): the re-entry guard (_playtestActiveUntil) and the
    -- MessageOut listener are armed LOWER DOWN — only AFTER every playtest
    -- script has been inserted (see the "arm guard + console listener" block
    -- just before the injected/cleanup table). Arming them here used to strand
    -- BOTH on an injection-denied .Source write below: the write throws before
    -- cleanup() exists, so the guard wedged the whole turn for duration+15s and
    -- the LogService connection leaked. Nothing is emitted between here and
    -- play-mode entry, so deferring the listener misses no console output.

    local serverScript = Instance.new("Script")
    serverScript.Name   = "__PiscesV5PlaytestServer"
    serverScript.Source = serverSrc
    serverScript.Parent = game:GetService("ServerScriptService")

    local clientScript = Instance.new("LocalScript")
    clientScript.Name   = "__PiscesV5PlaytestClient"
    clientScript.Source = clientSrc
    local starterPlayer = game:GetService("StarterPlayer")
    local starterScripts = starterPlayer:FindFirstChild("StarterPlayerScripts") or starterPlayer
    clientScript.Parent = starterScripts

    -- p28: AUTO VISUAL PROBE (ported from web plugin v8.9/v9.0). A headless
    -- playtest asserts state but renders no frame the AI can see — a black
    -- screen (opaque full-screen GUI, camera staring at sky) passed every
    -- scripted check. And a harness that fires remotes directly instead of
    -- driving the character LOOKS like nothing happened to the watching user.
    -- The probe tracks the avatar the whole run (distance moved, Tools
    -- equipped), then late in the session samples camera/view/GUI state and
    -- prints ONE structured PISCES_VISUAL:: line the result assembly decodes.
    local probeAt = math.max(duration - 4, 3)
    local probeScript = Instance.new("LocalScript")
    probeScript.Name = "__PiscesV5VisualProbe"
    probeScript.Source = ''
        .. 'local __t0 = os.clock()\n'
        .. 'local __probeAt = ' .. tostring(probeAt) .. '\n'
        .. 'local __moved = 0\n'
        .. 'local __tools = {}\n'
        .. 'task.spawn(function()\n'
        .. '    pcall(function()\n'
        .. '        local Players = game:GetService("Players")\n'
        .. '        local lp = Players.LocalPlayer\n'
        .. '        local char = lp.Character or lp.CharacterAdded:Wait()\n'
        .. '        for _, c in ipairs(char:GetChildren()) do\n'
        .. '            if c:IsA("Tool") then __tools[c.Name] = true end\n'
        .. '        end\n'
        .. '        char.ChildAdded:Connect(function(c)\n'
        .. '            if c:IsA("Tool") then __tools[c.Name] = true end\n'
        .. '        end)\n'
        .. '        local hrp = char:WaitForChild("HumanoidRootPart", 5)\n'
        .. '        if hrp then\n'
        .. '            local sp = hrp.Position\n'
        .. '            while os.clock() - __t0 < __probeAt - 0.3 do\n'
        .. '                task.wait(0.25)\n'
        .. '                local okd, d = pcall(function() return (hrp.Position - sp).Magnitude end)\n'
        .. '                if okd and d > __moved then __moved = d end\n'
        .. '            end\n'
        .. '        end\n'
        .. '    end)\n'
        .. 'end)\n'
        -- rev p34: fire the sample EARLY when the harness prints its DONE
        -- sentinel (client-side LogService sees client prints), so an
        -- early-exiting playtest still gets a visual payload.
        .. 'local __doneSeen = false\n'
        .. 'pcall(function()\n'
        .. '    game:GetService("LogService").MessageOut:Connect(function(m)\n'
        .. '        if tostring(m):find("PISCES_PLAYTEST_DONE", 1, true) then __doneSeen = true end\n'
        .. '    end)\n'
        .. 'end)\n'
        .. 'while os.clock() - __t0 < __probeAt and not __doneSeen do task.wait(0.25) end\n'
        .. 'local ok, err = pcall(function()\n'
        .. '    local Players = game:GetService("Players")\n'
        .. '    local HttpService = game:GetService("HttpService")\n'
        .. '    local camera = workspace.CurrentCamera\n'
        .. '    local payload = {}\n'
        .. '    local lp = Players.LocalPlayer\n'
        .. '    if camera then\n'
        .. '        local p = camera.CFrame.Position\n'
        .. '        payload.camera = { type = tostring(camera.CameraType.Name),\n'
        .. '            position = { math.floor(p.X + 0.5), math.floor(p.Y + 0.5), math.floor(p.Z + 0.5) },\n'
        .. '            fov = math.floor(camera.FieldOfView + 0.5) }\n'
        .. '        local vs = camera.ViewportSize\n'
        .. '        local params = RaycastParams.new()\n'
        .. '        params.FilterType = Enum.RaycastFilterType.Exclude\n'
        .. '        if lp and lp.Character then params.FilterDescendantsInstances = { lp.Character } end\n'
        .. '        local hits, sky = {}, 0\n'
        .. '        for iy = 1, 3 do\n'
        .. '            for ix = 1, 3 do\n'
        .. '                local ray = camera:ViewportPointToRay(vs.X * (ix - 0.5) / 3, vs.Y * (iy - 0.5) / 3)\n'
        .. '                local r = workspace:Raycast(ray.Origin, ray.Direction * 1000, params)\n'
        .. '                if r and r.Instance then\n'
        .. '                    if #hits < 6 then table.insert(hits, r.Instance.Name .. " @" .. math.floor(r.Distance + 0.5) .. "s") end\n'
        .. '                else\n'
        .. '                    sky = sky + 1\n'
        .. '                end\n'
        .. '            end\n'
        .. '        end\n'
        .. '        payload.view = { sky_rays = sky, total_rays = 9, sees = hits }\n'
        .. '    end\n'
        .. '    local occluders = {}\n'
        .. '    local pg = lp and lp:FindFirstChildOfClass("PlayerGui")\n'
        .. '    if pg and camera then\n'
        .. '        local vs = camera.ViewportSize\n'
        .. '        for _, d in ipairs(pg:GetDescendants()) do\n'
        .. '            if d:IsA("GuiObject") and d.Visible\n'
        .. '                and d.AbsoluteSize.X >= vs.X * 0.9 and d.AbsoluteSize.Y >= vs.Y * 0.9 then\n'
        .. '                local sg = d:FindFirstAncestorOfClass("ScreenGui")\n'
        .. '                local shown = (sg == nil) or sg.Enabled\n'
        .. '                local opaque = false\n'
        .. '                pcall(function() opaque = d.BackgroundTransparency <= 0.05 end)\n'
        .. '                if not opaque and d:IsA("ImageLabel") then\n'
        .. '                    pcall(function() opaque = d.ImageTransparency <= 0.05 and d.Image ~= "" end)\n'
        .. '                end\n'
        .. '                if shown and opaque then\n'
        .. '                    table.insert(occluders, d:GetFullName())\n'
        .. '                    if #occluders >= 5 then break end\n'
        .. '                end\n'
        .. '            end\n'
        .. '        end\n'
        .. '    end\n'
        .. '    payload.fullscreen_opaque_guis = occluders\n'
        .. '    local toolNames = {}\n'
        .. '    for n in pairs(__tools) do table.insert(toolNames, n) end\n'
        .. '    payload.avatar = { moved_studs = math.floor(__moved + 0.5), tools_equipped = toolNames }\n'
        .. '    print("PISCES_VISUAL::" .. HttpService:JSONEncode(payload))\n'
        .. 'end)\n'
        .. 'if not ok then print("PISCES_VISUAL_FAIL::" .. tostring(err)) end\n'
    probeScript.Parent = starterScripts

    -- p29: NAVIGATOR — walks the avatar to each visit_target in order using
    -- PathfindingService (falls back to a straight MoveTo when no path
    -- computes), triggers ProximityPrompts on arrival, and prints one
    -- PISCES_NAV:: JSON line per target. Injected only when targets exist.
    local navScript = nil
    if #navTargets > 0 then
        -- Editor-time position enrichment: resolve each path NOW and embed the
        -- coordinates as a fallback — the play copy usually resolves the same
        -- path, but a script-created/renamed instance might not exist yet.
        for _, t in ipairs(navTargets) do
            if t.path and not t.x then
                local inst = findInstanceByPath(t.path)
                if inst then
                    local okp, pos = pcall(function()
                        if inst:IsA("BasePart") then return inst.Position end
                        if inst:IsA("Model") then return inst:GetPivot().Position end
                        local pp = inst:FindFirstAncestorWhichIsA("BasePart")
                        local fp = inst:FindFirstChildWhichIsA("BasePart", true)
                        return (pp and pp.Position) or (fp and fp.Position) or nil
                    end)
                    if okp and pos then
                        t.x = math.floor(pos.X * 10 + 0.5) / 10
                        t.y = math.floor(pos.Y * 10 + 0.5) / 10
                        t.z = math.floor(pos.Z * 10 + 0.5) / 10
                    end
                end
            end
        end
        local targetsJson = HttpService:JSONEncode(navTargets)
        -- Long-bracket safety: JSON can contain "]]"; level-3 bracket + strip
        -- any accidental terminator from user-controlled path text.
        targetsJson = targetsJson:gsub("%]===%]", "")
        navScript = Instance.new("LocalScript")
        navScript.Name = "__PiscesV5Navigator"
        navScript.Source = ''
            .. 'local HttpService = game:GetService("HttpService")\n'
            .. 'local Players = game:GetService("Players")\n'
            .. 'local PathfindingService = game:GetService("PathfindingService")\n'
            .. 'local TARGETS = HttpService:JSONDecode([===[' .. targetsJson .. ']===])\n'
            .. 'local DEADLINE = os.clock() + ' .. tostring(math.max(duration - 6, 8)) .. '\n'
            .. 'local function resolve(path)\n'
            .. '    if not path or path == "" then return nil end\n'
            .. '    path = path:gsub("%[%d+%]", ""):gsub("^[Gg]ame%.", "")\n'
            .. '    local cur = nil\n'
            .. '    for seg in path:gmatch("[^%.]+") do\n'
            .. '        if cur == nil then\n'
            .. '            local ok, svc = pcall(function() return game:GetService(seg) end)\n'
            .. '            cur = (ok and svc) or game:FindFirstChild(seg)\n'
            .. '        else\n'
            .. '            cur = cur:FindFirstChild(seg)\n'
            .. '        end\n'
            .. '        if cur == nil then return nil end\n'
            .. '    end\n'
            .. '    return cur\n'
            .. 'end\n'
            .. 'local function posOf(t)\n'
            .. '    local inst = t.path and resolve(t.path) or nil\n'
            .. '    if inst then\n'
            .. '        local ok, p = pcall(function()\n'
            .. '            if inst:IsA("BasePart") then return inst.Position end\n'
            .. '            if inst:IsA("Model") then return inst:GetPivot().Position end\n'
            .. '            local fp = inst:FindFirstChildWhichIsA("BasePart", true)\n'
            .. '            return fp and fp.Position or nil\n'
            .. '        end)\n'
            .. '        if ok and p then return p, inst end\n'
            .. '    end\n'
            .. '    if t.x then return Vector3.new(t.x, t.y or 0, t.z or 0), inst end\n'
            .. '    return nil, inst\n'
            .. 'end\n'
            .. 'local lp = Players.LocalPlayer\n'
            .. 'local char = lp.Character or lp.CharacterAdded:Wait()\n'
            .. 'local hum = char:WaitForChild("Humanoid", 10)\n'
            .. 'local hrp = char:WaitForChild("HumanoidRootPart", 10)\n'
            .. 'if not (hum and hrp) then print("PISCES_NAV::" .. HttpService:JSONEncode({error="no character"})) return end\n'
            .. 'task.wait(0.6)\n'
            .. 'for _, t in ipairs(TARGETS) do\n'
            .. '    if os.clock() >= DEADLINE then\n'
            .. '        print("PISCES_NAV::" .. HttpService:JSONEncode({label=t.label, reached=false, reason="out of time"}))\n'
            .. '    else\n'
            .. '        local t0 = os.clock()\n'
            .. '        local targetPos, inst = posOf(t)\n'
            .. '        if not targetPos then\n'
            .. '            print("PISCES_NAV::" .. HttpService:JSONEncode({label=t.label, reached=false, reason="target not found (path did not resolve and no coords given)"}))\n'
            .. '        else\n'
            .. '            local budget = math.min(15, math.max(4, DEADLINE - os.clock() - 1))\n'
            .. '            local walked = false\n'
            .. '            local path = PathfindingService:CreatePath({AgentRadius = 2, AgentHeight = 5, AgentCanJump = true})\n'
            .. '            local okc = pcall(function() path:ComputeAsync(hrp.Position, targetPos) end)\n'
            .. '            if okc and path.Status == Enum.PathStatus.Success then\n'
            .. '                for _, wp in ipairs(path:GetWaypoints()) do\n'
            .. '                    if os.clock() - t0 > budget then break end\n'
            .. '                    if wp.Action == Enum.PathWaypointAction.Jump then hum.Jump = true end\n'
            .. '                    hum:MoveTo(wp.Position)\n'
            .. '                    local done = false\n'
            .. '                    local conn = hum.MoveToFinished:Connect(function() done = true end)\n'
            .. '                    local w0 = os.clock()\n'
            .. '                    while not done and os.clock() - w0 < 3 do task.wait(0.05) end\n'
            .. '                    conn:Disconnect()\n'
            .. '                end\n'
            .. '                walked = true\n'
            .. '            end\n'
            .. '            if not walked then\n'
            .. '                hum:MoveTo(targetPos)\n'
            .. '                local done = false\n'
            .. '                local conn = hum.MoveToFinished:Connect(function() done = true end)\n'
            .. '                local w0 = os.clock()\n'
            .. '                while not done and os.clock() - w0 < budget do task.wait(0.05) end\n'
            .. '                conn:Disconnect()\n'
            .. '            end\n'
            .. '            local dist = (hrp.Position - targetPos).Magnitude\n'
            .. '            local reached = dist <= 8\n'
            .. '            local fired = nil\n'
            .. '            if reached and inst then\n'
            .. '                local prompt = inst:FindFirstChildWhichIsA("ProximityPrompt", true)\n'
            .. '                if prompt then\n'
            .. '                    pcall(function()\n'
            .. '                        prompt:InputHoldBegin()\n'
            .. '                        task.wait((prompt.HoldDuration or 0) + 0.15)\n'
            .. '                        prompt:InputHoldEnd()\n'
            .. '                        fired = "ProximityPrompt held"\n'
            .. '                    end)\n'
            .. '                end\n'
            .. '            end\n'
            .. '            print("PISCES_NAV::" .. HttpService:JSONEncode({label=t.label, reached=reached,\n'
            .. '                dist=math.floor(dist * 10 + 0.5) / 10, took=math.floor((os.clock() - t0) * 10 + 0.5) / 10,\n'
            .. '                prompt=fired, pathfound=walked}))\n'
            .. '        end\n'
            .. '    end\n'
            .. 'end\n'
            .. 'print("PISCES_NAV_DONE::1")\n'
        navScript.Parent = starterScripts
    end

    -- 2026-07-09 (audit): every playtest script has now landed. Arm the
    -- re-entry guard and the console listener HERE — never before the inserts.
    -- If any .Source/.Parent write above threw (Studio "Script Injection"
    -- disabled — the dominant prod failure, 11 hits 2026-07-01), run_tool's
    -- pcall catches it and reports script_injection_denied WITHOUT the guard
    -- left wedged for duration+15s or the LogService connection leaked.
    _playtestActiveUntil = os.clock() + duration + 15
    local logConn = LogService.MessageOut:Connect(function(message, messageType)
        capture.feed(message, messageType)
        local msgStr = tostring(message)
        if msgStr:sub(1, 7) == "PISCES_" and #markers < 80 then
            table.insert(markers, msgStr)
        end
    end)

    local injected = { serverScript, clientScript, probeScript }
    if navScript then table.insert(injected, navScript) end
    local function cleanup()
        _playtestActiveUntil = 0   -- release the re-entry guard on any return
        pcall(function() plugin:SetSetting("pisces_pt_arm", false) end)
        pcall(function() logConn:Disconnect() end)
        for _, s in ipairs(injected) do pcall(function() s:Destroy() end) end
    end

    local gotSts, StudioTestService = pcall(function()
        return game:GetService("StudioTestService")
    end)

    if not (gotSts and StudioTestService and StudioTestService.ExecutePlayModeAsync) then
        cleanup()
        return false, {
            error      = "StudioTestService.ExecutePlayModeAsync unavailable in this Studio build",
            error_code = "playtest_service_unavailable",
            mode       = "unavailable",
        }, nil, nil
    end

    local stopScript = Instance.new("Script")
    stopScript.Name   = "__PiscesV5PlaytestAutoStop"
    stopScript.Source = 'task.wait(' .. tostring(duration) .. ')\n'
        .. 'local ok, STS = pcall(function() return game:GetService("StudioTestService") end)\n'
        .. 'if ok and STS and STS.EndTest then pcall(function() STS:EndTest({completed=true}) end) end\n'
    stopScript.Parent = game:GetService("ServerScriptService")
    table.insert(injected, stopScript)

    -- p30: arm the play-session console relay — clear any stale blob and
    -- stamp the window start the freshness gate checks against after the run.
    local ptStartedAt = os.time()
    pcall(function() plugin:SetSetting("pisces_pt_relay", false) end)
    pcall(function() plugin:SetSetting("pisces_pt_relay_c", false) end)
    pcall(function() plugin:SetSetting("pisces_pt_arm_at", ptStartedAt) end)
    pcall(function() plugin:SetSetting("pisces_pt_done", false) end)
    -- p54: tell the play server copy this is a run_playtest window (not the
    -- interactive lane): it then backs up the auto-stop and ends early on DONE.
    pcall(function()
        plugin:SetSetting("pisces_pt_arm", {
            at = ptStartedAt, dur = duration, early = (#navTargets == 0),
        })
    end)

    -- p54 (2026-10-25): ExecutePlayModeAsync YIELDS until the session ends
    -- (EndTest) on current Studio builds, and once in a while it never enters
    -- play at all (L0: second back-to-back run hung past the 150 s tool
    -- deadline, Studio still in Edit). Run it on its own thread and watch it:
    -- no play heartbeat (relay blob) within 35 s = a stuck start, said plainly.
    local playT0 = os.clock()
    local playCallDone, startOk, startErr = false, true, nil
    task.spawn(function()
        local okP, errP = pcall(function()
            StudioTestService:ExecutePlayModeAsync(suiteName)
        end)
        startOk, startErr = okP, errP
        playCallDone = true
    end)
    local function relayFresh()
        local okR, blob = pcall(function()
            return plugin:GetSetting("pisces_pt_relay")
        end)
        return okR and type(blob) == "table"
            and (tonumber(blob.at) or 0) >= ptStartedAt - 1
    end
    local sawPlay, playHung = false, nil
    while not playCallDone do
        task.wait(0.5)
        if not sawPlay and relayFresh() then sawPlay = true end
        local waited = os.clock() - playT0
        if not sawPlay and waited > 35 then playHung = "start"; break end
        if waited > duration + 50 then playHung = "end"; break end
    end
    if not sawPlay and relayFresh() then sawPlay = true end
    if playHung == "start" then
        cleanup()
        return false, {
            error      = "Studio did not enter play mode within 35 s (the play "
                .. "call is stuck), so nothing ran. Try run_playtest once more; "
                .. "if it repeats, ask the user to press Stop in Studio.",
            error_code = "playtest_start_hung",
            mode       = "start_hung",
        }, nil, nil
    end
    -- the call already sat through the whole session: no second wait below
    local blockedThroughPlay = (playCallDone and sawPlay) or playHung == "end"
    if not startOk then
        cleanup()
        return false, {
            error      = "ExecutePlayModeAsync threw: " .. tostring(startErr),
            error_code = "playtest_start_failed",
        }, nil, nil
    end

    -- Brief poll to detect player spawn (info-only)
    local Players = game:GetService("Players")
    local playerSpawned = sawPlay
    for _ = 1, blockedThroughPlay and 0 or 50 do
        task.wait(0.1)
        if #Players:GetPlayers() > 0 then playerSpawned = true; break end
    end

    -- 2026-05-30: wait the FULL duration so the avatar actually plays the
    -- whole window (was duration-2, which cut every playtest ~2s short).
    -- rev p34 (2026-07-10): EARLY EXIT — every July 9-10 prod playtest sat out
    -- the full 30s even when its checks finished in 3. Stop as soon as the
    -- harness prints PISCES_PLAYTEST_DONE (seen via edit-DM markers or the
    -- p30 relay blob, which flushes every 2s), with a 4s grace so the visual
    -- probe (which also fires on DONE) and trailing prints land. Navigation
    -- runs keep the full window — the navigator owns the tail of the run.
    local __earlyOk = (#navTargets == 0)
    local __elapsed = blockedThroughPlay
        and math.floor(os.clock() - playT0 + 0.5) or 0
    local __doneAt = nil
    if blockedThroughPlay and __elapsed < duration then __doneAt = __elapsed end
    while not blockedThroughPlay and __elapsed < duration do
        task.wait(1)
        __elapsed += 1
        if __earlyOk and not __doneAt and __elapsed >= 8 then
            local sawDone = false
            for _, m in ipairs(markers) do
                if m:find("PISCES_PLAYTEST_DONE", 1, true) then sawDone = true; break end
            end
            if not sawDone and __elapsed % 2 == 0 then
                local okR, blob = pcall(function()
                    return plugin:GetSetting("pisces_pt_relay")
                end)
                if okR and type(blob) == "table"
                    and (tonumber(blob.at) or 0) >= ptStartedAt - 5
                    and type(blob.markers) == "table" then
                    for _, m in ipairs(blob.markers) do
                        if type(m) == "string" and m:find("PISCES_PLAYTEST_DONE", 1, true) then
                            sawDone = true; break
                        end
                    end
                end
            end
            if sawDone then __doneAt = __elapsed end
        end
        if __doneAt and __elapsed >= __doneAt + 4 then break end
    end
    pcall(function() if RunService:IsRunning() then RunService:Stop() end end)
    task.wait(0.3)
    cleanup()

    -- p30: CONSOLE RECOVERY LAYERS. If the edit-DM MessageOut listener caught
    -- nothing (the dominant prod case — see relay header above), try two
    -- fallbacks, cheapest first:
    --   1. LogService:GetLogHistory() — on builds that share log history
    --      across DataModels, backfill every line in the playtest window.
    --   2. The play-session relay blob from plugin settings (written by the
    --      plugin instance that ran INSIDE the play session).
    local captureSource = (capture.messages > 0) and "live" or "none"
    if capture.messages == 0 then
        local okH, hist = pcall(function() return LogService:GetLogHistory() end)
        if okH and type(hist) == "table" then
            for _, e in ipairs(hist) do
                if (tonumber(e.timestamp) or 0) >= ptStartedAt - 1 then
                    capture.feed(e.message, e.messageType)
                    local msgStr = tostring(e.message)
                    if msgStr:sub(1, 7) == "PISCES_" and #markers < 80 then
                        table.insert(markers, msgStr)
                    end
                end
            end
            if capture.messages > 0 then captureSource = "log_history" end
        end
    end
    -- p52 (2026-10-25): ALWAYS read the relay. The edit-DM listener often
    -- catches a stray Studio warning but none of the play session's prints,
    -- and the old "only when the listener saw nothing" rule then dropped
    -- every PISCES_ASSERT (L0 run: asserts 0/0 on a passing harness).
    local relayBlob = nil
    for _ = 1, (capture.messages == 0) and 6 or 3 do
        -- the play DM's final flush rides its Unloading teardown; give the
        -- settings write a few beats to land before giving up.
        local okR, blob = pcall(function()
            return plugin:GetSetting("pisces_pt_relay")
        end)
        if okR and type(blob) == "table"
            and (tonumber(blob.at) or 0) >= ptStartedAt - 5
            and (tonumber(blob.output_count) or 0) > 0 then
            relayBlob = blob
            break
        end
        task.wait(0.5)
    end
    -- p53: merge the client play copy's relay (its own key) into the server's
    do
        local okC, cblob = pcall(function()
            return plugin:GetSetting("pisces_pt_relay_c")
        end)
        if okC and type(cblob) == "table"
            and (tonumber(cblob.at) or 0) >= ptStartedAt - 5
            and (tonumber(cblob.output_count) or 0) > 0 then
            if relayBlob == nil then
                relayBlob = cblob
            else
                local m = {}
                for _, x in ipairs(type(relayBlob.markers) == "table" and relayBlob.markers or {}) do
                    table.insert(m, x)
                end
                for _, x in ipairs(type(cblob.markers) == "table" and cblob.markers or {}) do
                    if #m < 80 then table.insert(m, x) end
                end
                relayBlob = {
                    at           = relayBlob.at,
                    console      = tostring(relayBlob.console or "")
                        .. "\n[client]\n" .. tostring(cblob.console or ""),
                    errors       = (tonumber(relayBlob.errors) or 0) + (tonumber(cblob.errors) or 0),
                    warnings     = (tonumber(relayBlob.warnings) or 0) + (tonumber(cblob.warnings) or 0),
                    output_count = (tonumber(relayBlob.output_count) or 0) + (tonumber(cblob.output_count) or 0),
                    markers      = m,
                }
            end
        end
    end
    -- the relay replaces the live capture only when it saw more of the run
    local relayWins = relayBlob ~= nil
        and (tonumber(relayBlob.output_count) or 0) > capture.messages
    if relayWins then captureSource = "play_relay" end

    -- rev 01104 (P1): counts come from the live counters (never capped).
    -- rev 01105 (P1b): render = head + tail ring + entry-boundary truncation.
    local errorCount, warningCount = capture.errors, capture.warnings
    local consoleOut = capture.render(12000, 4000, 8000)
    if relayWins then
        errorCount   = tonumber(relayBlob.errors) or 0
        warningCount = tonumber(relayBlob.warnings) or 0
        consoleOut   = tostring(relayBlob.console or "")
    end
    if relayBlob and type(relayBlob.markers) == "table" then
        -- merge markers either way: the play session's own listener is the
        -- one that hears its prints
        local seenM = {}
        for _, m in ipairs(markers) do seenM[m] = true end
        local added = 0
        for _, m in ipairs(relayBlob.markers) do
            if type(m) == "string" and not seenM[m] and #markers < 80 then
                table.insert(markers, m)
                seenM[m] = true
                added = added + 1
            end
        end
        if added > 0 and not relayWins then
            captureSource = captureSource .. "+relay_markers"
        end
    end

    -- p28: structured verdicts from the raw marker side channel. The model was
    -- eyeballing raw console text and misreading it — pre-count the asserts and
    -- decode the visual probe here, and say it in plain language.
    local assertsPassed, assertsFailed = 0, 0
    local failedAssertLines = {}
    local visualPayload = nil
    local navResults = {}   -- p29: decoded PISCES_NAV:: entries
    local validatorChunks   -- p39: raw PISCES_VALIDATOR:: payload chunks
    for _, msg in ipairs(markers) do
        if msg:find("PISCES_ASSERT", 1, true) then
            if not _ptAssertPassed(msg) then
                assertsFailed = assertsFailed + 1
                if #failedAssertLines < 10 then
                    table.insert(failedAssertLines, msg:sub(1, 300))
                end
            else
                assertsPassed = assertsPassed + 1
            end
        end
        local vIdx = msg:find("PISCES_VISUAL::", 1, true)
        if vIdx then
            local okDecode, decoded = pcall(function()
                return HttpService:JSONDecode(msg:sub(vIdx + 15))
            end)
            if okDecode then visualPayload = decoded end
        end
        -- p29: decode navigator verdicts (one JSON line per visit_target)
        local nIdx = msg:find("PISCES_NAV::", 1, true)
        if nIdx then
            local okNav, navDecoded = pcall(function()
                return HttpService:JSONDecode(msg:sub(nIdx + 12))
            end)
            if okNav and type(navDecoded) == "table" then
                table.insert(navResults, navDecoded)
            end
        end
        -- p39: map-validator payload (may span several chunk lines; they
        -- arrive in print order, so plain concat reassembles the JSON).
        local dIdx = msg:find("PISCES_VALIDATOR::", 1, true)
        if dIdx then
            validatorChunks = validatorChunks or {}
            table.insert(validatorChunks, msg:sub(dIdx + 18))
        end
    end

    local visualSummary = ""
    if visualPayload then
        local bits = {}
        local occl = visualPayload.fullscreen_opaque_guis
        if type(occl) == "table" and #occl > 0 then
            table.insert(bits, "FULL-SCREEN OPAQUE GUI hiding the 3D world: "
                .. table.concat(occl, ", ")
                .. " (anything behind it is invisible - if a 3D/camera backdrop was intended, this element must be transparent)")
        end
        local view = visualPayload.view
        if type(view) == "table" then
            local sky = tonumber(view.sky_rays) or 0
            if sky >= 8 then
                table.insert(bits, "camera is staring at EMPTY SKY/VOID ("
                    .. sky .. "/9 rays hit nothing within 1000 studs - it is not aimed at any scene)")
            elseif type(view.sees) == "table" and #view.sees > 0 then
                table.insert(bits, "camera sees: " .. table.concat(view.sees, ", "))
            end
        end
        if visualPayload.camera and visualPayload.camera.type then
            local cp = visualPayload.camera.position or {}
            table.insert(bits, "camera " .. tostring(visualPayload.camera.type)
                .. " at (" .. table.concat(cp, ", ") .. ")")
        end
        -- Did the character actually DO anything, or did the harness shortcut
        -- past it? The user judges the test by watching the avatar.
        local av = visualPayload.avatar
        if type(av) == "table" then
            local mv = tonumber(av.moved_studs) or 0
            local tl = (type(av.tools_equipped) == "table") and av.tools_equipped or {}
            if mv < 2 and #tl == 0 then
                table.insert(bits, "AVATAR NEVER ACTED: it moved " .. mv
                    .. " studs and equipped no Tool the entire run - if this test involved moving/shooting/interacting, the harness fired code paths directly instead of driving the character (use hum:MoveTo + MoveToFinished, hum:EquipTool(tool) + tool:Activate())")
            else
                local seg = "avatar moved " .. mv .. " studs"
                if #tl > 0 then seg = seg .. ", equipped Tool(s): " .. table.concat(tl, ", ") end
                table.insert(bits, seg)
            end
        end
        if #bits > 0 then visualSummary = "VISUAL PROBE: " .. table.concat(bits, "; ") .. "." end
    end

    -- p29: plain-language navigation verdict. A requested target the avatar
    -- never reached is a REAL test failure signal, phrased so the model acts.
    local navSummary = ""
    local navFailed = 0
    local navReached = 0
    if #navTargets > 0 then
        local bits = {}
        for _, n in ipairs(navResults) do
            if n.label then
                if n.reached then
                    navReached = navReached + 1
                    local seg = "reached " .. tostring(n.label)
                        .. " (" .. tostring(n.took or "?") .. "s"
                    if n.prompt then seg = seg .. ", " .. tostring(n.prompt) end
                    seg = seg .. ")"
                    table.insert(bits, seg)
                else
                    navFailed = navFailed + 1
                    table.insert(bits, "FAILED to reach " .. tostring(n.label)
                        .. (n.reason and (" — " .. tostring(n.reason))
                            or (" — stopped " .. tostring(n.dist or "?") .. " studs away (blocked path / obstacle / unreachable position?)")))
                end
            end
        end
        if #navResults == 0 then
            navFailed = #navTargets
            table.insert(bits, "navigator produced no results — character may "
                .. "never have spawned or the run ended before walking began")
        end
        navSummary = "NAVIGATION (" .. navReached .. "/"
            .. #navTargets .. " targets reached): " .. table.concat(bits, "; ") .. "."
    end

    -- p29 audit: a FAILED ASSERT is a failed test — it must flip ok, not hide
    -- inside a summary the model may skim past. (errorCount / nav already did.)
    local ok = errorCount == 0 and navFailed == 0 and assertsFailed == 0
    local summary = ""
    if assertsPassed + assertsFailed > 0 then
        summary = string.format("ASSERTS: %d passed, %d FAILED.", assertsPassed, assertsFailed)
        if assertsFailed > 0 then
            summary = summary .. " Failed: " .. table.concat(failedAssertLines, " | ")
        end
    end
    if navSummary ~= "" then
        summary = (summary ~= "" and (summary .. " ") or "") .. navSummary
    end
    if visualSummary ~= "" then
        summary = (summary ~= "" and (summary .. " ") or "") .. visualSummary
    end

    local errText = ""
    if errorCount > 0 then
        errText = "playtest captured " .. errorCount .. " error(s)"
    end
    if navFailed > 0 then
        errText = (errText ~= "" and (errText .. "; ") or "")
            .. navFailed .. " visit_target(s) unreachable"
    end
    if assertsFailed > 0 then
        errText = (errText ~= "" and (errText .. "; ") or "")
            .. assertsFailed .. " assert(s) FAILED"
    end

    -- p30: when every layer came back empty, say so — the model (and our
    -- telemetry) must distinguish "game printed nothing" from "capture gap".
    if consoleOut == "" and captureSource == "none" and playerSpawned then
        summary = (summary ~= "" and (summary .. " ") or "")
            .. "NOTE: no console output was captured this run (capture gap, "
            .. "not proof of a clean run) - rely on asserts/visual probe, and "
            .. "treat missing PISCES_ASSERT lines as unverified."
    end

    return ok, {
        mode            = "play_solo",
        duration        = __elapsed,
        duration_requested = duration,
        early_exit      = (__doneAt ~= nil) or nil,
        player_spawned  = playerSpawned,
        error_count     = errorCount,
        warning_count   = warningCount,
        output_count    = relayBlob and (tonumber(relayBlob.output_count) or 0)
            or capture.messages,
        console_capture = captureSource,
        console_output  = consoleOut,
        asserts        = { passed = assertsPassed, failed = assertsFailed,
                           failed_lines = failedAssertLines },
        visual         = visualPayload,
        validator      = validatorChunks
            and table.concat(validatorChunks, "") or nil,
        navigation     = (#navTargets > 0) and navResults or nil,
        summary        = summary,
        error          = errText,
        error_code     = ok and "" or ((errorCount > 0)
            and "playtest_errors_detected"
            or (navFailed > 0 and "playtest_nav_failed"
                or "playtest_asserts_failed")),
    }, nil, nil
end

-- run_test  (V4 ref: pisces_web_plugin.lua:1405-1460)
local function run_test(input)
    local duration    = math.min(math.max(tonumber(input.duration) or 5, 1), 20)
    -- rev 01104 (P13): accept the arg names the model actually emits
    -- (script/test_script/code) — the server remaps too (S14), this is the
    -- belt-and-braces so an old server can't silently run the empty stub.
    local harnessSource = tostring(
        input.harness_server or input.source or input.script
        or input.test_script or input.code or "")
    if harnessSource == "" then harnessSource = 'print("[Pipeline] Test started")' end

    local synErr = checkLuauSyntax(harnessSource, "test harness")
    if synErr then
        return false, { error = "Test NOT started - " .. synErr,
                        error_code = "harness_syntax_error" }, nil, nil
    end

    -- rev 01104 (P1): unconditional error counting + head/tail capture
    -- (same fix as run_playtest — the old 140-entry cap hid late errors).
    -- rev 01105 (P1b): shared capped/deduped capture sink (see _ptNewCapture).
    local capture = _ptNewCapture(80, 60)
    local logConn = LogService.MessageOut:Connect(function(message, messageType)
        capture.feed(message, messageType)
    end)

    local harnessScript = Instance.new("Script")
    harnessScript.Name   = "__PiscesV5TestHarness"
    harnessScript.Source = harnessSource
    harnessScript.Parent = game:GetService("ServerScriptService")

    if RunService:IsRunning() then
        pcall(function() RunService:Stop() end)
        task.wait(0.5)
    end

    local runOk = pcall(function() RunService:Run() end)
    if runOk then
        task.wait(duration)
        pcall(function() RunService:Stop() end)
        task.wait(0.3)
    end

    pcall(function() logConn:Disconnect() end)
    pcall(function() harnessScript:Destroy() end)

    -- rev 01104 (P1): live counter + head/tail console (see run_playtest)
    -- rev 01105 (P1b): entry-boundary render via the shared capture sink.
    local errorCount = capture.errors
    local consoleOut = capture.render(8000, 2500, 5500)

    return errorCount == 0, {
        duration       = duration,
        error_count    = errorCount,
        output_count   = capture.messages,
        console_output = consoleOut,
    }, nil, nil
end

--------------------------------------------------------------------------------
-- delete_instance — V4 parity: tear down a non-script Instance
--------------------------------------------------------------------------------
local function run_delete_instance(input)
    local path = tostring(input.target or input.path or input.instance or
                          input.instance_path or "")
    if path == "" then
        return false, { error = "target path required", error_code = "missing_target" }, nil, nil
    end
    local inst = findInstanceByPath(path)
    if not inst then
        return false, { error = "Instance not found: " .. path, error_code = "not_found" }, nil, nil
    end
    local full = inst:GetFullName()
    ChangeHistoryService:SetWaypoint("Pre-Pipeline Delete: " .. full)
    local ok, err = pcall(function() inst:Destroy() end)
    ChangeHistoryService:SetWaypoint("Pipeline Delete: " .. full)
    if not ok then
        return false, { error = "Delete failed: " .. tostring(err), error_code = "delete_failed" }, nil, nil
    end
    return true, { deleted = full }, nil, nil
end

--------------------------------------------------------------------------------
-- read_properties — inspection (returns current state of an Instance).
-- Critical for the model to verify what's actually on the DataModel before
-- mutating it (e.g. "make this part bigger" needs the current Size).
--------------------------------------------------------------------------------
local _DEFAULT_INSPECT_PROPS = {
    "Name", "ClassName", "Position", "Size", "Orientation",
    "Color", "BrickColor", "Material", "Transparency",
    "Anchored", "CanCollide", "CanQuery", "CanTouch",
    "Value", "Text", "Visible", "Enabled",
    "WalkSpeed", "JumpHeight", "MaxHealth", "Health",
    "Source",
}

local function _serialise_value(t, val)
    if t == "Vector3" then return { val.X, val.Y, val.Z } end
    if t == "Vector2" then return { val.X, val.Y } end
    if t == "Color3"  then
        return { math.floor(val.R * 255 + 0.5),
                 math.floor(val.G * 255 + 0.5),
                 math.floor(val.B * 255 + 0.5) }
    end
    if t == "BrickColor" then return val.Name end
    if t == "EnumItem"   then return tostring(val) end
    if t == "CFrame"     then
        local p = val.Position
        return { p.X, p.Y, p.Z }
    end
    if t == "Instance"   then return val:GetFullName() end
    if t == "string" or t == "number" or t == "boolean" then return val end
    return tostring(val)
end

local function _read_one_instance(path, props_to_read)
    local inst = findInstanceByPath(path)
    if not inst then
        return nil, "Instance not found: " .. path
    end
    local result = {
        path       = inst:GetFullName(),
        class_name = inst.ClassName,
        properties = {},
    }
    if type(props_to_read) ~= "table" or #props_to_read == 0 then
        props_to_read = _DEFAULT_INSPECT_PROPS
    end
    for _, prop_name in ipairs(props_to_read) do
        local pname = tostring(prop_name)
        local ok, val = pcall(function() return inst[pname] end)
        if ok and val ~= nil then
            result.properties[pname] = _serialise_value(typeof(val), val)
        end
    end
    -- p28: surface ATTRIBUTES (custom data lives there; set_property's
    -- attribute fallback writes them — reads must round-trip).
    pcall(function()
        local attrs = inst:GetAttributes()
        if next(attrs) ~= nil then
            local a = {}
            for k, v in pairs(attrs) do a[k] = tostring(v) end
            result.attributes = a
        end
    end)
    -- p34: LIVE CHILDREN. Hierarchy blindness fix — read_properties used to
    -- return only the instance's own props, so the model concluded "empty"
    -- for containers whose children it never saw. Always report the real
    -- child list (name+class, cap 50) plus counts.
    pcall(function()
        local kids = inst:GetChildren()
        result.child_count = #kids
        local listed = {}
        for i, c in ipairs(kids) do
            if i > 50 then break end
            table.insert(listed, { name = c.Name, class = c.ClassName })
        end
        result.children = listed
        if #kids > 50 then
            result.children_truncated = true
        end
        -- descendant count only when cheap (skip huge subtrees like Workspace)
        if #kids <= 200 then
            local ok2, desc = pcall(function() return inst:GetDescendants() end)
            if ok2 and desc then result.descendant_count = #desc end
        end
    end)
    return result, nil
end

local function run_read_properties(input)
    -- p29: BATCH READS. Accept `targets`/`paths` (array of instance paths, max
    -- 20) alongside the single-path form — inspecting a whole build no longer
    -- costs one tool round-trip per instance.
    local multi = input.targets or input.paths
    if type(multi) == "table" and #multi > 0 then
        local results, misses = {}, {}
        for i, p in ipairs(multi) do
            if i > 20 then break end
            local one, _err = _read_one_instance(tostring(p), input.properties)
            if one then
                table.insert(results, one)
            else
                table.insert(misses, tostring(p))
            end
        end
        if #results == 0 then
            return false, { error = "No instances found for any target path: "
                .. table.concat(misses, ", "), error_code = "not_found" }, nil, nil
        end
        local out = { instances = results, count = #results }
        if #misses > 0 then out.not_found = misses end
        return true, out, nil, nil
    end

    local path = tostring(input.target or input.path or input.instance or
                          input.instance_path or "")
    if path == "" then
        return false, { error = "target path required", error_code = "missing_target" }, nil, nil
    end
    local result, err = _read_one_instance(path, input.properties)
    if not result then
        return false, { error = err, error_code = "not_found" }, nil, nil
    end
    -- value_after enables M4 read-back diffing on subsequent set_property
    return true, result, nil, result.properties
end

--------------------------------------------------------------------------------
-- spawn_rig — spawn an R6/R15 humanoid rig that looks like a NORMAL Roblox
-- character (Bright yellow BodyColors + smile face). Tries
-- GetHumanoidDescriptionFromUserId(1) first (canonical default avatar); falls
-- back to a hand-built default if HTTP/InsertService is unavailable.
-- HumanoidRootPart is ALWAYS left unanchored — anchoring it silently disables
-- Humanoid:MoveTo and PathfindingService (the class-of-bug the prompt warns
-- about). Decorative parts honor `anchored=true` for stationary dummies.
--------------------------------------------------------------------------------
local function _build_default_humanoid_description()
    local desc = Instance.new("HumanoidDescription")
    local yellow = BrickColor.new("Bright yellow").Color
    desc.HeadColor     = yellow
    desc.TorsoColor    = yellow
    desc.LeftArmColor  = yellow
    desc.RightArmColor = yellow
    desc.LeftLegColor  = yellow
    desc.RightLegColor = yellow
    desc.Face          = 7074786  -- classic smile
    return desc
end

local function run_spawn_rig(input)
    -- Arg aliases match the server-side _normalize_spawn_rig_args coercion.
    local rigName    = tostring(input.name or input.rig_name or input.instance_name or "Rig")
    local rigType    = tostring(input.rig_type or input.type or "R15"):upper()
    if rigType ~= "R6" and rigType ~= "R15" then rigType = "R15" end
    local parentPath = tostring(input.parent or input.location or input.path or "Workspace")

    local parent = findOrCreateParent(parentPath)
    if not parent then
        return false, { error = "Parent not found: " .. parentPath, error_code = "parent_not_found" }, nil, nil
    end

    -- Idempotency: if a Model with this name already exists under parent and
    -- has a Humanoid child, reuse it. Prevents Zombie/Zombie2/Zombie3 spam
    -- when the harness re-emits across iters.
    local existing = parent:FindFirstChild(rigName)
    if existing and existing:IsA("Model") and existing:FindFirstChildOfClass("Humanoid") then
        local fullPath = existing:GetFullName()
        return true, { path = fullPath, class_name = "Model", reused = true, rig_type = rigType }, nil, fullPath
    end

    ChangeHistoryService:SetWaypoint("Pre-Pipeline Rig: " .. rigName)

    local Players = game:GetService("Players")
    local rigEnum = rigType == "R6" and Enum.HumanoidRigType.R6 or Enum.HumanoidRigType.R15

    local ok, rig = pcall(function()
        -- p40 (owner report 2026-07-22, "severed head"): NEVER clone
        -- userId 1's live avatar. The ROBLOX account now wears an Rthro
        -- "Man" bundle (MeshPart limbs) + "Stevie Standard" DynamicHead;
        -- built by a plugin in Edit mode those bundle body MeshParts do
        -- not render, so rigs spawned as a floating head. The hand-built
        -- classic description is deterministic: blocky R15/R6, yellow
        -- skin, smile face.
        return Players:CreateHumanoidModelFromDescription(
            _build_default_humanoid_description(), rigEnum)
    end)

    if not ok or not rig then
        -- Second-chance with the hand-built default desc.
        local ok2, rig2 = pcall(function()
            return Players:CreateHumanoidModelFromDescription(
                _build_default_humanoid_description(), rigEnum
            )
        end)
        if ok2 and rig2 then rig = rig2; ok = true end
    end

    if not ok or not rig then
        -- Last-resort manual rig (parts-only). Still gives the model a valid
        -- Humanoid so AI scripts that read humanoid don't crash.
        rig = Instance.new("Model")
        local hrp = Instance.new("Part")
        hrp.Name = "HumanoidRootPart"
        hrp.Size = Vector3.new(2, 2, 1)
        hrp.Transparency = 1
        hrp.Anchored = false  -- HARD RULE
        hrp.Parent = rig
        local hum = Instance.new("Humanoid")
        hum.Parent = rig
        rig.PrimaryPart = hrp
    else
        -- NOTE (rev 01135 BUG #1 fix): anchoring is DEFERRED until after the
        -- PivotTo below. A decorative part anchored while the rig is still being
        -- positioned fights the Motor6D solver and yanks the Head off its neck
        -- ("head not spawned in the right place"). Here we only add the face.
        -- If the description didn't apply a Face decal, add the classic smile
        -- so the head isn't blank.
        local head = rig:FindFirstChild("Head")
        if head and not head:FindFirstChildWhichIsA("Decal") then
            local face = Instance.new("Decal")
            face.Name = "face"
            face.Texture = "rbxasset://textures/face.png"
            face.Parent = head
        end
    end

    rig.Name = rigName

    -- rev 01135 BUG #1: PivotTo pivots about PrimaryPart. CreateHumanoidModel-
    -- FromDescription can return the model with PrimaryPart unset, in which case
    -- PivotTo uses the bounding-box center and the rig lands off-target. Pin it
    -- to the HumanoidRootPart so the whole assembly moves predictably.
    if not rig.PrimaryPart then
        local hrp = rig:FindFirstChild("HumanoidRootPart")
        if hrp and hrp:IsA("BasePart") then
            rig.PrimaryPart = hrp
        end
    end

    local pos = input.position
    if type(pos) == "table" and #pos >= 3 then
        local x = tonumber(pos[1]) or 0
        local y = tonumber(pos[2]) or 5
        local z = tonumber(pos[3]) or 0
        pcall(function() rig:PivotTo(CFrame.new(x, y, z)) end)
    end

    -- rev 01135 BUG #1: anchor AFTER the pivot so each part locks at its final,
    -- correct position (the assembly moved as one rigid unanchored unit above).
    -- HumanoidRootPart ALWAYS stays unanchored (HARD RULE) so the Humanoid
    -- assembly stays valid; everything else honors the requested anchored flag.
    do
        local shouldAnchor = coerceBool(input.anchored, false)
        for _, part in ipairs(rig:GetDescendants()) do
            if part:IsA("BasePart") then
                if part.Name == "HumanoidRootPart" then
                    part.Anchored = false
                else
                    part.Anchored = shouldAnchor
                end
            end
        end
    end

    rig.Parent = parent
    ChangeHistoryService:SetWaypoint("Pipeline Rig: " .. rigName)

    local rigPath = rig:GetFullName()
    return true, {
        path       = rigPath,
        class_name = "Model",
        rig_type   = rigType,
    }, nil, rigPath
end

--------------------------------------------------------------------------------
-- stop_playtest — force Studio out of PlayMode so the next request can edit.
-- Harness enqueues this at the start of every user turn (rev 00986 routes.py)
-- so the studio is guaranteed in edit mode regardless of what state the
-- previous run_playtest left it in.
--------------------------------------------------------------------------------
local function run_stop_playtest(_input)
    local wasRunning = false
    pcall(function()
        if RunService:IsRunning() then
            wasRunning = true
            RunService:Stop()
        end
    end)
    if wasRunning then
        pcall(function() task.wait(0.3) end)
    end
    return true, {
        tool        = "stop_playtest",
        was_running = wasRunning,
        summary     = wasRunning
            and "Stopped play mode; Studio is now in edit mode."
            or  "Studio was already in edit mode.",
    }, nil, nil
end

--------------------------------------------------------------------------------
-- generate_mesh — Cube 3D text->3D via GenerationService:GenerateModelAsync.
-- Verified 2026-06-23: GenerateModelAsync is Security:None, capability
-- DynamicGeneration, takes NO Player and has NO "server scripts only" note
-- (unlike GenerateMeshAsync) -> the edit-mode plugin can call it. It yields a
-- few seconds; ALWAYS pcall'd. On ANY failure (capability off, moderation,
-- timeout, edit-mode rejection) it returns a clean error so the model falls
-- back to building with primitives — generation must never break a build.
--------------------------------------------------------------------------------
local function run_generate_mesh(input)
    local prompt = tostring(input.prompt or input.text_prompt or input.description or "")
    if prompt == "" then
        return false, { error = "prompt required (describe the object to generate)", error_code = "missing_prompt" }, nil, nil
    end
    local meshName    = tostring(input.name or input.instance_name or "GeneratedModel")
    local parentPath  = tostring(input.parent or input.location or input.path or "Workspace")
    local schemaName  = tostring(input.schema or input.predefined_schema or "Body1")
    if schemaName ~= "Body1" and schemaName ~= "Car5" then schemaName = "Body1" end

    local parent = findOrCreateParent(parentPath)
    if not parent then
        return false, { error = "Parent not found: " .. parentPath, error_code = "parent_not_found" }, nil, nil
    end

    -- Idempotency: a re-dispatch with the same name reuses the existing model
    -- instead of generating a costly duplicate (GeneratedModel2 spam).
    local existing = parent:FindFirstChild(meshName)
    if existing and (existing:IsA("Model") or existing:IsA("MeshPart"))
        and (existing:IsA("MeshPart") or existing:FindFirstChildWhichIsA("MeshPart", true)) then
        local fullPath = existing:GetFullName()
        local reMesh = existing:IsA("MeshPart") and existing
                    or existing:FindFirstChildWhichIsA("MeshPart", true)
        local rp, rs
        pcall(function() local pv = existing:GetPivot().Position; rp = { pv.X, pv.Y, pv.Z } end)
        pcall(function()
            local sz = existing:IsA("Model") and existing:GetExtentsSize() or existing.Size
            rs = { sz.X, sz.Y, sz.Z }
        end)
        return true, {
            path = fullPath, class_name = existing.ClassName, reused = true, schema = schemaName,
            mesh_part_path = reMesh and reMesh:GetFullName() or nil, pivot = rp, size = rs,
            note = "Already exists (reused, not regenerated). Already placed — do NOT inspect it; move with one set_property(path,'CFrame',...) if needed.",
        }, nil, fullPath
    end

    local gsOk, GenerationService = pcall(function() return game:GetService("GenerationService") end)
    if not (gsOk and GenerationService and GenerationService.GenerateModelAsync) then
        return false, {
            error      = "Cube 3D mesh generation isn't available in this Studio build — build with parts instead.",
            error_code = "generation_unavailable",
        }, nil, nil
    end

    local inputs = { TextPrompt = prompt, GenerateTextures = true }
    local sz = input.size
    if type(sz) == "table" and #sz >= 3 then
        inputs.Size = Vector3.new(tonumber(sz[1]) or 4, tonumber(sz[2]) or 4, tonumber(sz[3]) or 4)
    end
    local maxTris = tonumber(input.max_triangles)
    if maxTris then inputs.MaxTriangles = math.floor(maxTris) end
    local schema = { PredefinedSchema = schemaName }

    ChangeHistoryService:SetWaypoint("Pre-Pipeline GenerateMesh: " .. meshName)

    local genOk, result = pcall(function()
        return GenerationService:GenerateModelAsync(inputs, schema)
    end)

    if not genOk then
        local msg   = tostring(result or "generation failed")
        local lower = msg:lower()
        local code  = "generation_failed"
        if lower:find("capab") or lower:find("permission") or lower:find("not enabled") or lower:find("disabled") then
            code = "generation_capability_off"
            msg = "Cube 3D generation is disabled. Turn on File > Game Settings > Security > "
                .. "\"Allow Mesh & Image APIs\", then retry — or build this with parts. (" .. msg .. ")"
        elseif lower:find("moderat") or lower:find("reject") or lower:find("inappropriate") or lower:find("policy") then
            code = "generation_moderated"
            msg = "The prompt was rejected by moderation. Rephrase it, or build this with parts. (" .. msg .. ")"
        elseif lower:find("timeout") or lower:find("overload") or lower:find("rate") or lower:find("busy") then
            code = "generation_busy"
            msg = "Generation timed out / service busy. Build with parts now, or retry once. (" .. msg .. ")"
        end
        return false, { error = msg, error_code = code }, nil, nil
    end

    if not (result and typeof(result) == "Instance") then
        return false, { error = "generation returned nothing — build with parts instead", error_code = "generation_empty" }, nil, nil
    end

    result.Name = meshName

    local pos = input.position
    if type(pos) == "table" and #pos >= 3 then
        pcall(function()
            result:PivotTo(CFrame.new(tonumber(pos[1]) or 0, tonumber(pos[2]) or 5, tonumber(pos[3]) or 0))
        end)
    end

    -- Default-anchor a generated build object (static scenery). HumanoidRootPart
    -- guard is irrelevant here (no Humanoid), but keep the explicit per-part set.
    local shouldAnchor = coerceBool(input.anchored, true)
    for _, d in ipairs(result:GetDescendants()) do
        if d:IsA("BasePart") then d.Anchored = shouldAnchor end
    end
    if result:IsA("BasePart") then result.Anchored = shouldAnchor end

    result.Parent = parent
    ChangeHistoryService:SetWaypoint("Pipeline GenerateMesh: " .. meshName)

    local meshCount = 0
    local firstMeshPath = nil
    for _, d in ipairs(result:GetDescendants()) do
        if d:IsA("MeshPart") then
            meshCount += 1
            if not firstMeshPath then firstMeshPath = d:GetFullName() end
        end
    end
    if result:IsA("MeshPart") then
        meshCount += 1
        if not firstMeshPath then firstMeshPath = result:GetFullName() end
    end

    local fullPath = result:GetFullName()
    -- Hand the model everything it needs to PLACE this WITHOUT inspecting: the
    -- world pivot, the bounding size, and the inner MeshPart path. Fixes the
    -- "generate → 10× inspect to find the MeshPart/size/ground" overdo loop.
    local pivotPos, extents
    pcall(function()
        local pv = result:GetPivot().Position
        pivotPos = { pv.X, pv.Y, pv.Z }
    end)
    pcall(function()
        local sz = result:IsA("Model") and result:GetExtentsSize() or result.Size
        extents = { sz.X, sz.Y, sz.Z }
    end)
    return true, {
        path           = fullPath,
        class_name     = result.ClassName,
        schema         = schemaName,
        mesh_parts     = meshCount,
        mesh_part_path = firstMeshPath,
        pivot          = pivotPos,
        size           = extents,
        note           = "Already parented, ANCHORED, and placed at `pivot`. Do NOT inspect it or hunt for the "
                  .. "inner MeshPart — to move it, ONE set_property(path,'CFrame',...) is enough. IMPORTANT: "
                  .. "until the place is SAVED/PUBLISHED to Roblox, this mesh renders as a plain gray cube in "
                  .. "playtests (its data is in-memory only). If a playtest matters now, TELL THE USER: "
                  .. "\"Save/publish the place (Ctrl+S) so the generated meshes bake in — until then they "
                  .. "show as gray cubes when you hit Play.\" After one save it works everywhere, forever.",
    }, nil, fullPath
end

--------------------------------------------------------------------------------
-- install_gui: build a Pisces Design Studio tree DIRECTLY as real instances
-- under StarterGui (no Command Bar paste). Ingests the Design Studio's
-- normalized tree and mirrors its _prop_to_rbxmx / _prop_to_luau value mapping,
-- so the in-Studio result matches the .rbxmx / LocalScript exports exactly.
-- Fired by the web Design Studio's "Push to Studio" when this plugin is live.
--------------------------------------------------------------------------------
-- Class allowlist mirroring the server's GUI_CLASSES: install_gui builds
-- whatever class the payload names, so without this a crafted payload could
-- Instance.new a Script/RemoteEvent under StarterGui. The server filters too
-- (normalize_tree) — this is defense-in-depth at the point of construction.
local _UI_ALLOWED_CLASSES = {
    ScreenGui = true, Frame = true, ScrollingFrame = true, TextLabel = true,
    TextButton = true, TextBox = true, ImageLabel = true, ImageButton = true,
    ViewportFrame = true, CanvasGroup = true,
    UICorner = true, UIListLayout = true, UIGridLayout = true, UIPadding = true,
    UIStroke = true, UIGradient = true, UIAspectRatioConstraint = true,
    UITextSizeConstraint = true, UISizeConstraint = true, UIScale = true,
}
local _UI_COLOR3_KEYS = {
    BackgroundColor3 = true, TextColor3 = true,
    ImageColor3 = true, BorderColor3 = true,
}
local _UI_ALIGN_ENUMS = {
    TextXAlignment = Enum.TextXAlignment,
    TextYAlignment = Enum.TextYAlignment,
}

-- A table-shaped design value → its Roblox datatype, or nil to defer to the
-- generic scalar coercion. Arrays are 1-indexed Lua tables (JSON-decoded).
local function _uiTableValue(key, val)
    if type(val) ~= "table" then return nil end
    local u2 = val.udim2
    if type(u2) == "table" and #u2 >= 4 then
        return UDim2.new(tonumber(u2[1]) or 0, tonumber(u2[2]) or 0,
                         tonumber(u2[3]) or 0, tonumber(u2[4]) or 0)
    end
    local ud = val.udim
    if type(ud) == "table" and #ud >= 2 then
        return UDim.new(tonumber(ud[1]) or 0, tonumber(ud[2]) or 0)
    end
    -- UIGradient stops: Color = {{r,g,b},...} spread evenly 0..1. Handles
    -- 2-stop candy AND 3+-stop rainbow/gold trims — the 2-only branch made
    -- pushed rainbow trims render WHITE in Studio.
    if key == "Color" and #val >= 2 and type(val[1]) == "table" then
        local allTables = true
        for _, c in ipairs(val) do
            if type(c) ~= "table" then allTables = false break end
        end
        if allTables then
            local kps = {}
            local n = #val - 1
            for i, c in ipairs(val) do
                kps[#kps + 1] = ColorSequenceKeypoint.new(
                    n > 0 and (i - 1) / n or 0,
                    Color3.new(tonumber(c[1]) or 0, tonumber(c[2]) or 0,
                               tonumber(c[3]) or 0))
            end
            return ColorSequence.new(kps)
        end
    end
    -- solid Color3: {r,g,b} for known color keys (and plain "Color", e.g. UIStroke)
    if #val == 3 and type(val[1]) ~= "table"
        and (_UI_COLOR3_KEYS[key] or key == "Color") then
        return Color3.new(tonumber(val[1]) or 0, tonumber(val[2]) or 0, tonumber(val[3]) or 0)
    end
    if key == "AnchorPoint" and #val == 2 then
        return Vector2.new(tonumber(val[1]) or 0, tonumber(val[2]) or 0)
    end
    return nil
end

local function _applyUiProp(inst, key, val)
    if key == "Name" then return end
    local coerced
    if type(val) == "table" then
        coerced = _uiTableValue(key, val)
    elseif (_UI_ALIGN_ENUMS[key] ~= nil) and type(val) == "number" then
        for _, item in ipairs(_UI_ALIGN_ENUMS[key]:GetEnumItems()) do
            if item.Value == val then coerced = item break end
        end
    elseif key == "Image" and type(val) == "string" then
        local id = val:match("(%d+)")
        coerced = id and ("rbxassetid://" .. id) or val
    else
        -- scalars / enums (Font, ApplyStrokeMode, bool, number, string) via the
        -- plugin's existing coercion against the fresh instance's default type.
        coerced = coercePropertyValue(inst, key, val)
    end
    if coerced ~= nil then
        pcall(function() inst[key] = coerced end)
    end
end

local function run_install_gui(input)
    local tree = input.tree or input.gui or input.root
    if type(tree) ~= "table" then
        return false, { error = "install_gui: no tree provided",
                        error_code = "no_tree" }, nil, nil
    end
    local guiName = tostring(input.gui_name or input.name or "PiscesDesign")
    local sg = game:GetService("StarterGui")

    -- Force a ScreenGui root named guiName (mirror tree_to_luau "starter").
    local rootNode
    if tostring(tree.class or tree.className or tree.class_name or "") == "ScreenGui" then
        tree.name = guiName
        rootNode = tree
    else
        rootNode = { class = "ScreenGui", name = guiName, props = {}, children = { tree } }
    end

    local count = 0
    local function build(node, parent)
        if type(node) ~= "table" then return nil end
        local className = tostring(node.class or node.className or node.class_name or "Frame")
        if not _UI_ALLOWED_CLASSES[className] then className = "Frame" end
        local okNew, inst = pcall(function() return Instance.new(className) end)
        if not okNew or not inst then return nil end
        inst.Name = tostring(node.name or className)
        local props = node.props or node.properties
        if type(props) == "table" then
            for k, v in _propPairs(props) do
                _applyUiProp(inst, tostring(k), v)
            end
        end
        inst.Parent = parent
        count = count + 1
        local kids = node.children
        if type(kids) == "table" then
            for _, child in ipairs(kids) do
                build(child, inst)
            end
        end
        return inst
    end

    ChangeHistoryService:SetWaypoint("Pre-Pipeline Install: " .. guiName)
    local old = sg:FindFirstChild(guiName)
    if old then pcall(function() old:Destroy() end) end
    local okBuild, built = pcall(build, rootNode, sg)
    ChangeHistoryService:SetWaypoint("Pipeline Install: " .. guiName)
    if not okBuild or not built then
        return false, { error = "install_gui: build failed — " .. tostring(built),
                        error_code = "build_failed" }, nil, nil
    end
    local path = built:GetFullName()
    return true, {
        tool = "install_gui",
        path = path,
        gui_name = guiName,
        created = count,
    }, nil, path
end

--------------------------------------------------------------------------------
-- GuidedPub (p43, multi-project p44): guided manual animation publishing.
-- Forward TABLE — the panel/staging implementation is assigned into it after
-- the UI helpers load (see the GUIDED ANIMATION PUBLISH section); the table
-- reference is stable, so handlers below can call GuidedPub.* at runtime.
-- state.clips[name] = { rig_name, status, aid, project_id } — each clip
-- keeps its OWN project_id (multi-clip builds are one project per clip; the
-- panel merges across guided_publish calls and never resets). Fields:
--   stage_rig(rig, clipName, reused)  — row layout + floating status tag
--   set_tag(clipName, status, hex)    — recolor a rig's status tag
--   mark_done(clipName, aid)          — auto-mint success bookkeeping
--   run(input)                        — the guided_publish tool entry
local GuidedPub = { state = { project_id = nil, clips = {}, order = {} } }

--------------------------------------------------------------------------------
-- install_animation (p33, Pisces Animation Studio): build a NATIVE Roblox
-- KeyframeSequence inside <rig>.AnimSaves — exactly where Roblox's own
-- Animation Editor looks — so the clip shows up in the official editor's
-- Load menu, plays natively via a registered temp id, and can be published
-- to the USER'S account with publish_animation (SaveSelectedToRoblox).
-- Spec: {rig_name, rig_type="R15"|"R6", name, loop, priority,
--        hierarchy={part=parentPart|json.null}, keyframes=[{t, style, dir,
--        poses={part={px,py,pz,r00..r22}}}]}
--------------------------------------------------------------------------------
local function _build_keyframe_sequence(spec)
    local kfs = Instance.new("KeyframeSequence")
    kfs.Name = tostring(spec.name or "PiscesClip")
    kfs.Loop = spec.loop == true
    local prioOk, prio = pcall(function()
        return Enum.AnimationPriority[tostring(spec.priority or "Action")]
    end)
    kfs.Priority = (prioOk and prio) or Enum.AnimationPriority.Action

    local hierarchy = spec.hierarchy or {}
    for _, fr in ipairs(spec.keyframes or {}) do
        local kf = Instance.new("Keyframe")
        kf.Time = tonumber(fr.t) or 0
        local styleOk, style = pcall(function()
            return Enum.PoseEasingStyle[tostring(fr.style or "Linear")]
        end)
        local dirOk, dir = pcall(function()
            return Enum.PoseEasingDirection[tostring(fr.dir or "InOut")]
        end)
        local poseByPart = {}
        -- create a Pose for EVERY part in the hierarchy (unposed = identity)
        for part in pairs(hierarchy) do
            local p = Instance.new("Pose")
            p.Name = part
            p.Weight = 1
            p.EasingStyle = (styleOk and style) or Enum.PoseEasingStyle.Linear
            p.EasingDirection = (dirOk and dir) or Enum.PoseEasingDirection.InOut
            local vals = fr.poses and fr.poses[part]
            if type(vals) == "table" and #vals >= 12 then
                p.CFrame = CFrame.new(
                    vals[1], vals[2], vals[3],
                    vals[4], vals[5], vals[6],
                    vals[7], vals[8], vals[9],
                    vals[10], vals[11], vals[12])
            end
            poseByPart[part] = p
        end
        -- nest poses per the hierarchy; roots attach to the keyframe
        for part, p in pairs(poseByPart) do
            local parentName = hierarchy[part]
            local parentPose = (type(parentName) == "string")
                and poseByPart[parentName] or nil
            if parentPose then
                p.Parent = parentPose
            else
                p.Parent = kf
            end
        end
        -- p37: detected motion events ride in as native KeyframeMarkers
        -- (PiscesFootstep left/right, PiscesStrike, ...) so game scripts can
        -- hook AnimationTrack:GetMarkerReachedSignal
        if type(fr.markers) == "table" then
            for _, m in ipairs(fr.markers) do
                if type(m) == "table" and type(m[1]) == "string" then
                    local marker = Instance.new("KeyframeMarker")
                    marker.Name = m[1]
                    marker.Value = tostring(m[2] or "")
                    marker.Parent = kf
                end
            end
        end
        kf.Parent = kfs
    end
    return kfs
end

local function run_install_animation(input)
    local spec = input.spec or input
    if type(spec) ~= "table" or type(spec.keyframes) ~= "table"
        or #spec.keyframes == 0 then
        return false, { error = "install_animation: no keyframes provided",
                        error_code = "missing_target" }, nil, nil
    end
    local clipName = tostring(spec.name or "PiscesClip")
    local rigType  = tostring(spec.rig or spec.rig_type or "R15"):upper()
    if rigType ~= "R6" then rigType = "R15" end
    local rigName  = tostring(input.rig_name or spec.rig_name
        or ("PiscesRig - " .. clipName))

    -- 1) spawn/reuse the preview rig (same idempotent path as spawn_rig)
    local okRig, rigRes = run_spawn_rig({
        name = rigName, rig_type = rigType, parent = "Workspace",
        anchored = false, fast = true,
    })
    if not okRig then
        return false, { error = "install_animation: rig spawn failed — "
            .. tostring(rigRes and rigRes.error),
            error_code = "rig_spawn_failed" }, nil, nil
    end
    local rig = workspace:FindFirstChild(rigName)
    if not rig then
        return false, { error = "install_animation: rig not found after spawn",
                        error_code = "rig_spawn_failed" }, nil, nil
    end

    -- p43: line fresh rigs up in a row (instead of piling onto one spot) and
    -- hang a floating name/status tag over each — "go into it" is visual.
    pcall(function()
        if GuidedPub.stage_rig then
            GuidedPub.stage_rig(rig, clipName,
                rigRes and rigRes.reused or false)
        end
    end)

    ChangeHistoryService:SetWaypoint("Pre-Pipeline Animation: " .. clipName)

    -- p38: synced ball prop (Pisces Animator soccer clips). The spec's
    -- hierarchy carries a "PiscesBall" Pose under HumanoidRootPart; the rig
    -- just needs a matching Motor6D'd part. An EXISTING PiscesBall (e.g. the
    -- user's own soccer-ball mesh dropped into the rig and renamed) is
    -- reused as-is — only the Motor6D is ensured.
    if type(spec.prop) == "table" and spec.prop.kind == "ball" then
        local hrp = rig:FindFirstChild("HumanoidRootPart")
        if hrp then
            local ball = rig:FindFirstChild("PiscesBall")
            if not ball then
                ball = Instance.new("Part")
                ball.Name = "PiscesBall"
                ball.Shape = Enum.PartType.Ball
                local d = 2 * (tonumber(spec.prop.radius) or 0.6)
                ball.Size = Vector3.new(d, d, d)
                ball.Color = Color3.fromRGB(245, 245, 245)
                ball.Material = Enum.Material.SmoothPlastic
                ball.CanCollide = false
                ball.Massless = true
                ball.CFrame = hrp.CFrame
                ball.Parent = rig
            end
            local motor = ball:FindFirstChild("PiscesBall")
            if not (motor and motor:IsA("Motor6D")) then
                motor = Instance.new("Motor6D")
                motor.Name = "PiscesBall"
                motor.Parent = ball
            end
            motor.Part0 = hrp
            motor.Part1 = ball
            motor.C0 = CFrame.new()
            motor.C1 = CFrame.new()
        end
    end

    -- 2) AnimSaves model (the official Animation Editor's clip store)
    local saves = rig:FindFirstChild("AnimSaves")
    if not saves then
        saves = Instance.new("Model")
        saves.Name = "AnimSaves"
        saves.Parent = rig
    end

    -- 3) build + replace the KeyframeSequence
    local old = saves:FindFirstChild(clipName)
    if old then old:Destroy() end
    local kfs = _build_keyframe_sequence(spec)
    kfs.Parent = saves

    -- 4) register a session-local id so the clip plays NATIVELY in playtests
    --    before it's ever published, and wire a ready-to-use Animation object.
    local tempId = nil
    pcall(function()
        local provider = game:GetService("KeyframeSequenceProvider")
        tempId = provider:RegisterKeyframeSequence(kfs)
    end)
    if tempId then
        local animName = clipName .. " (Preview)"
        local anim = saves:FindFirstChild(animName)
        if not anim then
            anim = Instance.new("Animation")
            anim.Name = animName
            anim.Parent = saves
        end
        anim.AnimationId = tempId
    end

    ChangeHistoryService:SetWaypoint("Pipeline Animation: " .. clipName)

    -- 5) leave the KFS selected so the user can immediately publish it from
    --    the Studio UI too (Save to Roblox works on the selection)
    pcall(function()
        game:GetService("Selection"):Set({ kfs })
    end)

    return true, {
        tool = "install_animation",
        rig_path = rig:GetFullName(),
        kfs_path = kfs:GetFullName(),
        rig_type = rigType,
        keyframes = #spec.keyframes,
        temp_id = tempId,
        rig_reused = rigRes and rigRes.reused or false,
    }, nil, kfs:GetFullName()
end

--------------------------------------------------------------------------------
-- publish_animation (p41, 2026-07-22): publish the installed KeyframeSequence
-- as a real USER-OWNED Animation asset via AssetService:CreateAssetAsync —
-- NO dialog, returns the numeric AnimationId synchronously so the runner can
-- wire it into scripts automatically. This is the SAME proven API this plugin
-- already uses to mint user-owned meshes (publish_user_mesh), so the beta flag
-- ("CreateAssetAsync Luau API"), the local-plugin gate, and the
-- AssetCreateUpdate capability are already satisfied here — only the Animation
-- asset type is newly exercised. If CreateAssetAsync is unavailable (beta off,
-- or Animation not accepted from a plugin context in this build) it degrades to
-- the old Save-to-Roblox dialog so the user can still publish by hand.
-- Was (p33): plugin:SaveSelectedToRoblox() — opens a fire-and-forget dialog
-- that returns NO id (DevForum FR 2420750), which is why "it never opened it up"
-- into anything usable.
--------------------------------------------------------------------------------
local function run_publish_animation(input)
    local clipName = tostring(input.clip_name or input.name or "")
    local rigName  = tostring(input.rig_name or "")
    if clipName == "" then
        return false, { error = "publish_animation: no clip_name",
                        error_code = "missing_target" }, nil, nil
    end
    local kfs = nil
    local function scan(container)
        local saves = container and container:FindFirstChild("AnimSaves")
        local hit = saves and saves:FindFirstChild(clipName)
        if hit and hit:IsA("KeyframeSequence") then kfs = hit end
    end
    if rigName ~= "" then scan(workspace:FindFirstChild(rigName)) end
    if not kfs then
        for _, m in ipairs(workspace:GetChildren()) do
            if m:IsA("Model") then
                scan(m)
                if kfs then break end
            end
        end
    end
    if not kfs then
        return false, { error = "publish_animation: KeyframeSequence '"
            .. clipName .. "' not found in any AnimSaves — push it first",
            error_code = "not_found" }, nil, nil
    end

    -- PRIMARY: publish under the signed-in Studio user, capture the id inline.
    local uid = 0
    pcall(function() uid = game:GetService("StudioService"):GetUserId() end)
    local params = {
        Name = ("Pipeline - " .. clipName):sub(1, 50),
        Description = "AI-generated animation (Pipeline Animation Studio)",
    }
    if uid and uid > 0 then
        params.CreatorId = uid
        params.CreatorType = Enum.AssetCreatorType.User
    end
    local okCall, result, idOrErr = pcall(function()
        return game:GetService("AssetService"):CreateAssetAsync(
            kfs, Enum.AssetType.Animation, params)
    end)

    if okCall then
        local success = false
        pcall(function()
            success = (result == Enum.CreateAssetResult.Success)
        end)
        if success then
            local aid = tonumber(idOrErr)
            if aid then
                -- Fresh-asset propagation lag: the id is valid immediately but
                -- LoadAnimation can briefly fail. Best-effort preload (mirror
                -- the mesh wait+retry) — never block the return on it.
                local playable = false
                pcall(function()
                    local a = Instance.new("Animation")
                    a.AnimationId = "rbxassetid://" .. tostring(aid)
                    for _ = 1, 3 do
                        local okLoad = pcall(function()
                            game:GetService("ContentProvider"):PreloadAsync({ a })
                        end)
                        if okLoad then playable = true break end
                        task.wait(1.0)
                    end
                    a:Destroy()
                end)
                warn("[Pipeline] publish_animation: published USER-owned "
                    .. "Animation asset " .. tostring(aid)
                    .. " for '" .. clipName .. "'")
                pcall(function()
                    if GuidedPub.mark_done then
                        GuidedPub.mark_done(clipName, tostring(aid))
                    end
                end)
                return true, {
                    tool = "publish_animation",
                    kfs_path = kfs:GetFullName(),
                    animation_id = aid,
                    content_id = "rbxassetid://" .. tostring(aid),
                    owned_by_user = true,
                    playable_confirmed = playable,
                    moderation = "pending_ok",
                    note = "Published to the user's account — AnimationId "
                        .. tostring(aid) .. " is ready to wire into scripts.",
                }, nil, kfs:GetFullName()
            end
        end
        local moderated = false
        pcall(function()
            moderated = (result == Enum.CreateAssetResult.ModerationFailed)
        end)
        if moderated then
            return false, {
                error = "publish_animation: Roblox moderation rejected the "
                    .. "animation upload.",
                error_code = "moderation_failed",
            }, nil, nil
        end
        -- else: non-success (e.g. type not permitted here) → dialog fallback
    end

    local why = okCall and ("non-success:" .. tostring(result))
        or tostring(result)

    -- p43 GUIDED MODE: the server orchestrates a panel-driven manual flow —
    -- do NOT auto-open the dialog here. With several clips the auto-opened
    -- dialogs REPLACE each other and every Submit but the last is lost
    -- (owner-reported: 9 clips → 1 usable id). Report needs_manual instead;
    -- the server follows up with ONE guided_publish call listing every
    -- pending clip and the panel opens dialogs one at a time on user clicks.
    if input.guided then
        pcall(function()
            if GuidedPub.set_tag then
                GuidedPub.set_tag(clipName, "publish pending", "FFDC64")
            end
        end)
        return true, {
            tool = "publish_animation",
            kfs_path = kfs:GetFullName(),
            needs_manual = true,
            guided = true,
            auto_publish_error = tostring(why),
            note = "Automatic publish unavailable (" .. tostring(why)
                .. ") — clip queued for the guided publish panel.",
        }, nil, kfs:GetFullName()
    end

    -- FALLBACK (non-guided callers / older servers): open Roblox's own
    -- Save-to-Roblox dialog so the user can still publish by hand and read the
    -- AnimationId off it. Honest: no auto-capture on this path.
    game:GetService("Selection"):Set({ kfs })
    local okDlg, dlgErr = pcall(function()
        plugin:SaveSelectedToRoblox()
    end)
    if okDlg then
        warn("[Pipeline] publish_animation: CreateAssetAsync unavailable ("
            .. tostring(why) .. ") — opened manual Save-to-Roblox dialog")
        return true, {
            tool = "publish_animation",
            kfs_path = kfs:GetFullName(),
            dialog_opened = true,
            needs_manual = true,
            auto_publish_error = tostring(why),
            note = "Automatic publish is off — enable File > Beta Features > "
                .. "'CreateAssetAsync Luau API' and restart Studio for one-click "
                .. "publishing. For now Roblox's Save-to-Roblox dialog is open: "
                .. "click Submit, then copy the AnimationId it shows.",
        }, nil, kfs:GetFullName()
    end
    return false, {
        error = "publish_animation: automatic publish failed (" .. tostring(why)
            .. ") and the Studio publish dialog also could not open — "
            .. tostring(dlgErr),
        error_code = "publish_failed",
    }, nil, nil
end

--------------------------------------------------------------------------------
-- insert_mesh  (p35, 2026-07-10 — Pisces Modeling Studio)
-- Inserts an AI-generated mesh by its published mesh CONTENT id (cross-account
-- resolvable, like design Image assets) via InsertService:CreateMeshPartAsync,
-- applies SurfaceAppearance PBR maps, then clones for each placement in
-- input.instances = {{cf = {12 nums}, size = {x,y,z}}, ...}.
--------------------------------------------------------------------------------

-- p37: local EditableMesh build — works in UNPUBLISHED places where private
-- Open-Cloud assets can never load (no universe to grant). Fetches packed
-- binary geometry + RGBA texture chunks from the server and constructs the
-- MeshPart entirely in Studio: no publish, no moderation, no permissions.
local function v5_fetch_binary(path)
    local ok, resp = pcall(function()
        return HttpService:RequestAsync({
            Url = BASE_URL .. path, Method = "GET", Headers = v5_headers(),
        })
    end)
    if not ok then return nil, tostring(resp) end
    if resp.StatusCode ~= 200 then return nil, "http " .. resp.StatusCode end
    return buffer.fromstring(resp.Body)
end

-- Build ONLY the EditableMesh geometry from the server's packed PMG1 blob.
-- Split out from the MeshPart wrap so the SAME EditableMesh can be published as
-- a durable, user-owned Mesh asset (publish_user_mesh) instead of only living
-- as a session-local preview.
local function build_local_editablemesh(input)
    local sha = tostring(input.sha or "")
    if sha == "" then return nil, "no sha for local build" end
    local b, gerr = v5_fetch_binary("/v5/model-localmesh/" .. sha .. "?part=geo")
    if not b then return nil, "geo: " .. tostring(gerr) end
    if buffer.len(b) < 12 or buffer.readstring(b, 0, 4) ~= "PMG1" then
        return nil, "bad geo blob"
    end
    local vcount = buffer.readu32(b, 4)
    local icount = buffer.readu32(b, 8)
    local pos0 = 12
    local nrm0 = pos0 + vcount * 12
    local uv0  = nrm0 + vcount * 12
    local idx0 = uv0 + vcount * 8
    if buffer.len(b) < idx0 + icount * 4 then return nil, "truncated geo" end
    local AssetService = game:GetService("AssetService")
    local okEm, em = pcall(function()
        return AssetService:CreateEditableMesh({ FixedSize = false })
    end)
    if not okEm or not em then return nil, "CreateEditableMesh: " .. tostring(em) end
    local vids  = table.create(vcount)
    local nids  = table.create(vcount)
    local uvids = table.create(vcount)
    for i = 0, vcount - 1 do
        vids[i + 1] = em:AddVertex(Vector3.new(
            buffer.readf32(b, pos0 + i * 12),
            buffer.readf32(b, pos0 + i * 12 + 4),
            buffer.readf32(b, pos0 + i * 12 + 8)))
        nids[i + 1] = em:AddNormal(Vector3.new(
            buffer.readf32(b, nrm0 + i * 12),
            buffer.readf32(b, nrm0 + i * 12 + 4),
            buffer.readf32(b, nrm0 + i * 12 + 8)))
        uvids[i + 1] = em:AddUV(Vector2.new(
            buffer.readf32(b, uv0 + i * 8),
            buffer.readf32(b, uv0 + i * 8 + 4)))
    end
    for t = 0, math.floor(icount / 3) - 1 do
        local i1 = buffer.readu32(b, idx0 + t * 12) + 1
        local i2 = buffer.readu32(b, idx0 + t * 12 + 4) + 1
        local i3 = buffer.readu32(b, idx0 + t * 12 + 8) + 1
        local okF, faceId = pcall(function()
            return em:AddTriangle(vids[i1], vids[i2], vids[i3])
        end)
        if okF and faceId then
            pcall(function() em:SetFaceNormals(faceId, { nids[i1], nids[i2], nids[i3] }) end)
            pcall(function() em:SetFaceUVs(faceId, { uvids[i1], uvids[i2], uvids[i3] }) end)
        end
    end
    return em
end

-- Publish an EditableMesh as a durable MESH asset OWNED BY THE LOGGED-IN STUDIO
-- USER via AssetService:CreateAssetAsync (fully programmatic — no modal — and
-- created on the user's own account, NOT our moderated Open-Cloud account). A
-- user-owned mesh loads in that user's own play session with no universe grant,
-- so it survives F5 playtest + save/reopen. THIS is the durability fix for
-- meshes rendering as a box in playtest on an unpublished place. Every enum /
-- API touch is pcall-guarded so an older Studio build simply returns nil and
-- falls back to the session preview. Cached per-sha for the session so a repeat
-- insert of the same mesh doesn't re-upload. Returns the asset id or nil.
local _userMeshCache = {}
-- Returns (asset_id, nil) or (nil, reason). p49: the reason RIDES THE TOOL
-- RESULT back to the server — a console warn is invisible to the service, and
-- an invisible mint failure is exactly what blinded the 2026-08-04 white-block
-- diagnosis for a whole session.
local function publish_user_mesh(em, sha)
    if sha and sha ~= "" and _userMeshCache[sha] then
        return _userMeshCache[sha], nil
    end
    local uid = 0
    pcall(function() uid = game:GetService("StudioService"):GetUserId() end)
    if not uid or uid <= 0 then return nil, "no_studio_user" end
    local okAll, result, idOrErr = pcall(function()
        return game:GetService("AssetService"):CreateAssetAsync(
            em, Enum.AssetType.Mesh, {
                CreatorId = uid,
                CreatorType = Enum.AssetCreatorType.User,
                Name = "Pipeline Mesh",
                Description = "Generated in Pipeline Modeling Studio",
            })
    end)
    if not okAll then
        warn("[Pipeline] CreateAssetAsync error: " .. tostring(result))
        return nil, "api_error: " .. tostring(result)
    end
    local success = false
    pcall(function() success = (result == Enum.CreateAssetResult.Success) end)
    if success then
        local aid = tonumber(idOrErr)
        if aid then
            if sha and sha ~= "" then _userMeshCache[sha] = aid end
            warn("[Pipeline] insert_mesh: published USER-owned mesh asset "
                .. tostring(aid) .. " — durable, survives playtest")
            return aid, nil
        end
    end
    warn("[Pipeline] CreateAssetAsync non-success: " .. tostring(result)
        .. " / " .. tostring(idOrErr))
    return nil, "create_result: " .. tostring(result)
        .. " / " .. tostring(idOrErr)
end

-- Wrap an EditableMesh into a MeshPart + apply the session texture. This is the
-- PREVIEW representation: renders in Edit but its geometry is session-local, so
-- it BOXES in playtest / after reopen. Last-resort fallback only.
local function editablemesh_to_meshpart(em, input, fid)
    local sha = tostring(input.sha or "")
    local AssetService = game:GetService("AssetService")
    local okP, part = pcall(function()
        return AssetService:CreateMeshPartAsync(Content.fromObject(em),
            { CollisionFidelity = fid })
    end)
    if not okP or typeof(part) ~= "Instance" then
        return nil, "CreateMeshPartAsync(local): " .. tostring(part)
    end
    -- texture: chunked raw RGBA → EditableImage → TextureContent
    local chunk = v5_fetch_binary("/v5/model-localmesh/" .. sha .. "?part=tex&i=0")
    if chunk and buffer.len(chunk) >= 12
        and buffer.readstring(chunk, 0, 4) == "PMT1" then
        local w = buffer.readu16(chunk, 4)
        local h = buffer.readu16(chunk, 6)
        local okI, img = pcall(function()
            return AssetService:CreateEditableImage({ Size = Vector2.new(w, h) })
        end)
        if okI and img then
            local wrote = false
            local ci = 0
            while chunk do
                local y0   = buffer.readu16(chunk, 8)
                local rows = buffer.readu16(chunk, 10)
                local need = rows * w * 4
                if buffer.len(chunk) < 12 + need then break end
                local px = buffer.create(need)
                buffer.copy(px, 0, chunk, 12, need)
                local okW = pcall(function()
                    img:WritePixelsBuffer(Vector2.new(0, y0),
                        Vector2.new(w, rows), px)
                end)
                wrote = wrote or okW
                if y0 + rows >= h then break end
                ci += 1
                chunk = v5_fetch_binary("/v5/model-localmesh/" .. sha
                    .. "?part=tex&i=" .. ci)
                if chunk and (buffer.len(chunk) < 12
                    or buffer.readstring(chunk, 0, 4) ~= "PMT1") then
                    chunk = nil
                end
            end
            if wrote then
                pcall(function() part.TextureContent = Content.fromObject(img) end)
            end
        end
    end
    return part
end

-- Backwards-compatible one-call preview build (geometry + session texture).
local function build_local_meshpart(input, fid)
    local em, err = build_local_editablemesh(input)
    if not em then return nil, err end
    return editablemesh_to_meshpart(em, input, fid)
end

local function run_insert_mesh(input)
    local meshId = tonumber(input.mesh_id or input.meshId)
    if not meshId then
        return false, { error = "insert_mesh requires numeric mesh_id",
                        error_code = "bad_args" }, nil, nil
    end
    local parentPath = tostring(input.parent_path or input.parent or "Workspace")
    local parent, vivified = findOrCreateParent(parentPath)
    if not parent then
        return false, { error = "Parent not found: " .. parentPath,
                        error_code = "parent_not_found" }, nil, nil
    end
    if vivified then
        warn("[Pipeline] insert_mesh vivified container(s): "
            .. table.concat(vivified, ", "))
    end
    local name  = tostring(input.name or "PiscesMesh")
    local insts = input.instances
    if type(insts) ~= "table" or #insts == 0 then
        insts = { { cf = input.cframe or input.cf, size = input.size } }
    end

    local fid = Enum.CollisionFidelity.Hull
    pcall(function()
        fid = Enum.CollisionFidelity[tostring(input.collision_fidelity or "Hull")]
    end)

    -- Durability: a MeshPart only survives F5 playtest + save/reopen if its
    -- geometry is a durable asset the RUNNING game is authorised to load.
    --   • Published place (GameId ~= 0): the server grants our private mesh to
    --     the universe, so the fast Pisces-asset path is durable — use it.
    --   • Unpublished place (Baseplate, GameId == 0): that private asset can
    --     NEVER be granted (no universe) and would render as a box in playtest,
    --     so mint a durable USER-OWNED mesh asset instead — it loads in the
    --     user's own play session with no grant and no dependency on our
    --     account's moderation state. (owner report 2026-07-22: "shows up as a
    --     box in a playtest even if the place is saved")
    local tmpl, localBuilt, durableUserAsset, mintedUserAsset =
        nil, false, nil, nil
    local mintError = nil
    -- the server tells us whether it actually granted our PRIVATE mesh to this
    -- place's universe. If it couldn't (unpublished place, or a stale/failed
    -- grant) the Pisces asset boxes in playtest, so treat it as unusable and go
    -- straight to the durable user-owned publish. Legacy server (no flag) =
    -- assume granted, preserving prior behaviour.
    local grantOk = input.grant_ok
    if grantOk == nil then grantOk = true end
    local published = false
    pcall(function() published = (game.GameId ~= 0) end)

    -- Fast path ONLY when the place is published AND the grant landed — then our
    -- private mesh is authorised for the running game and survives playtest.
    if published and grantOk then
        -- new API wants a Content value; fall back to the legacy string form
        local contentArg = "rbxassetid://" .. meshId
        pcall(function() contentArg = Content.fromAssetId(meshId) end)
        -- p59: the Content + options form lives on AssetService. The old code
        -- called it on InsertService ("Unable to cast Content to ContentId"),
        -- so the fast path never worked and EVERY model became a preview.
        -- A fresh upload can lag a few seconds, so retry briefly.
        for _try = 1, 4 do
            local okC, t = pcall(function()
                return game:GetService("AssetService"):CreateMeshPartAsync(
                    contentArg, { CollisionFidelity = fid })
            end)
            if okC and typeof(t) == "Instance" then tmpl = t break end
            local okL, t2 = pcall(function()
                return game:GetService("InsertService"):CreateMeshPartAsync(
                    "rbxassetid://" .. meshId, fid,
                    Enum.RenderFidelity.Automatic)
            end)
            if okL and typeof(t2) == "Instance" then tmpl = t2 break end
            if _try < 4 then task.wait(2) end
        end
    end

    if not tmpl then
        local em, emErr = build_local_editablemesh(input)
        if em then
            local aid, mintErr = publish_user_mesh(em, tostring(input.sha or ""))
            mintError = mintErr
            if aid then
                mintedUserAsset = aid
                -- a freshly-created asset can lag before CreateMeshPartAsync can
                -- load it (moderation / CDN propagation) — wait+retry so the
                -- FIRST insert lands durable instead of dropping to a box
                local up
                for _ = 1, 5 do
                    local okU, u = pcall(function()
                        return game:GetService("AssetService"):CreateMeshPartAsync(
                            Content.fromAssetId(aid), { CollisionFidelity = fid })
                    end)
                    if okU and typeof(u) == "Instance" then up = u break end
                    task.wait(2)
                end
                if up then
                    tmpl = up
                    durableUserAsset = aid
                end
            end
            if not tmpl then
                -- durable asset not ready yet (or publish unavailable) → session
                -- EditableMesh PREVIEW (renders in Edit, BOXES in playtest);
                -- reported honestly so the UI can tell the user it's pending.
                local lp = editablemesh_to_meshpart(em, input, fid)
                if lp then
                    tmpl = lp
                    localBuilt = true
                    warn("[Pipeline] insert_mesh: durable mesh not ready — "
                        .. "inserted PREVIEW (sha " .. tostring(input.sha)
                        .. (mintedUserAsset
                            and (", minted " .. tostring(mintedUserAsset)) or "")
                        .. "); shows a box in playtest until publishing finishes")
                end
            end
        else
            emErr = emErr or "no geometry"
        end
    end

    if typeof(tmpl) ~= "Instance" then
        return false, {
            error = "insert_mesh could not produce geometry for mesh " .. meshId,
            error_code = "mesh_insert_failed",
            note = "The mesh may still be moderating — retry in a minute.",
        }, nil, nil
    end
    -- AI-sculpted meshes can carry flipped normals on thin features; single
    -- sided rendering makes those faces invisible ("the mesh looks
    -- transparent", owner report 2026-07-12)
    pcall(function() tmpl.DoubleSided = true end)

    -- PBR maps. ColorMap is republished as a PUBLIC image so it resolves for
    -- anyone; Normal/Metalness/Roughness are PRIVATE ids that only load where
    -- our universe grant landed. On the user-owned / ungranted path those would
    -- reference UNLOADABLE ids (gray override), so restrict to the public
    -- ColorMap there. Skip entirely for local previews (TextureContent already
    -- carries the albedo).
    local publicMapsOnly = (durableUserAsset ~= nil) or (not grantOk)
    local surface = (not localBuilt)
        and (input.surface or input.surface_appearance) or nil
    if type(surface) == "table" and next(surface) ~= nil then
        local sa = Instance.new("SurfaceAppearance")
        -- never let texture alpha punch holes in the mesh
        pcall(function() sa.AlphaMode = Enum.AlphaMode.Overlay end)
        local appliedAny = false
        for prop, id in pairs(surface) do
            local n = tonumber(id)
            local allowed = (prop == "ColorMap") or (not publicMapsOnly and
                (prop == "NormalMap" or prop == "MetalnessMap"
                    or prop == "RoughnessMap"))
            if n and allowed then
                pcall(function() sa[prop] = "rbxassetid://" .. n end)
                appliedAny = true
            end
        end
        -- an empty SurfaceAppearance would gray the mesh — only attach it when
        -- at least one loadable map was set
        if appliedAny then sa.Parent = tmpl else sa:Destroy() end
        -- p37: classic MeshPart texture as belt-and-braces — renders the
        -- albedo even where SurfaceAppearance maps fail to resolve
        local cm = tonumber(surface.ColorMap)
        if cm then
            pcall(function() tmpl.TextureID = "rbxassetid://" .. cm end)
        end
    end

    ChangeHistoryService:SetWaypoint("Pre-Pipeline InsertMesh: " .. name)
    local anchored = coerceBool(input.anchored, true)
    local made, firstPath = 0, nil
    for i, inst in ipairs(insts) do
        if i > 500 then break end
        local part = (i == 1) and tmpl or tmpl:Clone()
        part.Name = (i == 1) and name or (name .. "_" .. i)
        part.Anchored = anchored
        if type(inst) == "table" then
            if inst.size ~= nil then
                local okS, v = pcall(function()
                    return coercePropertyValue(part, "Size", inst.size)
                end)
                if okS and v then pcall(function() part.Size = v end) end
            end
            if inst.cf ~= nil then
                local okF, cfv = pcall(function()
                    return coercePropertyValue(part, "CFrame", inst.cf)
                end)
                if okF and cfv then pcall(function() part.CFrame = cfv end) end
            end
        end
        part.Parent = parent
        made = made + 1
        if i == 1 then firstPath = part:GetFullName() end
    end
    ChangeHistoryService:SetWaypoint("Pipeline InsertMesh: " .. name)
    return true, {
        tool = "insert_mesh",
        mesh_id = durableUserAsset or meshId,
        path = firstPath,
        instances_created = made,
        parent = parent:GetFullName(),
        -- honesty: durable=true means it survives playtest; local_preview=true
        -- means it renders now but BOXES in playtest until it finishes
        -- publishing (server surfaces this to the user). user_asset_id carries
        -- the minted durable id even when the load lagged (localBuilt path), so
        -- a re-push resolves it from cache.
        durable = (not localBuilt),
        local_preview = localBuilt,
        user_asset_id = durableUserAsset or mintedUserAsset,
        -- p49: WHY the durable mint didn't happen, so the server can name the
        -- remedy (beta flag / account capability / API error) instead of
        -- shrugging "preview_only" at the user.
        mint_error = localBuilt and mintError or nil,
    }, nil, firstPath
end

--------------------------------------------------------------------------------
-- TOOL DISPATCHER
--------------------------------------------------------------------------------

--------------------------------------------------------------------------------
-- TEAM VIEW (p60): the Pisces team, live in the viewport.
-- Each member is a coloured bubble with its name and a facing arrow. When it
-- works on something that is in the 3D world it stands next to it, points a
-- laser at it and outlines it in its colour. When it works on something that
-- has no place in the world (a script, a screen) it stays at its spot in the
-- team circle and its label says what it is on.
-- VIEW ONLY: every piece lives in CoreGui. Nothing is added to the place,
-- nothing is saved, nothing replicates.
-- One table, no top-level locals (Luau caps a chunk at 200 local registers).
--------------------------------------------------------------------------------
local TV = { feed = nil, members = {}, order = {}, on = false, root = nil, conn = nil,
             anchor = nil, card = nil, rows = {}, last_update = 0, clock = 0 }

function TV.color(hex)
    local ok, c = pcall(function() return Color3.fromHex(tostring(hex or "FFFFFF")) end)
    return (ok and c) or Color3.new(1, 1, 1)
end

function TV.leaf(path)
    local s = tostring(path or "")
    return s:match("([^%.]+)$") or s
end

-- Where a thing is in the world: centre + rough radius. nil = not in the world.
function TV.world_of(inst)
    if typeof(inst) ~= "Instance" or not inst:IsDescendantOf(workspace) then return nil end
    if inst == workspace or inst:IsA("Terrain") or inst:IsA("Camera") then return nil end
    if inst:IsA("BasePart") then
        return inst.Position, math.clamp(inst.Size.Magnitude * 0.5, 1, 60)
    end
    if inst:IsA("Attachment") then return inst.WorldPosition, 1 end
    if inst:IsA("Model") then
        local ok, cf, size = pcall(function() return inst:GetBoundingBox() end)
        if ok and cf and size and size.Magnitude > 0.01 then
            return cf.Position, math.clamp(size.Magnitude * 0.5, 1, 60)
        end
    end
    -- a folder or anything else: the middle of the first parts under it
    local sum, n, far = Vector3.zero, 0, 1
    for _, d in ipairs(inst:GetDescendants()) do
        if d:IsA("BasePart") and not d:IsA("Terrain") then
            sum += d.Position; n += 1
            if n >= 40 then break end
        end
    end
    if n == 0 then return nil end
    local mid = sum / n
    for _, d in ipairs(inst:GetDescendants()) do
        if d:IsA("BasePart") and not d:IsA("Terrain") then
            far = math.max(far, (d.Position - mid).Magnitude + d.Size.Magnitude * 0.5)
        end
    end
    return mid, math.clamp(far, 1, 60)
end

-- The thing a path names; when it does not exist yet, the nearest thing above it.
function TV.find(path)
    local p = tostring(path or ""):gsub("^[Gg]ame%.", "")
    local exact = true
    while p ~= "" do
        local ok, inst = pcall(findInstanceByPath, p)
        if ok and typeof(inst) == "Instance" then return inst, exact end
        local up = p:match("^(.*)%.[^%.]+$")
        if not up then break end
        p = up
        exact = false
    end
    return nil, false
end

function TV.ensure_root()
    local cg = game:GetService("CoreGui")
    if TV.root and TV.root.Parent == cg then return TV.root end
    local old = cg:FindFirstChild("PipelineTeamView")
    if old then pcall(function() old:Destroy() end) end
    local f = Instance.new("Folder")
    f.Name = "PipelineTeamView"
    f.Archivable = false
    f.Parent = cg
    TV.root = f
    return f
end

function TV.adorn(class, parent, props)
    local a = Instance.new(class)
    a.Adornee = workspace.Terrain
    a.Archivable = false
    for k, v in pairs(props) do a[k] = v end
    a.Parent = parent
    return a
end

function TV.label_layer()
    if TV.labels and TV.labels.Parent then return TV.labels end
    local sg = Instance.new("ScreenGui")
    sg.Name = "PipelineTeamLabels"
    sg.Archivable = false
    sg.DisplayOrder = 40
    sg.ResetOnSpawn = false
    sg.IgnoreGuiInset = true
    sg.Parent = TV.ensure_root()
    TV.labels = sg
    return sg
end

function TV.make(name, info)
    local root = TV.ensure_root()
    local color = TV.color(info.color)
    local f = Instance.new("Folder")
    f.Name = name
    f.Archivable = false
    f.Parent = root
    local e = { name = name, color = color, folder = f, phase = (#TV.order) * 1.7, laser_a = 1 }
    e.shell = TV.adorn("SphereHandleAdornment", f, { Radius = 1.05, Color3 = color, Transparency = 0.45, ZIndex = 1 })
    e.core  = TV.adorn("SphereHandleAdornment", f, { Radius = 0.42, Color3 = Color3.new(1, 1, 1), Transparency = 0.05, ZIndex = 2 })
    e.arrow = TV.adorn("ConeHandleAdornment", f, { Radius = 0.5, Height = 1.0, Color3 = color, Transparency = 0.05, ZIndex = 2 })
    e.laser = TV.adorn("CylinderHandleAdornment", f, { Radius = 0.05, Height = 1, Color3 = color, Transparency = 1, ZIndex = 1,
                                                       AlwaysOnTop = true })
    e.dot   = TV.adorn("SphereHandleAdornment", f, { Radius = 0.22, Color3 = color, Transparency = 1, ZIndex = 3, AlwaysOnTop = true })
    local hl = Instance.new("Highlight")
    hl.Archivable = false
    hl.FillColor = color
    hl.FillTransparency = 0.86
    hl.OutlineColor = color
    hl.OutlineTransparency = 0
    hl.DepthMode = Enum.HighlightDepthMode.AlwaysOnTop
    hl.Enabled = false
    hl.Parent = f
    e.hl = hl
    -- the name tag: a 2D label that follows the bubble on screen (always readable, any distance, through walls)
    local holder = Instance.new("Frame")
    holder.Name = name
    holder.AnchorPoint = Vector2.new(0.5, 1)
    holder.Size = UDim2.fromOffset(260, 40)
    holder.BackgroundTransparency = 1
    holder.Visible = false
    holder.Parent = TV.label_layer()
    e.holder = holder
    local col = Instance.new("UIListLayout")
    col.HorizontalAlignment = Enum.HorizontalAlignment.Center
    col.VerticalAlignment = Enum.VerticalAlignment.Bottom
    col.SortOrder = Enum.SortOrder.LayoutOrder
    col.Padding = UDim.new(0, 2)
    col.Parent = holder
    local tag = Instance.new("TextLabel")
    tag.BackgroundColor3 = color
    tag.BackgroundTransparency = 0
    tag.BorderSizePixel = 0
    tag.TextColor3 = Color3.new(1, 1, 1)
    tag.Font = Enum.Font.GothamBold
    tag.TextSize = 14
    tag.Text = tostring(info.role or name)
    tag.AutomaticSize = Enum.AutomaticSize.X
    tag.Size = UDim2.fromOffset(0, 22)
    tag.LayoutOrder = 1
    tag.Parent = holder
    e.tag = tag
    local pad = Instance.new("UIPadding")
    pad.PaddingLeft = UDim.new(0, 9)
    pad.PaddingRight = UDim.new(0, 9)
    pad.Parent = tag
    local cr = Instance.new("UICorner")
    cr.CornerRadius = UDim.new(0, 7)
    cr.Parent = tag
    local st = Instance.new("TextLabel")
    st.BackgroundTransparency = 1
    st.TextColor3 = Color3.new(1, 1, 1)
    st.TextStrokeTransparency = 0.3
    st.Font = Enum.Font.GothamMedium
    st.TextSize = 12
    st.Text = ""
    st.Size = UDim2.new(1, 0, 0, 15)
    st.LayoutOrder = 2
    st.Parent = holder
    e.status_label = st
    table.insert(TV.order, name)
    TV.members[name] = e
    return e
end

function TV.drop(name)
    local e = TV.members[name]
    if not e then return end
    pcall(function() e.folder:Destroy() end)
    pcall(function() e.holder:Destroy() end)   -- its name tag lives in the label layer, not in its folder
    TV.members[name] = nil
    for i, n in ipairs(TV.order) do
        if n == name then table.remove(TV.order, i) break end
    end
end

-- p61: a member whose work has no place in the world (a screen, an effect, code) still moves, so the team never
-- looks frozen; during the meeting the members draw together.
TV.STILL = { [""] = true, ["done"] = true, ["stopped"] = true, ["waiting"] = true, ["waiting for the team"] = true }
TV.MEET = { ["in the meeting"] = true, ["posting to the team"] = true, ["talking to a teammate"] = true,
    ["asking a teammate"] = true, ["reading the plans"] = true, ["reading the brief"] = true,
    ["settling the plan"] = true, ["setting up the team"] = true, ["bringing in the team"] = true }
function TV.is_busy(status)
    return not TV.STILL[string.lower(tostring(status or ""))]
end
function TV.is_meeting(status)
    return TV.MEET[string.lower(tostring(status or ""))] == true
end

-- The team circle: where a member waits when its work has no place in the world.
function TV.home(i, n, tight)
    local a = TV.anchor or Vector3.new(0, 6, 0)
    local ang = (i - 1) * (2 * math.pi / math.max(n, 3)) + math.pi * 0.5
    local r = (3.2 + 0.5 * math.max(n - 3, 0)) * (tight and 0.6 or 1)
    return a + Vector3.new(math.cos(ang) * r, 0, math.sin(ang) * r), a
end

-- Decide where each member should be and what it looks at.
function TV.plan()
    local n = #TV.order
    for i, name in ipairs(TV.order) do
        local e = TV.members[name]
        if e then
            local centre, radius = nil, nil
            if e.target_inst and e.target_inst.Parent then
                centre, radius = TV.world_of(e.target_inst)
            end
            if centre then
                -- stand a little way off, each member on its own side, slightly above
                local ang = (i - 1) * (2 * math.pi / math.max(n, 3)) + 0.6
                local off = Vector3.new(math.cos(ang), 0, math.sin(ang)) * (radius + 3.5)
                e.goal = centre + off + Vector3.new(0, math.max(1.5, radius * 0.35), 0)
                e.look_at = centre
                e.aim = centre
            else
                local home, mid = TV.home(i, n, e.huddle)
                e.goal = home
                e.look_at = mid
                e.aim = nil
            end
            if e.hl then
                local want = (centre ~= nil and e.target_exact) and e.target_inst or nil
                if e.hl.Adornee ~= want then e.hl.Adornee = want end
                e.hl.Enabled = want ~= nil
            end
            if not e.pos then
                -- a new member appears at the circle and then walks to its work
                e.pos = (TV.home(i, n))
                e.dir = Vector3.new(0, 0, -1)
            end
        end
    end
end

function TV.step(dt)
    TV.clock += dt
    TV.replan = (TV.replan or 0) + dt
    if TV.replan > 0.5 then
        TV.replan = 0
        pcall(TV.plan)
        if os.clock() - TV.last_update > 900 then   -- the server went quiet: do not leave ghosts
            TV.stop()
            return
        end
    end
    local move = 1 - math.exp(-dt * 2.6)
    local turn = 1 - math.exp(-dt * 7)
    local tags = {}
    for _, name in ipairs(TV.order) do
        local e = TV.members[name]
        if e and e.pos and e.goal then
            local goal = e.goal
            if e.aim == nil and e.busy then
                -- p61: at work on something with no place in the world: circle slowly, so it reads as busy
                local a = TV.clock * (0.8 + 0.12 * (e.phase % 3)) + e.phase
                local r = e.huddle and 0.45 or 1.1
                goal = goal + Vector3.new(math.cos(a) * r, math.sin(a * 1.7) * 0.35, math.sin(a) * r)
            end
            e.pos = e.pos:Lerp(goal, move)
            local row = TV.rows and TV.rows[name]
            if row and row.dot then   -- p61: the card's dot breathes while that member works
                row.dot.BackgroundTransparency = e.busy and (0.05 + 0.55 * (0.5 + 0.5 * math.sin(TV.clock * 4 + e.phase))) or 0
            end
            local bob = math.sin(TV.clock * 1.5 + e.phase) * 0.12
            local p = e.pos + Vector3.new(0, bob, 0)
            local want = e.look_at - p
            want = Vector3.new(want.X, want.Y * 0.35, want.Z)
            if want.Magnitude > 0.05 then
                local d = e.dir:Lerp(want.Unit, turn)
                if d.Magnitude > 0.001 then e.dir = d.Unit end
            end
            local cf = CFrame.lookAt(p, p + e.dir)
            e.shell.CFrame = cf
            e.core.CFrame = cf
            e.arrow.CFrame = cf * CFrame.new(0, 0, -1.15)
            -- the name tag sits just above the bubble, wherever the camera is
            local cam = workspace.CurrentCamera
            if cam and e.holder then
                local v, onscreen = cam:WorldToViewportPoint(p + Vector3.new(0, 1.55, 0))
                local show = onscreen and v.Z > 0 and v.Z < 3000
                e.holder.Visible = show
                if show then
                    e.status_label.Visible = v.Z < 220 and cam.ViewportSize.X >= 520   -- narrow viewport: name only, the card shows the status
                    table.insert(tags, { e = e, x = v.X, y = v.Y, z = v.Z })
                end
            end
            -- the laser fades in once the member has arrived, and fades out when it leaves
            local arrived = e.aim ~= nil and (e.pos - e.goal).Magnitude < 1.2
            e.laser_a += ((arrived and 0.25 or 1) - e.laser_a) * (1 - math.exp(-dt * 6))
            if e.aim and e.laser_a < 0.98 then
                local from = p + e.dir * 1.6
                local len = (e.aim - from).Magnitude
                if len > 0.2 then
                    e.laser.Height = len
                    e.laser.CFrame = CFrame.lookAt((from + e.aim) * 0.5, e.aim)
                    e.laser.Transparency = e.laser_a
                    e.dot.CFrame = CFrame.new(e.aim)
                    e.dot.Transparency = math.clamp(e.laser_a - 0.15, 0, 1)
                end
            else
                e.laser.Transparency = 1
                e.dot.Transparency = 1
            end
        end
    end
    -- name tags never cover each other: the nearest bubble keeps its spot, the others step up
    table.sort(tags, function(a, b) return a.z < b.z end)
    for i, t in ipairs(tags) do
        local with_status = t.e.status_label.Visible and t.e.status_label.Text ~= ""
        local w = t.e.tag.AbsoluteSize.X
        if with_status then w = math.max(w, t.e.status_label.TextBounds.X) end
        t.w = w + 8
        t.h = with_status and 41 or 24
        local y = t.y
        for _ = 1, 6 do
            local hit = false
            for j = 1, i - 1 do
                local o = tags[j]
                if math.abs(t.x - o.x) < (t.w + o.w) * 0.5 and y > o.top - 2 and y - t.h < o.bottom + 2 then
                    y = o.top - 3
                    hit = true
                end
            end
            if not hit then break end
        end
        t.bottom = y
        t.top = y - t.h
        t.e.lift = (t.e.lift or 0) + ((y - t.y) - (t.e.lift or 0)) * turn
        t.e.holder.Position = UDim2.fromOffset(t.x, t.y + t.e.lift)
    end
end

-- The small card in the corner of the viewport: who is on what.
function TV.card_build()
    if TV.card and TV.card.Parent then return end
    local sg = Instance.new("ScreenGui")
    sg.Name = "PipelineTeamCard"
    sg.Archivable = false
    sg.DisplayOrder = 50
    sg.ResetOnSpawn = false
    sg.Parent = TV.ensure_root()
    local fr = Instance.new("Frame")
    fr.AnchorPoint = Vector2.new(1, 0)
    fr.Position = UDim2.new(1, -14, 0, 14)
    fr.Size = UDim2.fromOffset(250, 0)
    fr.AutomaticSize = Enum.AutomaticSize.Y
    fr.BackgroundColor3 = Color3.fromRGB(11, 11, 13)
    fr.BackgroundTransparency = 0.12
    fr.BorderSizePixel = 0
    fr.Parent = sg
    local cr = Instance.new("UICorner"); cr.CornerRadius = UDim.new(0, 10); cr.Parent = fr
    local stroke = Instance.new("UIStroke"); stroke.Color = Color3.fromRGB(255, 90, 31); stroke.Transparency = 0.6; stroke.Parent = fr
    local pad = Instance.new("UIPadding")
    pad.PaddingTop = UDim.new(0, 10); pad.PaddingBottom = UDim.new(0, 10)
    pad.PaddingLeft = UDim.new(0, 12); pad.PaddingRight = UDim.new(0, 12)
    pad.Parent = fr
    local list = Instance.new("UIListLayout")
    list.Padding = UDim.new(0, 6)
    list.SortOrder = Enum.SortOrder.LayoutOrder
    list.Parent = fr
    local title = Instance.new("TextLabel")
    title.BackgroundTransparency = 1
    title.Size = UDim2.new(1, 0, 0, 16)
    title.Font = Enum.Font.GothamBold
    title.TextSize = 12
    title.TextColor3 = Color3.fromRGB(166, 166, 166)
    title.TextXAlignment = Enum.TextXAlignment.Left
    title.Text = "PIPELINE TEAM"
    title.LayoutOrder = 0
    title.Parent = fr
    local sc = Instance.new("UIScale")   -- a small viewport gets a small card, so the bubbles stay in view
    sc.Parent = fr
    TV.card_scale = sc
    TV.card = sg
    TV.card_frame = fr
    TV.rows = {}
end

function TV.card_row(name, e, order)
    local row = TV.rows[name]
    if not row or not row.frame.Parent then
        local f = Instance.new("Frame")
        f.BackgroundTransparency = 1
        f.Size = UDim2.new(1, 0, 0, 32)
        f.Parent = TV.card_frame
        local dot = Instance.new("Frame")
        dot.Size = UDim2.fromOffset(10, 10)
        dot.Position = UDim2.fromOffset(0, 4)
        dot.BackgroundColor3 = e.color
        dot.BorderSizePixel = 0
        dot.Parent = f
        local dc = Instance.new("UICorner"); dc.CornerRadius = UDim.new(1, 0); dc.Parent = dot
        local nm = Instance.new("TextLabel")
        nm.BackgroundTransparency = 1
        nm.Position = UDim2.fromOffset(18, 0)
        nm.Size = UDim2.new(1, -18, 0, 16)
        nm.Font = Enum.Font.GothamBold
        nm.TextSize = 13
        nm.TextColor3 = Color3.fromRGB(240, 255, 255)
        nm.TextXAlignment = Enum.TextXAlignment.Left
        nm.TextTruncate = Enum.TextTruncate.AtEnd
        nm.Parent = f
        local what = Instance.new("TextLabel")
        what.BackgroundTransparency = 1
        what.Position = UDim2.fromOffset(18, 16)
        what.Size = UDim2.new(1, -18, 0, 14)
        what.Font = Enum.Font.Gotham
        what.TextSize = 12
        what.TextColor3 = Color3.fromRGB(166, 166, 166)
        what.TextXAlignment = Enum.TextXAlignment.Left
        what.TextTruncate = Enum.TextTruncate.AtEnd
        what.Parent = f
        row = { frame = f, name = nm, what = what, dot = dot }
        TV.rows[name] = row
    end
    row.frame.LayoutOrder = order
    row.name.Text = e.role or name
    row.what.Text = e.line or ""
end

function TV.card_refresh()
    TV.card_build()
    local cam = workspace.CurrentCamera
    if cam and TV.card_scale then
        TV.card_scale.Scale = math.clamp(cam.ViewportSize.X / 900, 0.6, 1)
    end
    for name, row in pairs(TV.rows) do
        if not TV.members[name] then
            pcall(function() row.frame:Destroy() end)
            TV.rows[name] = nil
        end
    end
    for i, name in ipairs(TV.order) do
        local e = TV.members[name]
        if e then TV.card_row(name, e, i) end
    end
end

function TV.stop()
    TV.on = false
    if TV.conn then pcall(function() TV.conn:Disconnect() end) end
    TV.conn = nil
    if TV.root then pcall(function() TV.root:Destroy() end) end
    TV.root, TV.card, TV.card_frame, TV.labels = nil, nil, nil, nil
    TV.members, TV.order, TV.rows = {}, {}, {}
    TV.anchor = nil
end

function TV.start()
    if TV.on then return end
    TV.on = true
    TV.ensure_root()
    -- the team gathers in front of the camera, a little above the ground
    local cam = workspace.CurrentCamera
    local a = Vector3.new(0, 6, 0)
    if cam then
        local f = cam.Focus.Position
        if (f - cam.CFrame.Position).Magnitude > 120 or (f - cam.CFrame.Position).Magnitude < 4 then
            f = cam.CFrame.Position + cam.CFrame.LookVector * 28
        end
        a = Vector3.new(f.X, f.Y + 4, f.Z)
    end
    TV.anchor = a
    TV.conn = RunService.Heartbeat:Connect(function(dt)
        local ok, err = pcall(TV.step, math.min(dt, 0.1))
        if not ok then
            warn("[Pipeline] team view stopped: " .. tostring(err))
            TV.stop()
        end
    end)
end

-- input = { on = bool, members = { {name, role, color, status, target}, ... } }
function TV.apply(input)
    if RunService:IsRunning() then
        return true, { shown = 0, note = "play session" }, nil, nil
    end
    local list = type(input.members) == "table" and input.members or {}
    if input.on == false or #list == 0 then
        TV.stop()
        return true, { shown = 0 }, nil, nil
    end
    TV.start()
    TV.last_update = os.clock()
    local seen = {}
    for _, m in ipairs(list) do
        local name = tostring(m.name or "")
        if name ~= "" and #TV.order < 8 or TV.members[name] then
            seen[name] = true
            local e = TV.members[name] or TV.make(name, m)
            e.role = tostring(m.role or name)
            if e.tag then e.tag.Text = e.role end
            local target = tostring(m.target or "")
            local status = tostring(m.status or "")
            if target ~= e.target_path then
                e.target_path = target
                e.target_inst, e.target_exact = nil, false
                if target ~= "" then
                    local inst, exact = TV.find(target)
                    e.target_inst, e.target_exact = inst, exact
                end
            elseif target ~= "" and not e.target_exact then
                -- the thing may exist by now
                local inst, exact = TV.find(target)
                e.target_inst, e.target_exact = inst, exact
            end
            e.line = (target ~= "" and (status ~= "" and (status .. " · ") or "") .. TV.leaf(target)) or status
            e.busy = TV.is_busy(status)
            e.huddle = TV.is_meeting(status)
            if e.status_label then e.status_label.Text = e.line end
            if TV.feed then pcall(TV.feed, name, e.role, tostring(m.say or ""), e.line, tostring(m.color or "FFFFFF"), e.busy) end
        end
    end
    for _, name in ipairs(table.clone(TV.order)) do
        if not seen[name] then TV.drop(name) end
    end
    pcall(TV.plan)
    pcall(TV.card_refresh)
    return true, { shown = #TV.order }, nil, nil
end

--------------------------------------------------------------------------------
-- read_model_ids (p59): the user's own Studio loads a Model the USER owns and
-- reports the mesh + texture ids inside it. The server cannot download a
-- private user-owned Model, so it asks here. Edit mode, places nothing.
--------------------------------------------------------------------------------
local function run_read_model_ids(input)
    local id = tonumber(input.asset_id or input.id or input.model_id)
    if not id or id <= 0 then
        return false, { error = "asset_id required", error_code = "bad_asset" }, nil, nil
    end
    local tries = math.min(math.max(tonumber(input.tries) or 8, 1), 12)
    local model, lastErr
    for i = 1, tries do
        local ok, m = pcall(function()
            return game:GetService("InsertService"):LoadAsset(id)
        end)
        if ok and m then model = m break end
        lastErr = tostring(m)
        if i < tries then task.wait(4) end   -- a fresh upload can lag a few seconds
    end
    if not model then
        return false, { error = "could not load model " .. tostring(id) .. ": "
                            .. tostring(lastErr), error_code = "load_failed" }, nil, nil
    end
    local meshes = {}
    for _, d in ipairs(model:GetDescendants()) do
        if d:IsA("MeshPart") then
            local sa = d:FindFirstChildOfClass("SurfaceAppearance")
            table.insert(meshes, {
                name       = d.Name,
                mesh_id    = d.MeshId,
                texture_id = d.TextureID,
                color_map  = sa and sa.ColorMap or "",
            })
        end
    end
    pcall(function() model:Destroy() end)
    if #meshes == 0 then
        return false, { error = "model " .. tostring(id) .. " has no mesh",
                        error_code = "no_mesh" }, nil, nil
    end
    return true, { asset_id = id, meshes = meshes,
                   mesh_id = meshes[1].mesh_id,
                   texture_id = meshes[1].texture_id,
                   color_map = meshes[1].color_map }, nil, nil
end

local function run_tool(tool, input)
    if     tool == "create_script"    then return run_create_script(input)
    elseif tool == "install_gui"      then return run_install_gui(input)
    elseif tool == "install_animation" then return run_install_animation(input)
    elseif tool == "publish_animation" then return run_publish_animation(input)
    elseif tool == "guided_publish"   then return GuidedPub.run(input)
    elseif tool == "edit_script"      then return run_edit_script(input)
    elseif tool == "fix_script"       then return run_fix_script(input)
    elseif tool == "delete_script"    then return run_delete_script(input)
    elseif tool == "create_instance"  then return run_create_instance(input)
    elseif tool == "delete_instance"  then return run_delete_instance(input)
    elseif tool == "set_property"     then return run_set_property(input)
    elseif tool == "read_properties"
        or tool == "inspect"          then return run_read_properties(input)
    elseif tool == "create_animation" then return run_create_animation(input)
    elseif tool == "spawn_rig"        then return run_spawn_rig(input)
    elseif tool == "stop_playtest"
        or tool == "force_edit_mode"  then return run_stop_playtest(input)
    elseif tool == "playtest_start"   then return PT2_start_session(input)
    elseif tool == "playtest_act"     then
        -- ctx routing means this only reaches the EDIT copy when no play
        -- session is live to claim it — answer honestly instead of hanging.
        return false, {
            error      = "no live playtest session — call playtest_start "
                .. "first, then drive it with playtest_act",
            error_code = "no_play_session",
        }, nil, nil
    elseif tool == "run_playtest"
        or tool == "playtest"         then return run_playtest(input)
    elseif tool == "run_test"
        or tool == "run_service"     then return run_test(input)
    elseif tool == "generate_mesh"
        or tool == "generate_model"   then return run_generate_mesh(input)
    elseif tool == "insert_mesh"      then return run_insert_mesh(input)
    elseif tool == "read_model_ids"   then return run_read_model_ids(input)
    elseif tool == "team_view"        then return TV.apply(input)
    else
        return false, {
            error      = "Unknown tool: " .. tostring(tool),
            error_code = "unknown_tool",
        }, nil, nil
    end
end

--------------------------------------------------------------------------------
-- EXECUTE TOOL  (M3 ACK + M5 idempotency + M4 read-back)
--------------------------------------------------------------------------------

local function execute_tool(work)
    local call_id = tostring(work.call_id or "")
    local tool    = tostring(work.tool or "")
    local input   = work.input or {}
    if type(input) ~= "table" then input = {} end

    if call_id == "" or tool == "" then
        warn("[Pipeline] Malformed work item (missing call_id or tool)")
        return
    end

    -- Cancellation check: server may have cancelled this call_id while it was
    -- queued.  Post a cancelled result and skip execution entirely.
    if _cancelled_call_ids[call_id] then
        _cancelled_call_ids[call_id] = nil  -- consume entry
        v5_post_result(call_id, false, { error = "cancelled", error_code = "cancelled" },
                       tool, nil, nil)
        return
    end

    -- M5: idempotency — return cached result without re-executing
    local cached = cache_get(call_id)
    if cached then
        v5_post_result(call_id, cached.success, cached.result, cached.name,
                       cached.source_after, cached.value_after)
        return
    end

    -- M1: per-script-path mutex — serialise mutation tools that share a script
    -- path so two parallel workers cannot race on the same file.
    local script_path = nil
    if tool == "fix_script" or tool == "edit_script" or tool == "create_script"
        or tool == "delete_script" then
        script_path = tostring(
            input.target or input.path or input.script or input.name or "")
        -- rev 01104 (P5): canonicalize so two calls naming the SAME script via
        -- different path forms ("game.SSS.Foo" vs "SSS.Foo" vs " Foo ") take
        -- the SAME mutex — otherwise parallel workers race on one file and
        -- the second edit clobbers the first.
        script_path = script_path:gsub("%[%d+%]", ""):gsub("^[Gg]ame%.", "")
        script_path = script_path:gsub("^%s+", ""):gsub("%s+$", "")
    end
    if script_path and script_path ~= "" then
        -- Busy-wait up to 10s in 50ms ticks (10s >> any single tool execution)
        local wait_start = os.clock()
        while _execute_locks[script_path] do
            if os.clock() - wait_start > 10 then
                warn("[Pipeline] lock timeout for script: " .. script_path)
                -- 2026-05-26 p24: stale lock cleared. Without this, a
                -- leaked lock from a prior crash would block the path
                -- forever after the 10s busy-wait gives up.
                _execute_locks[script_path] = nil
                break
            end
            task.wait(0.05)
        end
        _execute_locks[script_path] = true
    end

    -- M3: ACK before execution
    v5_ack(call_id)

    -- p60: the team's live view is not a build step. It is not written to the
    -- activity log and needs no watchdog: draw, answer, done.
    if tool == "team_view" then
        local okv, a, b = pcall(TV.apply, input)
        v5_post_result(call_id, okv and a == true,
            (okv and type(b) == "table") and b or { error = tostring(a), error_code = "team_view_failed" },
            tool, nil, nil)
        return
    end

    -- Activity log: announce start (target picked from the most common input keys)
    local target_label = tostring(
        input.target or input.path or input.script or input.name or
        input.instance_path or input.instance or "")
    local start_line = tool
    if target_label ~= "" then start_line = tool .. " " .. target_label end
    plugin_state.last_call_label = start_line
    ui_log("info", start_line)

    -- p29 (2026-07-02): EXECUTION WATCHDOG. A tool handler can BLOCK forever
    -- with no Lua error at all — the #1 case is Studio's "Allow Script
    -- Injection" permission modal: UpdateSourceAsync parks the coroutine until
    -- the user clicks, so create_script posts NOTHING, the server lease
    -- expires, WTQ redelivers, the re-claim blocks on the same modal…
    -- (prod 2026-07-02: a user's build sat silent 10 min on exactly this —
    -- create_animation/create_instance landed, both create_scripts vanished).
    -- If the handler hasn't finished inside its deadline, post an explicit
    -- error result so the model/user get told what to click instead of dead
    -- air. If the real result lands later it is still cached for idempotent
    -- redelivery, but not re-posted (the server dedups by call_id anyway).
    local _WD_DEADLINES = {
        run_playtest     = 240,
        run_test         = 120,
        read_model_ids   = 60,
        create_animation = 120,
        generate_mesh    = 180,
        spawn_rig        = 60,
        -- p36: animator tools were falling into the default 30s — a cold
        -- rig spawn (web-yielding avatar assets) runs 40-60s+, the watchdog
        -- posted a timeout AND suppressed the late real result, so publish
        -- looked like "rig spawns, dialog never opens". Keep these UNDER the
        -- server's 120s wait so an honest error still arrives first.
        install_animation = 110,
        publish_animation = 55,
        -- p43: opens/refreshes the guided publish panel — pure UI, fast.
        guided_publish    = 25,
        -- p37: map pushes — insert_mesh loads Open-Cloud assets (or builds
        -- an EditableMesh locally) and can honestly run 30-90s; a 52-node
        -- create_instance packet can exceed 30s while Studio churns. The
        -- default 30s watchdog was killing them mid-work on big maps.
        insert_mesh     = 110,
        -- p39: fast push sends up to 600-node packets (was 52) — one big
        -- packet replaces ~12 round-trips, but Studio needs real time to
        -- instantiate it. Keep under the server's 120s wait.
        create_instance = 115,
    }
    local _wd = { done = false, fired = false }
    task.delay(_WD_DEADLINES[tool] or 30, function()
        if _wd.done then return end
        _wd.fired = true
        ui_log("err", tool .. " — timed out inside Studio (watchdog)")
        warn("[Pipeline] watchdog: " .. tool .. " did not finish — posting timeout result")
        pcall(function()
            v5_post_result(call_id, false, {
                error = "Tool '" .. tool .. "' did not finish inside Studio in "
                    .. tostring(_WD_DEADLINES[tool] or 30) .. "s. If Roblox "
                    .. "Studio is showing a permission popup (e.g. 'Allow "
                    .. "Script Injection' for Pipeline), TELL THE USER to "
                    .. "click Allow, then retry. Otherwise Studio may be "
                    .. "paused, busy, or mid-playtest.",
                error_code = "studio_tool_timeout",
            }, tool, nil, nil)
        end)
        -- Release the per-script lock so redeliveries aren't chained behind
        -- a permanently blocked handler.
        if script_path and script_path ~= "" then
            _execute_locks[script_path] = nil
        end
    end)

    -- Execute (timed)
    -- 2026-05-26 p24: WRAP IN PCALL. Without this, any uncaught Lua error
    -- inside run_tool (property setter throws, nil deref, HTTP failure
    -- bubbling as assert) kills the spawned coroutine silently — the
    -- per-script lock never releases AND v5_post_result never fires.
    -- Server lease expires 45s later, WTQ redelivers, plugin re-claims,
    -- re-errors → infinite stranded loop. Root cause of the "plugin
    -- hung mid-session" report.
    local t0 = os.clock()
    local success, result, source_after, value_after
    local _ok_run, _r1, _r2, _r3, _r4 = pcall(run_tool, tool, input)
    _wd.done = true
    if _ok_run then
        success, result, source_after, value_after = _r1, _r2, _r3, _r4
    else
        success = false
        -- p28: CLASSIFY the throw. The #1 real-world case is Studio's
        -- "Script Injection" permission being denied by the user - every
        -- script write throws, the model sees an opaque plugin_lua_error and
        -- retries forever (11 prod hits on 2026-07-01, incl. localized French
        -- text). Give it an explicit user-action message and a stable code so
        -- the server/model can stop retrying and tell the user what to click.
        local _errLower = tostring(_r1):lower()
        if _errLower:find("injection", 1, true)
            or _errLower:find("permission", 1, true)
            or _errLower:find("autorisation", 1, true)
            or _errLower:find("berechtigung", 1, true)
            or _errLower:find("permiso", 1, true)
            -- 2026-07-09 prod: Turkish Studio said "betik ekleme izni
            -- verilmedi" and fell through to opaque plugin_lua_error →
            -- the injection funnel/modal never fired for that user.
            or _errLower:find("izin", 1, true)
            or _errLower:find("izni", 1, true)
            or _errLower:find("permiss", 1, true)   -- pt permissão / it permesso
            or _errLower:find("autorizza", 1, true) -- it autorizzazione
            or _errLower:find("разреш", 1, true)    -- ru разрешение
            or _errLower:find("betik ekleme", 1, true) then
            result = {
                error = "SCRIPT INJECTION PERMISSION DENIED - Roblox Studio is "
                    .. "blocking the Pipeline plugin from creating/editing "
                    .. "scripts. This is a USER setting; retrying cannot fix "
                    .. "it. TELL THE USER: open the Plugins tab -> Manage "
                    .. "Plugins (or the permission popup), find 'Pipeline', "
                    .. "enable 'Script Injection', then send the request "
                    .. "again. (raw: " .. tostring(_r1) .. ")",
                error_code = "script_injection_denied",
            }
        else
            result = {
                error = "plugin_lua_error: " .. tostring(_r1),
                error_code = "plugin_lua_error",
            }
        end
        warn("[Pipeline] tool errored: " .. tostring(tool) .. " — " .. tostring(_r1))
    end
    -- p29: keep the heartbeat's injection_status TRUTHFUL against live results.
    -- Without this, a probe-time "denied" would ride every heartbeat and fight
    -- the server's reactive granted-on-success update (banner stuck forever).
    if tool == "create_script" or tool == "edit_script" or tool == "fix_script" then
        if success then
            plugin_state.injection_status = "granted"
        elseif type(result) == "table"
            and result.error_code == "script_injection_denied" then
            plugin_state.injection_status = "denied"
        end
    end
    local latency_ms = math.floor((os.clock() - t0) * 1000)
    plugin_state.last_call_latency_ms = latency_ms
    plugin_state.calls_handled = plugin_state.calls_handled + 1

    -- Release per-script lock (always — even on error)
    if script_path and script_path ~= "" then
        _execute_locks[script_path] = nil
    end

    -- Ensure result is a table (guards against nil from errant pcall)
    if type(result) ~= "table" then
        result = { raw = tostring(result) }
    end

    -- Activity log: outcome
    if success then
        ui_log("ok", string.format("%s (%dms)", tool, latency_ms))
    else
        local err_msg = (type(result) == "table" and (result.error or result.error_code)) or "failed"
        ui_log("err", string.format("%s — %s", tool, tostring(err_msg)))
    end

    -- M5: cache for idempotency
    cache_put(call_id, success, result, tool, source_after, value_after)

    -- M4: POST result with read-back fields
    -- p29: if the watchdog already posted a timeout for this call, the server
    -- consumed it and moved on — the late real result stays in the idempotency
    -- cache (for redeliveries) but must not be double-posted.
    if not _wd.fired then
        v5_post_result(call_id, success, result, tool, source_after, value_after)
    end
end

--------------------------------------------------------------------------------
-- MAIN LOOP
--------------------------------------------------------------------------------

-- 2026-05-23 idle-mode: after IDLE_AFTER_S seconds of no work, the worker
-- stops holding 25s long-polls and drops to lightweight 5s heartbeats. The
-- server reports has_work=true on heartbeat when something is queued; that
-- flips the worker back into long-poll mode. This keeps Cloud Run idle (no
-- requests in flight) during quiet periods → bills go to near zero.
local IDLE_AFTER_S = 300  -- 5 minutes of no work → enter idle-mode

local function poll_worker(worker_id)
    local my_gen = plugin_state.worker_gen
    local _last_work_at = os.time()
    local _mode = "active"  -- "active" (long-poll) | "idle" (heartbeat-only)
    -- rev p24 (2026-05-27): count consecutive HTTP failures so we can
    -- trigger a /v5/connect re-register after the gunicorn worker
    -- recycle (or a network blip) tears the long-poll TCP connection.
    -- Empty work returns (200 with empty work[]) are NOT failures.
    local _http_fail_count = 0
    local _RECONNECT_AFTER_FAILS = 3

    while plugin_state.connected and not plugin_state.user_disconnected
          and my_gen == plugin_state.worker_gen do

        if _mode == "active" then
            -- ACTIVE: 25s long-poll, heartbeat between polls if needed.
            local work, http_ok, reindex_req = v5_poll()
            -- p48: server asked for an index refresh (stale tree detected).
            -- Spawned so the poll loop never blocks on a full walk;
            -- v5_sync_codebase's own 5s throttle bounds the cost.
            if reindex_req then
                task.spawn(function()
                    pcall(function() v5_sync_codebase(false) end)
                end)
            end
            if not http_ok then
                _http_fail_count = _http_fail_count + 1
                -- rev p24c (2026-05-27): BOTH workers can trigger reconnect.
                -- The shared plugin_state.reconnect_in_progress flag prevents
                -- double-fire when both workers hit the threshold at once.
                if _http_fail_count >= _RECONNECT_AFTER_FAILS
                   and not plugin_state.reconnect_in_progress then
                    plugin_state.reconnect_in_progress = true
                    print(string.format(
                        "[Pipeline] worker %d: %d consecutive poll HTTP failures — re-registering session",
                        worker_id, _http_fail_count
                    ))
                    -- p47 (owner 2026-07-28 "THAT SHOULD NEVER HAPPEN"):
                    -- a server deploy/instance roll tears in-flight
                    -- long-polls by design and the reconnect below heals it
                    -- in seconds — showing a scary "connection torn" banner
                    -- BEFORE even trying made routine self-healing look
                    -- like an outage. Console keeps the detail; the UI only
                    -- hears about it if the reconnect actually FAILS.
                    -- rev p24b: v5_connect is internally pcall-wrapped and
                    -- returns false on 404/409/non-200.  pcall(v5_connect)
                    -- ALWAYS returns true (no exception), so the previous
                    -- code reset _http_fail_count even when the server
                    -- rejected us.  Call directly + use the return value.
                    local ok_call, reconnect_ok = pcall(v5_connect)
                    plugin_state.reconnect_in_progress = false
                    if ok_call and reconnect_ok == true then
                        _http_fail_count = 0
                        print("[Pipeline] session re-registered — connection restored")
                        -- Nudge the other worker to recover sooner: bump
                        -- the last-successful-poll watermark so its next
                        -- failed poll doesn't pile on top of stale fails.
                        plugin_state.last_successful_poll_at = os.time()
                    else
                        ui_log("warn", "Connection hiccup — retrying in the background…")
                        -- Don't reset; let the next iteration retry or
                        -- the worker exit if user_disconnected.  Back off
                        -- to avoid hammering a known-bad endpoint.
                        task.wait(2)
                    end
                elseif _http_fail_count >= _RECONNECT_AFTER_FAILS
                       and plugin_state.reconnect_in_progress then
                    -- Other worker is already handling reconnect; wait
                    -- briefly and re-check next iter rather than spinning.
                    task.wait(1)
                end
                task.wait(POLL_INTERVAL_S)
            elseif #work > 0 then
                _http_fail_count = 0
                plugin_state.last_successful_poll_at = os.time()
                _last_work_at = os.time()
                -- 2026-05-24 fix: install_calls race.  An animation install
                -- batch contains [create_instance(Folder "Animations"),
                -- create_script(PiscesAnimator), create_script("Animations/
                -- <clip>")].  Spawning all three in parallel via task.spawn
                -- races: the clip's create_script can resolve its parent
                -- ("ReplicatedStorage.Animations") before the Folder finishes
                -- being parented in, so the script lands at the wrong place
                -- or fails silently.  Solution: run parent-creating tools
                -- (create_instance, create_animation) SYNCHRONOUSLY first,
                -- then spawn the rest in parallel.  Order within each phase
                -- preserves arrival order from /v5/poll, which the server
                -- already topo-sorts dependencies in.
                local _is_parent_create = function(w)
                    local t = w and w.tool
                    return t == "create_instance" or t == "create_animation"
                end
                -- rev 01104 (P4b): execute_tool wraps run_tool in pcall, but
                -- it can still throw BEFORE that (cache_get / v5_ack / the
                -- lock wait) — a synchronous throw here would break the whole
                -- poll loop, and a spawned-worker throw dies with no result
                -- posted (server waits out the deadline). Guard the call
                -- sites: on a throw, surface a tool error so the call resolves.
                local function _safe_execute(w)
                    local ok, err = pcall(execute_tool, w)
                    if not ok then
                        warn("[Pipeline] execute_tool threw: " .. tostring(err))
                        pcall(function()
                            v5_post_result(tostring(w and w.call_id or ""), false, {
                                error      = "plugin dispatcher error: " .. tostring(err),
                                error_code = "dispatcher_error",
                            }, tostring(w and w.tool or ""), nil, nil)
                        end)
                    end
                end
                for _, w in ipairs(work) do
                    if _is_parent_create(w) then
                        -- Synchronous: block this poll loop tick until the
                        -- Folder/Instance lands.  Cheap (<50ms typical).
                        _safe_execute(w)
                    end
                end
                for _, w in ipairs(work) do
                    if not _is_parent_create(w) then
                        task.spawn(_safe_execute, w)
                    end
                end
            else
                -- No work returned (empty 200). This IS a successful poll —
                -- reset failure counter so a long quiet period doesn't bank
                -- up fake "failures" and prematurely trip reconnect.
                _http_fail_count = 0
                plugin_state.last_successful_poll_at = os.time()
                -- No work returned. Check if it's been long enough to idle.
                if worker_id == 1 then
                    local now = os.time()
                    if (now - plugin_state.last_heartbeat_at) >= HEARTBEAT_INTERVAL_S then
                        v5_heartbeat()
                    end
                end
                if (os.time() - _last_work_at) >= IDLE_AFTER_S then
                    _mode = "idle"
                    print("[Pipeline] entering idle-mode after " ..
                        IDLE_AFTER_S .. "s of no work — switching to heartbeat-only")
                    ui_log("trace", "Idle (saves cost). Next message wakes within " ..
                        HEARTBEAT_INTERVAL_S .. "s.")
                end
                task.wait(POLL_INTERVAL_S)
            end

        else
            -- IDLE: only heartbeat, every HEARTBEAT_INTERVAL_S seconds. The
            -- heartbeat response tells us if the server has queued work.
            local has_work = v5_heartbeat()
            if has_work then
                _mode = "active"
                _last_work_at = os.time()
                print("[Pipeline] resuming active polling (work pending)")
                ui_log("trace", "Resuming active polling — work pending")
            else
                task.wait(HEARTBEAT_INTERVAL_S)
            end
        end

        if worker_id == 1 then
            cache_prune()
        end
    end
end

local function main_loop()
    -- 2026-05-23: defense in depth. If the user clicked Disconnect, refuse
    -- to start polling even if main_loop is re-triggered by Studio lifecycle
    -- (e.g. play-mode toggle, plugin reload).
    if plugin_state.user_disconnected then
        print("[Pipeline] user_disconnected=true — main_loop refusing to start. Click Reconnect to resume.")
        return
    end

    if not v5_connect() then
        -- v5_connect already printed the reason; exit cleanly
        plugin_state.connected = false
        return
    end

    -- M1: spawn POLL_WORKERS parallel poll coroutines (new generation —
    -- retires any stale workers from a previous connect)
    plugin_state.worker_gen = plugin_state.worker_gen + 1
    for i = 1, POLL_WORKERS do
        task.spawn(poll_worker, i)
    end
end

--------------------------------------------------------------------------------
-- API KEY — load from plugin settings (read BEFORE widget so masked display
--           reflects current state on first paint).
--------------------------------------------------------------------------------

plugin_state.api_key = tostring(plugin:GetSetting("pisces_api_key") or "")

--------------------------------------------------------------------------------
-- DOCK WIDGET UI  (Pisces V5 control panel — Pisces brand)
-- Pisces design tokens (from web_app/static/css/style.css):
--   bg0     #05070f   bg1     #0a0a0a   bg2     #121212   bg3     #1c1c1c
--   text    #f0ffff   sub     #a6a6a6   line    rgba(147,171,208,0.24)
--   accent  #ff5a1f   accent-dim #c2400f   info  #ff5a1f
--   ok      #50ff78   warn    #ffdc64   danger  #ff6464
--------------------------------------------------------------------------------

local UI_LOG_MAX = 120

local C = {
    bg0          = Color3.fromRGB(11, 11, 13),
    bg1          = Color3.fromRGB(17, 17, 20),
    bg2          = Color3.fromRGB(23, 24, 28),
    bg3          = Color3.fromRGB(34, 36, 42),
    line         = Color3.fromRGB(150, 150, 160),   -- used w/ stroke Transparency 0.76
    line_strong  = Color3.fromRGB(255, 90, 31),     -- used w/ stroke Transparency 0.55
    text         = Color3.fromRGB(255, 255, 255),
    sub          = Color3.fromRGB(170, 170, 178),
    faint        = Color3.fromRGB(110, 110, 118),
    accent       = Color3.fromRGB(255, 90, 31),
    accent_dim   = Color3.fromRGB(150, 60, 25),
    accent_hover = Color3.fromRGB(255, 125, 75),
    info         = Color3.fromRGB(255, 255, 255),
    ok           = Color3.fromRGB(80, 255, 120),
    warn         = Color3.fromRGB(255, 220, 100),
    danger       = Color3.fromRGB(255, 100, 100),
    danger_hover = Color3.fromRGB(255, 130, 130),
    on_accent    = Color3.fromRGB(255, 255, 255),   -- text color on top of accent
    input_bg     = Color3.fromRGB(8, 8, 8),
}

-- p48b: UI toolkit + panel state live in ONE table, not top-level locals.
-- Luau caps a chunk at 200 local registers; cloud-compiled plugin builds
-- enforce it strictly (marketplace installs died at local #201 while local
-- .lua files squeaked by). Add new top-level state to a table, not a local.
local UI = {}
UI.HEX = {
    text  = "FFFFFF", sub   = "AAAAB2", faint = "6E6E76",
    accent= "FF5A1F", info  = "FFFFFF",
    ok    = "8EE9B6", warn  = "FFDC64", danger= "FF6464",
}

-- Helpers -----------------------------------------------------------------

function UI.add_corner(inst, r)
    local c = Instance.new("UICorner")
    c.CornerRadius = UDim.new(0, r or 8)
    c.Parent = inst
end

function UI.add_padding(inst, t, r, b, l)
    -- Single-arg = all four equal
    if r == nil then r, b, l = t, t, t end
    local p = Instance.new("UIPadding")
    p.PaddingTop    = UDim.new(0, t)
    p.PaddingRight  = UDim.new(0, r)
    p.PaddingBottom = UDim.new(0, b)
    p.PaddingLeft   = UDim.new(0, l)
    p.Parent = inst
end

function UI.add_stroke(inst, color, thickness, transparency)
    local s = Instance.new("UIStroke")
    s.Color = color or C.line
    s.Thickness = thickness or 1
    s.Transparency = transparency or 0.76
    s.ApplyStrokeMode = Enum.ApplyStrokeMode.Border
    s.Parent = inst
    return s
end

function UI.add_vlist(parent, gap)
    local l = Instance.new("UIListLayout")
    l.SortOrder = Enum.SortOrder.LayoutOrder
    l.FillDirection = Enum.FillDirection.Vertical
    l.Padding = UDim.new(0, gap or 10)
    l.Parent = parent
    return l
end

function UI.add_hlist(parent, gap, valign)
    local l = Instance.new("UIListLayout")
    l.SortOrder = Enum.SortOrder.LayoutOrder
    l.FillDirection = Enum.FillDirection.Horizontal
    l.Padding = UDim.new(0, gap or 8)
    l.VerticalAlignment = valign or Enum.VerticalAlignment.Center
    l.Parent = parent
    return l
end

function UI.make_frame(parent, props)
    local f = Instance.new("Frame")
    f.BackgroundColor3 = C.bg1
    f.BorderSizePixel = 0
    if props then for k, v in pairs(props) do f[k] = v end end
    f.Parent = parent
    return f
end

function UI.make_label(parent, text, props)
    local l = Instance.new("TextLabel")
    l.BackgroundTransparency = 1
    l.Font = Enum.Font.GothamMedium
    l.TextSize = 13
    l.TextColor3 = C.text
    l.TextXAlignment = Enum.TextXAlignment.Left
    l.TextYAlignment = Enum.TextYAlignment.Center
    l.RichText = true
    l.Text = text or ""
    if props then for k, v in pairs(props) do l[k] = v end end
    l.Parent = parent
    return l
end

function UI.make_section_label(parent, text, order)
    return UI.make_label(parent, text, {
        Size = UDim2.new(1, 0, 0, 14),
        TextColor3 = C.sub,
        TextSize = 11,
        Font = Enum.Font.GothamBold,
        LayoutOrder = order,
    })
end

function UI.make_panel(parent, order, height)
    local p = UI.make_frame(parent, {
        BackgroundColor3 = C.bg2,
        Size = UDim2.new(1, 0, 0, height or 0),
        AutomaticSize = height and Enum.AutomaticSize.None or Enum.AutomaticSize.Y,
        LayoutOrder = order,
    })
    UI.add_corner(p, 8)
    UI.add_stroke(p, C.line, 1, 0.76)
    UI.add_padding(p, 10)
    return p
end

function UI.make_kv(parent, label, initial_value, mono)
    local row = Instance.new("Frame")
    row.BackgroundTransparency = 1
    row.Size = UDim2.new(1, 0, 0, 18)
    row.Parent = parent
    local L = Instance.new("TextLabel")
    L.BackgroundTransparency = 1
    L.Position = UDim2.fromOffset(0, 0)
    L.Size = UDim2.new(0, 78, 1, 0)
    L.Font = Enum.Font.GothamMedium
    L.TextSize = 12
    L.TextColor3 = C.sub
    L.TextXAlignment = Enum.TextXAlignment.Left
    L.TextYAlignment = Enum.TextYAlignment.Center
    L.Text = label
    L.Parent = row
    local V = Instance.new("TextLabel")
    V.BackgroundTransparency = 1
    V.Position = UDim2.fromOffset(82, 0)
    V.Size = UDim2.new(1, -82, 1, 0)
    V.Font = mono and Enum.Font.RobotoMono or Enum.Font.GothamSemibold
    V.TextSize = 12
    V.TextColor3 = C.text
    V.TextXAlignment = Enum.TextXAlignment.Left
    V.TextYAlignment = Enum.TextYAlignment.Center
    V.RichText = true
    V.Text = initial_value or "—"
    V.Parent = row
    return row, V
end

function UI.make_button(parent, text, kind)
    -- kind ∈ "primary" | "danger" | "ghost"
    local b = Instance.new("TextButton")
    b.BorderSizePixel = 0
    b.AutoButtonColor = false
    b.Font = Enum.Font.GothamBold
    b.TextSize = 13
    b.Text = text
    UI.add_corner(b, 6)
    local bg, bg_hover, text_color, stroke_color, stroke_trans
    if kind == "primary" then
        bg, bg_hover = C.accent, C.accent_hover
        text_color = C.on_accent
        stroke_color, stroke_trans = nil, nil
    elseif kind == "danger" then
        bg, bg_hover = C.bg2, C.bg3
        text_color = C.danger
        stroke_color, stroke_trans = C.danger, 0.45
    else  -- ghost
        bg, bg_hover = C.bg2, C.bg3
        text_color = C.sub
        stroke_color, stroke_trans = C.line, 0.7
    end
    b.BackgroundColor3 = bg
    b.TextColor3 = text_color
    if stroke_color then UI.add_stroke(b, stroke_color, 1, stroke_trans) end
    -- Hover only fires when Active=true.  External state managers (e.g. the
    -- connect-button state machine) can disable Active to lock the visual
    -- in whatever colour they set.
    b.MouseEnter:Connect(function()
        if not b.Active then return end
        b.BackgroundColor3 = bg_hover
        if kind == "danger" then b.TextColor3 = C.danger_hover end
    end)
    b.MouseLeave:Connect(function()
        if not b.Active then return end
        b.BackgroundColor3 = bg
        if kind == "danger" then b.TextColor3 = C.danger end
    end)
    b.Parent = parent
    return b
end

function UI.mask_key(key)
    if not key or key == "" then return "<font color='#6E6E6E'>(not set — paste a key below)</font>" end
    if #key <= 4 then
        return "<font color='#6E6E6E'>••••</font>  <font color='#A6A6A6'>(" .. #key .. " chars)</font>"
    end
    local bullets = string.rep("•", math.min(12, #key - 4))
    return string.format(
        "<font color='#6E6E6E'>%s</font><font color='#F0FFFF'>%s</font>" ..
        "  <font color='#A6A6A6'>(%d chars)</font>",
        bullets, key:sub(-4), #key)
end

function UI.short_id(id)
    if not id or id == "" then return "—" end
    if #id <= 10 then return id end
    return id:sub(1, 8) .. "…"
end

function UI.fmt_age(ts)
    if not ts or ts == 0 then return "—" end
    local age = os.time() - ts
    if age < 0 then age = 0 end
    if age < 60 then return age .. "s ago" end
    if age < 3600 then return math.floor(age / 60) .. "m ago" end
    return math.floor(age / 3600) .. "h ago"
end

--------------------------------------------------------------------------------
-- GUIDED ANIMATION PUBLISH (p43)
-- Roblox has no Open Cloud Animation type — clips only mint in-Studio. When
-- CreateAssetAsync auto-mint is unavailable, the server sends ONE
-- guided_publish call and this panel walks the user through hand-publishing:
-- one Save-to-Roblox dialog at a time (auto-opened dialogs REPLACE each
-- other — 9 clips previously yielded 1 usable Submit), paste each
-- AnimationId back, the plugin relays it to /v5/anim_publish so the agent
-- wires it later. The opt-out button flips the project to PiscesAnimator
-- module mode (no ids needed at all). Populated here (not at the forward
-- declaration) because the panel needs the UI helpers above.
--------------------------------------------------------------------------------
do
    local Selection = game:GetService("Selection")
    local PENDING_HEX, DONE_HEX, MODULE_HEX = "FFDC64", "50FF78", "00D5FF"

    local function tag_line(clipName, status, hex)
        return string.format("%s  <font color='#%s'>%s</font>",
            clipName, hex, status)
    end

    -- floating status tag over a rig's head
    local function ensure_tag(rig, clipName, status, hex)
        local head = rig:FindFirstChild("Head") or rig.PrimaryPart
        if not head then return end
        local tag = rig:FindFirstChild("PiscesPublishTag", true)
        if not tag then
            tag = Instance.new("BillboardGui")
            tag.Name = "PiscesPublishTag"
            tag.Size = UDim2.new(0, 230, 0, 26)
            tag.StudsOffset = Vector3.new(0, 2.4, 0)
            tag.AlwaysOnTop = true
            local t = Instance.new("TextLabel")
            t.Name = "Line"
            t.BackgroundColor3 = Color3.fromRGB(10, 10, 10)
            t.BackgroundTransparency = 0.25
            t.BorderSizePixel = 0
            t.Size = UDim2.fromScale(1, 1)
            t.Font = Enum.Font.GothamBold
            t.TextSize = 12
            t.RichText = true
            t.TextColor3 = C.text
            t.Parent = tag
            tag.Parent = head
        end
        local line = tag:FindFirstChild("Line")
        if line then line.Text = tag_line(clipName, status, hex) end
    end

    function GuidedPub.stage_rig(rig, clipName, reused)
        pcall(function()
            if not reused and rig.PrimaryPart then
                -- fresh rigs line up in a row beside the rightmost PiscesRig
                -- (reused rigs stay wherever the user put them)
                local maxX, anchorZ, found = 0, nil, false
                for _, m in ipairs(workspace:GetChildren()) do
                    if m ~= rig and m:IsA("Model")
                        and m.Name:sub(1, 9) == "PiscesRig"
                        and m.PrimaryPart then
                        local p = m:GetPivot().Position
                        if not found or p.X > maxX then maxX = p.X end
                        anchorZ = anchorZ or p.Z
                        found = true
                    end
                end
                if found then
                    rig:PivotTo(CFrame.new(maxX + 6, 3.2, anchorZ or 0))
                else
                    -- FIRST rig: never leave it where it spawned (origin) —
                    -- generated builds insert there too and swallow it
                    -- (2026-08-02: "Friendly Farmer Idle" preview rig buried
                    -- inside a market stall). Walk +X in 6-stud steps until
                    -- the rig's bounds are clear of everything else.
                    local _, rigSize = rig:GetBoundingBox()
                    local op = OverlapParams.new()
                    op.FilterType = Enum.RaycastFilterType.Exclude
                    op.FilterDescendantsInstances = { rig }
                    local x = 8
                    for _ = 1, 40 do
                        local hits = workspace:GetPartBoundsInBox(
                            CFrame.new(x, 3.2, 0),
                            rigSize + Vector3.new(2, 0, 2), op)
                        if #hits == 0 then break end
                        x += 6
                    end
                    rig:PivotTo(CFrame.new(x, 3.2, 0))
                end
            end
        end)
        pcall(function()
            ensure_tag(rig, clipName, "clip installed", "A6A6A6")
        end)
    end

    local function rig_for(clipName)
        local st = GuidedPub.state.clips[clipName]
        local rigName = (st and st.rig_name ~= "" and st.rig_name)
            or ("PiscesRig - " .. clipName)
        return workspace:FindFirstChild(rigName)
    end

    function GuidedPub.set_tag(clipName, status, hex)
        pcall(function()
            local rig = rig_for(clipName)
            if rig then ensure_tag(rig, clipName, status, hex) end
        end)
    end

    -- panel state ----------------------------------------------------------
    local pubw = nil    -- DockWidgetPluginGui (lazy; persists plugin reloads)
    local rows = {}     -- clipName → { status = fn(text, color) }
    local active = nil  -- clip mid-dialog: ONE Save-to-Roblox at a time
    local hint = nil    -- header hint label (swaps on opt-out)
    local foot = nil    -- footer status label

    local function post_json(path, payload, on_done)
        task.spawn(function()
            local okReq, resp = pcall(function()
                return HttpService:RequestAsync({
                    Url = BASE_URL .. path,
                    Method = "POST",
                    Headers = v5_headers(),
                    Body = HttpService:JSONEncode(payload),
                })
            end)
            local ok = okReq and type(resp) == "table"
                and resp.StatusCode == 200
            local code = okReq and type(resp) == "table"
                and tostring(resp.StatusCode) or tostring(resp)
            on_done(ok, code)
        end)
    end

    function GuidedPub.mark_done(clipName, aid)
        local st = GuidedPub.state.clips[clipName]
        if st then st.status = "done"; st.aid = tostring(aid) end
        if active == clipName then active = nil end
        GuidedPub.set_tag(clipName, "published " .. tostring(aid), DONE_HEX)
        local row = rows[clipName]
        if row then row.status("✓ id " .. tostring(aid), C.ok) end
    end

    local function focus_camera(rig)
        pcall(function()
            local pos = rig:GetPivot().Position
            workspace.CurrentCamera.CFrame =
                CFrame.new(pos + Vector3.new(0, 3, 9), pos)
        end)
    end

    local function parse_id(text)
        -- longest digit run wins: handles bare ids, rbxassetid://N and
        -- pasted roblox.com URLs alike
        local best = nil
        for run in tostring(text or ""):gmatch("%d+") do
            if not best or #run > #best then best = run end
        end
        return best
    end

    local function build_row(holder, order, name)
        local st = GuidedPub.state.clips[name]
        local row = UI.make_frame(holder, {
            BackgroundColor3 = C.bg2,
            Size = UDim2.new(1, -6, 0, 104),
            LayoutOrder = order,
        })
        UI.add_corner(row, 8)
        UI.add_stroke(row, C.line, 1, 0.76)
        UI.add_padding(row, 8)
        UI.add_vlist(row, 6)

        local head_row = UI.make_frame(row, {
            BackgroundTransparency = 1,
            Size = UDim2.new(1, 0, 0, 16),
            LayoutOrder = 1,
        })
        UI.make_label(head_row, name, {
            Size = UDim2.new(0.55, 0, 1, 0),
            Font = Enum.Font.GothamBold,
            TextSize = 13,
            TextTruncate = Enum.TextTruncate.AtEnd,
        })
        local status_lbl = UI.make_label(head_row, "", {
            AnchorPoint = Vector2.new(1, 0),
            Position = UDim2.new(1, 0, 0, 0),
            Size = UDim2.new(0.45, 0, 1, 0),
            TextXAlignment = Enum.TextXAlignment.Right,
            TextSize = 11,
            TextColor3 = C.warn,
            TextTruncate = Enum.TextTruncate.AtEnd,
        })
        local function set_status(text, color)
            status_lbl.Text = text
            status_lbl.TextColor3 = color or C.sub
        end

        local btns = UI.make_frame(row, {
            BackgroundTransparency = 1,
            Size = UDim2.new(1, 0, 0, 28),
            LayoutOrder = 2,
        })
        UI.add_hlist(btns, 6)
        local pub_btn = UI.make_button(btns, "Publish", "primary")
        pub_btn.Size = UDim2.new(0.62, -3, 1, 0)
        pub_btn.LayoutOrder = 1
        pub_btn.TextSize = 12
        local skip_btn = UI.make_button(btns, "Skip", "ghost")
        skip_btn.Size = UDim2.new(0.38, -3, 1, 0)
        skip_btn.LayoutOrder = 2
        skip_btn.TextSize = 12

        local id_row = UI.make_frame(row, {
            BackgroundTransparency = 1,
            Size = UDim2.new(1, 0, 0, 30),
            LayoutOrder = 3,
        })
        UI.add_hlist(id_row, 6)
        local box = Instance.new("TextBox")
        box.BackgroundColor3 = C.input_bg
        box.BorderSizePixel = 0
        box.Font = Enum.Font.RobotoMono
        box.TextSize = 12
        box.TextColor3 = C.text
        box.PlaceholderText = "paste AnimationId / rbxassetid://…"
        box.PlaceholderColor3 = C.faint
        box.Text = ""
        box.ClearTextOnFocus = false
        box.TextXAlignment = Enum.TextXAlignment.Left
        box.Size = UDim2.new(1, -86, 1, 0)
        box.LayoutOrder = 1
        UI.add_corner(box, 6)
        UI.add_stroke(box, C.line, 1, 0.7)
        do
            local bp = Instance.new("UIPadding")
            bp.PaddingLeft = UDim.new(0, 8)
            bp.PaddingRight = UDim.new(0, 8)
            bp.Parent = box
        end
        box.Parent = id_row
        local save_btn = UI.make_button(id_row, "Save id", "primary")
        save_btn.Size = UDim2.new(0, 80, 1, 0)
        save_btn.LayoutOrder = 2
        save_btn.TextSize = 12

        pub_btn.MouseButton1Click:Connect(function()
            if st.status == "done" then
                set_status("already saved", C.ok)
                return
            end
            if active and active ~= name then
                -- ONE dialog at a time — a second SaveSelectedToRoblox
                -- REPLACES the first and its Submit is lost
                set_status("finish '" .. active .. "' first", C.danger)
                return
            end
            local rig = rig_for(name)
            local saves = rig and rig:FindFirstChild("AnimSaves")
            local kfs = saves and saves:FindFirstChild(name)
            if not (kfs and kfs:IsA("KeyframeSequence")) then
                set_status("clip missing — re-push from chat", C.danger)
                return
            end
            active = name
            focus_camera(rig)
            Selection:Set({ kfs })
            local okDlg = pcall(function()
                plugin:SaveSelectedToRoblox()
            end)
            if okDlg then
                set_status("dialog open → Submit, then paste id", C.warn)
                GuidedPub.set_tag(name, "dialog open — click Submit",
                    PENDING_HEX)
            else
                active = nil
                set_status("dialog failed to open — retry", C.danger)
            end
        end)

        skip_btn.MouseButton1Click:Connect(function()
            if active == name then active = nil end
            if st.status ~= "done" then
                set_status("skipped for now", C.sub)
            end
        end)

        local function save_id()
            if st.status == "done" then return end
            local aid = parse_id(box.Text)
            if not aid or #aid < 5 then
                set_status("no AnimationId in that text", C.danger)
                return
            end
            set_status("saving…", C.info)
            post_json("/v5/anim_publish", {
                -- p44: each clip posts against ITS OWN project (multi-clip
                -- builds are one project per clip)
                project_id = st.project_id or GuidedPub.state.project_id,
                clip = name,
                animation_id = aid,
            }, function(ok, code)
                if ok then
                    GuidedPub.mark_done(name, aid)
                    ui_log("ok", "AnimationId " .. aid .. " saved — '"
                        .. name .. "'")
                    -- best-effort propagation probe (informational only)
                    task.spawn(function()
                        local a = Instance.new("Animation")
                        a.AnimationId = "rbxassetid://" .. aid
                        local okLoad = pcall(function()
                            game:GetService("ContentProvider")
                                :PreloadAsync({ a })
                        end)
                        a:Destroy()
                        if not okLoad and st.status == "done" then
                            set_status("✓ id " .. aid
                                .. " (still propagating)", C.warn)
                        end
                    end)
                else
                    set_status("save failed (" .. code .. ") — retry",
                        C.danger)
                    ui_log("err", "anim id save failed for '" .. name
                        .. "': " .. code)
                end
            end)
        end
        save_btn.MouseButton1Click:Connect(save_id)
        box.FocusLost:Connect(function(enter)
            if enter then save_id() end
        end)

        if st.status == "done" then
            set_status("✓ id " .. tostring(st.aid), C.ok)
        else
            set_status("needs publish", C.warn)
        end
        rows[name] = { status = set_status }
    end

    function GuidedPub.open_panel()
        if not pubw then
            pubw = plugin:CreateDockWidgetPluginGui("PipelinePublishPanel",
                DockWidgetPluginGuiInfo.new(Enum.InitialDockState.Float,
                    true, true, 400, 540, 340, 420))
            pubw.Title = "Pipeline — Publish Animations"
            pubw.Name = "PipelinePublishPanel"
            pubw.ZIndexBehavior = Enum.ZIndexBehavior.Sibling
        end
        -- rebuild from scratch on every open (CreateDockWidgetPluginGui
        -- returns the PERSISTED gui — same stale-children reset idiom as
        -- the main widget)
        for _, ch in ipairs(pubw:GetChildren()) do
            pcall(function() ch:Destroy() end)
        end
        rows = {}
        local root = UI.make_frame(pubw, {
            BackgroundColor3 = C.bg0,
            Size = UDim2.fromScale(1, 1),
        })
        do
            local g = Instance.new("UIGradient")
            g.Color = ColorSequence.new({
                ColorSequenceKeypoint.new(0, Color3.fromRGB(12, 12, 12)),
                ColorSequenceKeypoint.new(1, Color3.fromRGB(6, 11, 21)),
            })
            g.Rotation = 165
            g.Parent = root
        end
        UI.add_padding(root, 12)
        UI.add_vlist(root, 8)

        UI.make_label(root, "Publish your animations", {
            Size = UDim2.new(1, 0, 0, 20),
            Font = Enum.Font.GothamBold,
            TextSize = 15,
            LayoutOrder = 1,
        })
        hint = UI.make_label(root,
            "<b>Fastest:</b> the <font color='#FF5A1F'>one-click button "
            .. "below</font> — Pipeline installs its animation system and "
            .. "every clip just plays. Done.\n"
            .. "<b>Or publish real AnimationIds</b> (Roblox only mints them "
            .. "in Studio, one clip at a time):\n"
            .. "<font color='#FF5A1F'>1.</font> Click <b>Publish</b> on a "
            .. "clip — Roblox's Save dialog opens; click <b>Submit</b>.\n"
            .. "<font color='#FF5A1F'>2.</font> Copy the <b>AnimationId</b> "
            .. "and paste it in the clip's box, then <b>Save id</b>.\n"
            .. "<font color='#6E6E6E'>(lost the id? create.roblox.com → "
            .. "Creations → Animations)</font>\n"
            .. "<font color='#FF5A1F'>3.</font> Repeat for each clip — "
            .. "Pipeline wires the ids in for you.",
            {
                Size = UDim2.new(1, 0, 0, 0),
                AutomaticSize = Enum.AutomaticSize.Y,
                TextWrapped = true,
                TextSize = 12,
                TextColor3 = C.sub,
                TextYAlignment = Enum.TextYAlignment.Top,
                LayoutOrder = 2,
            })

        -- p46: say WHAT one click covers — "all N animations", live count
        -- (panel rebuilds on every guided_publish merge, so N tracks the
        -- roster; owner 2026-07-27: "push all x animations, not just one")
        local _n_clips = #GuidedPub.state.order
        local optout = UI.make_button(root,
            (_n_clips > 1
                and ("⚡ One click: install all " .. _n_clips .. " animations")
                or "⚡ One click: install this animation"), "primary")
        optout.Size = UDim2.new(1, 0, 0, 36)
        optout.LayoutOrder = 3
        optout.TextSize = 13
        UI.make_label(root,
            "Recommended — installs the PiscesAnimator system + every clip "
            .. "automatically. No dialogs, no ids, plays instantly in Studio "
            .. "and in-game. (You can still publish real ids above anytime.)",
            {
                Size = UDim2.new(1, 0, 0, 0),
                AutomaticSize = Enum.AutomaticSize.Y,
                TextWrapped = true,
                TextSize = 10,
                TextColor3 = C.faint,
                LayoutOrder = 4,
            })

        local list_panel = UI.make_panel(root, 5, 100)
        list_panel.Size = UDim2.new(1, 0, 1, -270)
        list_panel.AutomaticSize = Enum.AutomaticSize.None
        local scroll = Instance.new("ScrollingFrame")
        scroll.BackgroundTransparency = 1
        scroll.BorderSizePixel = 0
        scroll.Size = UDim2.fromScale(1, 1)
        scroll.CanvasSize = UDim2.new()
        scroll.AutomaticCanvasSize = Enum.AutomaticSize.Y
        scroll.ScrollBarThickness = 3
        scroll.ScrollBarImageColor3 = C.accent_dim
        scroll.Parent = list_panel
        UI.add_vlist(scroll, 6)

        for i, name in ipairs(GuidedPub.state.order) do
            build_row(scroll, i, name)
        end

        local foot_row = UI.make_frame(root, {
            BackgroundTransparency = 1,
            Size = UDim2.new(1, 0, 0, 28),
            LayoutOrder = 6,
        })
        UI.add_hlist(foot_row, 8)
        local clean_btn = UI.make_button(foot_row, "Clean up rigs", "ghost")
        clean_btn.Size = UDim2.new(0, 110, 1, 0)
        clean_btn.LayoutOrder = 1
        clean_btn.TextSize = 11
        foot = UI.make_label(foot_row, "", {
            Size = UDim2.new(1, -120, 1, 0),
            TextSize = 11,
            TextColor3 = C.sub,
            LayoutOrder = 2,
        })

        optout.MouseButton1Click:Connect(function()
            -- p44: the panel can hold clips from MANY projects (one project
            -- per clip in a multi-clip build) — opt out EVERY distinct
            -- project, not just the last one that opened the panel.
            local pids, seen = {}, {}
            for _, cname in ipairs(GuidedPub.state.order) do
                local cst = GuidedPub.state.clips[cname]
                local cpid = (cst and cst.project_id)
                    or GuidedPub.state.project_id
                if cpid and not seen[cpid] then
                    seen[cpid] = true
                    table.insert(pids, cpid)
                end
            end
            if #pids == 0 then return end
            foot.Text = "switching to PiscesAnimator…"
            task.spawn(function()
                local fails = 0
                for _, cpid in ipairs(pids) do
                    local okReq, resp = pcall(function()
                        return HttpService:RequestAsync({
                            Url = BASE_URL .. "/v5/anim_publish",
                            Method = "POST",
                            Headers = v5_headers(),
                            Body = HttpService:JSONEncode({
                                project_id = cpid, opt_out = true }),
                        })
                    end)
                    if not (okReq and type(resp) == "table"
                        and resp.StatusCode == 200) then
                        fails = fails + 1
                    end
                end
                if fails == 0 then
                    foot.Text = "PiscesAnimator module installing… ("
                        .. #pids .. " project(s))"
                    hint.Text = "<b>PiscesAnimator mode.</b> No ids needed "
                        .. "— clips install as modules and scripts play "
                        .. "them via <font color='#FF5A1F'>PiscesAnimator:"
                        .. "Play(character, \"&lt;clip&gt;\")</font>. You "
                        .. "can still publish ids here later."
                    for cname, r in pairs(rows) do
                        local cst = GuidedPub.state.clips[cname]
                        if cst and cst.status ~= "done" then
                            r.status("module mode — no id needed", C.info)
                            GuidedPub.set_tag(cname,
                                "PiscesAnimator module", MODULE_HEX)
                        end
                    end
                    ui_log("ok", "animation publishing skipped — "
                        .. "PiscesAnimator module mode (" .. #pids
                        .. " project(s))")
                else
                    -- re-clicking retries every project: opt-out is
                    -- idempotent server-side (module mode is sticky)
                    foot.Text = "opt-out failed for " .. fails .. "/"
                        .. #pids .. " project(s) — click again to retry"
                end
            end)
        end)

        clean_btn.MouseButton1Click:Connect(function()
            ChangeHistoryService:SetWaypoint("Pre-Pipeline rig cleanup")
            local n = 0
            for cname in pairs(GuidedPub.state.clips) do
                local rig = rig_for(cname)
                if rig then
                    pcall(function() rig:Destroy() end)
                    n = n + 1
                end
            end
            ChangeHistoryService:SetWaypoint("Pipeline rig cleanup")
            -- p44: cleanup ends the session — clear the roster so the NEXT
            -- build's panel doesn't resurrect this one's clips (the server
            -- re-sends anything genuinely still pending).
            GuidedPub.state.clips = {}
            GuidedPub.state.order = {}
            active = nil
            GuidedPub.open_panel()
            foot.Text = "removed " .. n .. " rig(s) — list cleared"
        end)

        pubw.Enabled = true
    end

    function GuidedPub.run(input)
        local pid = tonumber(input.project_id or 0) or 0
        local clips = input.clips
        if pid <= 0 or type(clips) ~= "table" or #clips == 0 then
            return false, {
                error = "guided_publish: project_id and clips required",
                error_code = "missing_target",
            }, nil, nil
        end
        -- p44: MERGE, never reset. A multi-clip build is one project PER
        -- CLIP, so 9 sequential guided_publish calls (each a different
        -- project_id) must ACCUMULATE into one panel — the p43 reset-on-
        -- project-change left only the last clip listed, and its opt-out
        -- flipped only that one project to module mode. Each clip stores
        -- its own project_id for the id-save / opt-out POSTs.
        local st = GuidedPub.state
        st.project_id = pid
        for _, c in ipairs(clips) do
            local name = tostring(
                (type(c) == "table" and (c.name or c.clip)) or c or "")
            if name ~= "" then
                local cpid = (type(c) == "table"
                    and tonumber(c.project_id)) or pid
                local e = st.clips[name]
                if not e then
                    local rigName = tostring(
                        (type(c) == "table" and c.rig_name) or "")
                    if rigName == "" then
                        rigName = "PiscesRig - " .. name
                    end
                    e = { rig_name = rigName, status = "pending", aid = nil }
                    st.clips[name] = e
                    table.insert(st.order, name)
                    GuidedPub.set_tag(name, "publish pending", PENDING_HEX)
                end
                e.project_id = cpid
                -- the server re-listing a clip as pending means it has no
                -- recorded id — a stale "done" would hide the row's actions
                if e.status ~= "done" then e.status = "pending" end
            end
        end
        -- a stale mid-dialog lock for a clip no longer in the roster would
        -- block EVERY Publish click ("finish 'X' first") forever
        if active and not st.clips[active] then active = nil end
        local okPanel, perr = pcall(GuidedPub.open_panel)
        if not okPanel then
            return false, {
                error = "guided_publish: panel failed — " .. tostring(perr),
                error_code = "panel_failed",
            }, nil, nil
        end
        ui_log("info", "guided publish panel open — "
            .. tostring(#st.order) .. " clip(s)")
        return true, {
            tool = "guided_publish",
            panel_open = true,
            clips = #st.order,
            note = "Guided publish panel is open in Studio — the user "
                .. "publishes each clip and pastes its AnimationId, or "
                .. "opts out to the PiscesAnimator module.",
        }, nil, nil
    end
end

-- Build the widget --------------------------------------------------------

local widget_info = DockWidgetPluginGuiInfo.new(
    Enum.InitialDockState.Right,
    false, false,
    340, 620,
    300, 460
)

local widget = plugin:CreateDockWidgetPluginGui("PipelinePanel", widget_info)
widget.Title = "Pipeline"
widget.Name = "PipelinePanel"
widget.ZIndexBehavior = Enum.ZIndexBehavior.Sibling

-- 2026-05-25 (p16): CreateDockWidgetPluginGui returns the EXISTING widget if
-- one was created in a previous plugin run (the widget persists across
-- plugin re-loads). Without explicit cleanup, every reload STACKS a new
-- `root` frame inside the old children — the user sees "random stuff from
-- previous stuff" (stale log lines, ghost buttons, etc.) layered behind the
-- new UI. Destroy any leftover children before rebuilding.
for _, child in ipairs(widget:GetChildren()) do
    pcall(function() child:Destroy() end)
end

-- Root w/ Pisces gradient background
local root = UI.make_frame(widget, {
    BackgroundColor3 = C.bg0,
    Size = UDim2.fromScale(1, 1),
})
do
    local g = Instance.new("UIGradient")
    g.Color = ColorSequence.new({
        ColorSequenceKeypoint.new(0, Color3.fromRGB(14, 14, 16)),
        ColorSequenceKeypoint.new(1, Color3.fromRGB(8, 8, 10)),
    })
    g.Rotation = 165
    g.Parent = root
end
UI.add_padding(root, 14)
UI.add_vlist(root, 10)

-- Header: ◆ Pisces V5    [● status] ---------------------------------------
-- Position-based layout (no UIListLayout) so the right-side pill can
-- auto-size to whatever the status label needs (e.g. "Waiting for API key"
-- is wider than "Connected").
local header = UI.make_frame(root, {
    BackgroundTransparency = 1,
    Size = UDim2.new(1, 0, 0, 30),
    LayoutOrder = 1,
})

-- Accent diamond, vertically centered on the left
-- p35 hotfix: the main chunk hit Luau's 200-local register limit (plugin
-- failed to LOAD: "Out of local registers when trying to allocate panel_btn").
-- One-shot UI locals in this section are scoped into do-blocks / dropped so
-- their registers free up — behavior identical.
do
    local diamond = UI.make_frame(header, {
        BackgroundColor3 = C.accent,
        AnchorPoint = Vector2.new(0, 0.5),
        Position = UDim2.new(0, 0, 0.5, 0),
        Size = UDim2.fromOffset(12, 12),
        Rotation = 45,
    })
    local g = Instance.new("UIGradient")
    g.Color = ColorSequence.new({
        ColorSequenceKeypoint.new(0, C.accent),
        ColorSequenceKeypoint.new(1, C.info),
    })
    g.Parent = diamond
end

UI.make_label(header, "Pipeline", {
    AnchorPoint = Vector2.new(0, 0.5),
    Position = UDim2.new(0, 22, 0.5, 0),
    Size = UDim2.new(0, 180, 1, 0),
    Font = Enum.Font.GothamBold,
    TextSize = 17,
    TextColor3 = C.text,
})

-- Right-anchored status pill — width grows with content (AutomaticSize.X)
local status_pill = UI.make_frame(header, {
    BackgroundColor3 = C.bg2,
    AnchorPoint = Vector2.new(1, 0.5),
    Position = UDim2.new(1, 0, 0.5, 0),
    Size = UDim2.fromOffset(0, 26),
    AutomaticSize = Enum.AutomaticSize.X,
})
UI.add_corner(status_pill, 13)
UI.add_stroke(status_pill, C.line, 1, 0.6)
UI.add_padding(status_pill, 4, 12, 4, 10)
UI.add_hlist(status_pill, 8)

local status_dot = UI.make_frame(status_pill, {
    BackgroundColor3 = C.danger,
    Size = UDim2.fromOffset(8, 8),
    LayoutOrder = 1,
})
UI.add_corner(status_dot, 4)

local status_label = UI.make_label(status_pill, "Disconnected", {
    Size = UDim2.fromOffset(0, 18),
    AutomaticSize = Enum.AutomaticSize.X,
    Font = Enum.Font.GothamSemibold,
    TextSize = 12,
    TextColor3 = C.danger,
    LayoutOrder = 2,
    TextWrapped = false,
})

-- Accent divider line -----------------------------------------------------
UI.make_frame(root, {
    BackgroundColor3 = C.accent_dim,
    BackgroundTransparency = 0.55,
    Size = UDim2.new(1, 0, 0, 1),
    LayoutOrder = 2,
})

-- STATUS section ----------------------------------------------------------
UI.make_section_label(root, "STATUS", 3)
local val_connection, val_session, val_heartbeat, val_latency, val_handled
do
    local status_panel = UI.make_panel(root, 4, 110)
    UI.add_vlist(status_panel, 4)
    local _
    _, val_connection = UI.make_kv(status_panel, "Connection", "<font color='#FF6464'>Disconnected</font>")
    _, val_session    = UI.make_kv(status_panel, "Session",    UI.short_id(plugin_state.session_id), true)
    _, val_heartbeat  = UI.make_kv(status_panel, "Heartbeat",  "<font color='#A6A6A6'>—</font>")
    _, val_latency    = UI.make_kv(status_panel, "Latency",    "<font color='#A6A6A6'>—</font>")
    _, val_handled    = UI.make_kv(status_panel, "Handled",    "<b>0</b>")
end

-- API key field (no section label — single TextBox that auto-persists) ----
-- Whatever's in this box IS the saved key. Typing → 400ms debounce → save.
-- Click elsewhere → save. Clear the box → key is deleted.
local key_input = Instance.new("TextBox")
key_input.BackgroundColor3 = C.input_bg
key_input.BorderSizePixel = 0
key_input.Font = Enum.Font.RobotoMono
key_input.TextSize = 13
key_input.TextColor3 = C.text
key_input.PlaceholderText = "Paste your Pipeline API key…"
key_input.PlaceholderColor3 = C.faint
key_input.Text = plugin_state.api_key  -- seed with currently-saved value
key_input.ClearTextOnFocus = false
key_input.TextXAlignment = Enum.TextXAlignment.Left
key_input.Size = UDim2.new(1, 0, 0, 38)
key_input.LayoutOrder = 5
UI.add_corner(key_input, 8)
UI.add_stroke(key_input, C.line, 1, 0.7)
do
    local kp = Instance.new("UIPadding")
    kp.PaddingLeft = UDim.new(0, 12); kp.PaddingRight = UDim.new(0, 12)
    kp.PaddingTop = UDim.new(0, 4); kp.PaddingBottom = UDim.new(0, 4)
    kp.Parent = key_input
end
key_input.Parent = root

-- Focus ring (accent) on the input
key_input.Focused:Connect(function()
    local s = key_input:FindFirstChildOfClass("UIStroke")
    if s then s.Color = C.accent; s.Transparency = 0.3 end
end)
key_input.FocusLost:Connect(function()
    local s = key_input:FindFirstChildOfClass("UIStroke")
    if s then s.Color = C.line; s.Transparency = 0.7 end
end)

-- Buttons row ------------------------------------------------------------
local btn_row = UI.make_frame(root, {
    BackgroundTransparency = 1,
    Size = UDim2.new(1, 0, 0, 36),
    LayoutOrder = 7,
})
UI.add_hlist(btn_row, 8)

local connect_btn = UI.make_button(btn_row, "Connect", "primary")
connect_btn.Size = UDim2.new(0.55, -4, 1, 0)
connect_btn.LayoutOrder = 1

local disconnect_btn = UI.make_button(btn_row, "Disconnect", "danger")
disconnect_btn.Size = UDim2.new(0.45, -4, 1, 0)
disconnect_btn.LayoutOrder = 2

-- ACTIVITY section header (label + clear) --------------------------------
local activity_head = UI.make_frame(root, {
    BackgroundTransparency = 1,
    Size = UDim2.new(1, 0, 0, 16),
    LayoutOrder = 12,
})
UI.add_hlist(activity_head, 6)

UI.make_label(activity_head, "ACTIVITY", {
    Size = UDim2.new(1, -60, 1, 0),
    TextColor3 = C.sub,
    TextSize = 11,
    Font = Enum.Font.GothamBold,
    LayoutOrder = 1,
})

local clear_btn = UI.make_button(activity_head, "Clear", "ghost")
clear_btn.Size = UDim2.new(0, 56, 1, 0)
clear_btn.TextSize = 11
clear_btn.LayoutOrder = 2

-- Log scroll panel -------------------------------------------------------
local log_panel = UI.make_panel(root, 13, nil)  -- flex height
log_panel.Size = UDim2.new(1, 0, 1, -396)   -- absorb remaining space
log_panel.AutomaticSize = Enum.AutomaticSize.None
UI.add_padding(log_panel, 8)

local log_scroll = Instance.new("ScrollingFrame")
log_scroll.BackgroundTransparency = 1
log_scroll.BorderSizePixel = 0
log_scroll.Size = UDim2.fromScale(1, 1)
log_scroll.CanvasSize = UDim2.new()
log_scroll.AutomaticCanvasSize = Enum.AutomaticSize.Y
log_scroll.ScrollBarThickness = 3
log_scroll.ScrollBarImageColor3 = C.accent_dim
log_scroll.ScrollBarImageTransparency = 0.3
log_scroll.VerticalScrollBarPosition = Enum.VerticalScrollBarPosition.Right
log_scroll.Parent = log_panel

do
    local log_layout = Instance.new("UIListLayout")
    log_layout.SortOrder = Enum.SortOrder.LayoutOrder
    log_layout.FillDirection = Enum.FillDirection.Vertical
    log_layout.Padding = UDim.new(0, 2)
    log_layout.Parent = log_scroll
end

-- Footer -----------------------------------------------------------------
UI.make_label(UI.make_frame(root, {
    BackgroundTransparency = 1,
    Size = UDim2.new(1, 0, 0, 14),
    LayoutOrder = 14,
}), string.format(
    "<font color='#6E6E6E'>%s · place %s</font>",
    PLUGIN_VERSION,
    plugin_state.place_id:sub(1, 12)
), {
    Size = UDim2.fromScale(1, 1),
    TextSize = 10,
    Font = Enum.Font.RobotoMono,
    TextXAlignment = Enum.TextXAlignment.Right,
})

-- TEAM (Pipeline p62): the team's talk as chat bubbles, above the log ------
-- Fed by TV.apply: each member's latest words in the meeting (say) or what it
-- is on (line). New words = a new bubble; the same words just update its tag.
-- No new top-level locals (Luau 200-register cap): everything lives in UI.
UI.feed_head = UI.make_frame(root, {
    BackgroundTransparency = 1,
    Size = UDim2.new(1, 0, 0, 16),
    LayoutOrder = 8,
    Visible = false,
})
UI.add_hlist(UI.feed_head, 6)
UI.make_label(UI.feed_head, "TEAM", {
    Size = UDim2.new(1, -60, 1, 0),
    TextColor3 = C.sub,
    TextSize = 11,
    Font = Enum.Font.GothamBold,
    LayoutOrder = 1,
})
UI.feed_btn = UI.make_button(UI.feed_head, "Log", "ghost")
UI.feed_btn.Size = UDim2.new(0, 56, 1, 0)
UI.feed_btn.TextSize = 11
UI.feed_btn.LayoutOrder = 2

UI.feed_panel = UI.make_panel(root, 9, nil)
UI.feed_panel.Size = UDim2.new(1, 0, 1, -396)
UI.feed_panel.AutomaticSize = Enum.AutomaticSize.None
UI.feed_panel.Visible = false
UI.add_padding(UI.feed_panel, 8)

UI.feed_scroll = Instance.new("ScrollingFrame")
UI.feed_scroll.BackgroundTransparency = 1
UI.feed_scroll.BorderSizePixel = 0
UI.feed_scroll.Size = UDim2.fromScale(1, 1)
UI.feed_scroll.CanvasSize = UDim2.new()
UI.feed_scroll.AutomaticCanvasSize = Enum.AutomaticSize.Y
UI.feed_scroll.ScrollBarThickness = 3
UI.feed_scroll.ScrollBarImageColor3 = C.accent_dim
UI.feed_scroll.ScrollBarImageTransparency = 0.3
UI.feed_scroll.Parent = UI.feed_panel
do
    local l = Instance.new("UIListLayout")
    l.SortOrder = Enum.SortOrder.LayoutOrder
    l.Padding = UDim.new(0, 8)
    l.Parent = UI.feed_scroll
end

UI.feed_rows, UI.feed_last, UI.feed_seq, UI.feed_mode = {}, {}, 0, nil

function UI.feed_esc(s)
    return (tostring(s or ""):gsub("&", "&amp;"):gsub("<", "&lt;"):gsub(">", "&gt;"))
end

-- "team": bubbles fill the panel; "log": the old activity log comes back
function UI.feed_set(mode)
    UI.feed_mode = mode
    local team = mode == "team"
    UI.feed_head.Visible = mode ~= nil
    UI.feed_panel.Visible = team
    activity_head.Visible = not team
    log_panel.Visible = not team
    UI.feed_btn.Text = team and "Log" or "Team"
end
UI.feed_btn.MouseButton1Click:Connect(function()
    UI.feed_set(UI.feed_mode == "team" and "log" or "team")
end)

function UI.feed_tag(r, state)
    r.state = state
    r.tag.Text = (state == "working" and "working") or (state == "done" and "Done") or ""
    r.tag.TextColor3 = (state == "working") and C.accent or C.ok
    r.avs.Color = (state == "working") and C.accent or Color3.fromRGB(42, 43, 49)
    r.avs.Transparency = (state == "working") and 0.2 or 0.4
end

function UI.feed_bubble(role, text, hex)
    UI.feed_seq = UI.feed_seq + 1
    local row = Instance.new("Frame")
    row.BackgroundTransparency = 1
    row.Size = UDim2.new(1, -6, 0, 24)
    row.AutomaticSize = Enum.AutomaticSize.Y
    row.LayoutOrder = UI.feed_seq
    row.Parent = UI.feed_scroll
    local av = Instance.new("TextLabel")
    av.Size = UDim2.fromOffset(24, 24)
    av.BackgroundColor3 = Color3.fromRGB(23, 24, 28)
    av.BorderSizePixel = 0
    av.Font = Enum.Font.GothamBold
    av.TextSize = 11
    av.Text = string.upper(string.sub(role, 1, 1))
    av.TextColor3 = TV.color(hex)
    av.Parent = row
    UI.add_corner(av, 6)
    local avs = Instance.new("UIStroke"); avs.Thickness = 1; avs.Parent = av
    local b = Instance.new("Frame")
    b.Position = UDim2.fromOffset(32, 0)
    b.Size = UDim2.new(1, -32, 0, 0)
    b.AutomaticSize = Enum.AutomaticSize.Y
    b.BackgroundColor3 = Color3.fromRGB(20, 21, 25)
    b.BorderSizePixel = 0
    b.Parent = row
    UI.add_corner(b, 8)
    UI.add_stroke(b, Color3.fromRGB(60, 62, 70), 1, 0.5)
    UI.add_padding(b, 6, 9, 7, 9)
    UI.add_vlist(b, 2)
    local who = Instance.new("TextLabel")
    who.BackgroundTransparency = 1
    who.Size = UDim2.new(1, 0, 0, 14)
    who.Font = Enum.Font.Gotham
    who.TextSize = 11
    who.RichText = true
    who.TextXAlignment = Enum.TextXAlignment.Left
    who.TextColor3 = C.text
    who.Text = string.format("<b>%s</b>  <font color='#6E6E76'>agent</font>", UI.feed_esc(role))
    who.LayoutOrder = 1
    who.Parent = b
    local tag = Instance.new("TextLabel")
    tag.BackgroundTransparency = 1
    tag.AnchorPoint = Vector2.new(1, 0)
    tag.Position = UDim2.new(1, 0, 0, 0)
    tag.Size = UDim2.new(0, 70, 1, 0)
    tag.Font = Enum.Font.GothamSemibold
    tag.TextSize = 11
    tag.TextXAlignment = Enum.TextXAlignment.Right
    tag.Parent = who
    local body = Instance.new("TextLabel")
    body.BackgroundTransparency = 1
    body.Size = UDim2.new(1, 0, 0, 0)
    body.AutomaticSize = Enum.AutomaticSize.Y
    body.Font = Enum.Font.Gotham
    body.TextSize = 12
    body.TextWrapped = true
    body.TextXAlignment = Enum.TextXAlignment.Left
    body.TextYAlignment = Enum.TextYAlignment.Top
    body.TextColor3 = Color3.fromRGB(214, 214, 214)
    body.Text = text
    body.LayoutOrder = 2
    body.Parent = b
    return { frame = row, tag = tag, avs = avs, text = text }
end

TV.feed = function(name, role, say, line, hex, busy)
    say = say:gsub("%s+", " ")
    if #say > 220 then say = string.sub(say, 1, 217) .. "…" end
    local text = (say ~= "" and say) or line
    if text == "" then return end
    local low = string.lower(line)
    local state = busy and "working" or ((low:find("done") or low:find("finished")) and "done" or "")
    local last = UI.feed_last[name]
    if last and last.text == text then
        UI.feed_tag(last, state)
        return
    end
    if last then UI.feed_tag(last, last.state == "working" and "" or last.state) end
    local r = UI.feed_bubble(role ~= "" and role or name, text, hex)
    UI.feed_tag(r, state)
    UI.feed_last[name] = r
    table.insert(UI.feed_rows, r)
    while #UI.feed_rows > 40 do
        local o = table.remove(UI.feed_rows, 1)
        pcall(function() o.frame:Destroy() end)
    end
    if UI.feed_mode == nil then UI.feed_set("team") end
    task.delay(0.05, function()
        local s = UI.feed_scroll
        s.CanvasPosition = Vector2.new(0, math.max(0, s.AbsoluteCanvasSize.Y - s.AbsoluteWindowSize.Y))
    end)
end


-- Log writer (installs into the forward-declared `ui_log` upvalue) -------
UI._log_rows = {}
UI._log_seq = 0
UI._prefix = { info = "▸", ok = "✓", warn = "!", err = "✗", trace = "·" }
UI._level_hex = {
    info = UI.HEX.accent, ok = UI.HEX.ok, warn = UI.HEX.warn, err = UI.HEX.danger, trace = UI.HEX.sub,
}
UI._level_text_hex = {
    info = UI.HEX.text, ok = UI.HEX.text, warn = UI.HEX.text, err = UI.HEX.text, trace = UI.HEX.sub,
}

ui_log = function(level, msg)
    if not UI._level_hex[level] then level = "info" end
    UI._log_seq = UI._log_seq + 1
    local row = Instance.new("TextLabel")
    row.BackgroundTransparency = 1
    row.Size = UDim2.new(1, -6, 0, 15)
    row.AutomaticSize = Enum.AutomaticSize.Y
    row.TextXAlignment = Enum.TextXAlignment.Left
    row.TextYAlignment = Enum.TextYAlignment.Top
    row.Font = Enum.Font.RobotoMono
    row.TextSize = 11
    row.RichText = true
    row.TextWrapped = true
    row.TextColor3 = C.text
    row.LayoutOrder = UI._log_seq
    row.Text = string.format(
        "<font color='#%s'>%s</font>  <font color='#%s'>%s</font>  <font color='#%s'>%s</font>",
        UI.HEX.faint, os.date("%H:%M:%S"),
        UI._level_hex[level], UI._prefix[level],
        UI._level_text_hex[level], tostring(msg)
    )
    row.Parent = log_scroll
    table.insert(UI._log_rows, row)
    while #UI._log_rows > UI_LOG_MAX do
        local oldest = table.remove(UI._log_rows, 1)
        if oldest then oldest:Destroy() end
    end
    task.defer(function()
        if log_scroll.Parent then
            log_scroll.CanvasPosition = Vector2.new(0, log_scroll.AbsoluteCanvasSize.Y)
        end
    end)
end

-- Initial banner so the log is never empty on first open ----------------
ui_log("info", "Pipeline panel ready")

-- Button wiring ---------------------------------------------------------
-- Auto-save: writes plugin:SetSetting after a 400ms keystroke quiet period,
-- and immediately on focus-lost.  Empty string = key cleared (delete).
UI._key_save_token = 0
function UI._commit_key(val)
    if val == plugin_state.api_key then return end  -- no-op
    plugin_state.api_key = val
    plugin:SetSetting("pisces_api_key", val)
    if val == "" then
        ui_log("warn", "API key cleared")
    else
        ui_log("ok", string.format("API key saved (%d chars)", #val))
    end
end

function UI.autosave_key()
    UI._key_save_token = UI._key_save_token + 1
    local my_token = UI._key_save_token
    task.delay(0.4, function()
        if my_token ~= UI._key_save_token then return end  -- newer keystroke
        local val = key_input.Text:gsub("^%s+", ""):gsub("%s+$", "")
        UI._commit_key(val)
    end)
end

key_input:GetPropertyChangedSignal("Text"):Connect(UI.autosave_key)
key_input.FocusLost:Connect(function(_enter_pressed)
    -- Immediate flush on focus-lost (skip the debounce)
    UI._key_save_token = UI._key_save_token + 1  -- invalidates any pending delay
    local val = key_input.Text:gsub("^%s+", ""):gsub("%s+$", "")
    UI._commit_key(val)
end)

-- Connect / Disconnect state machine.
-- UI._conn_inflight is a hard guard against double-clicks while a connect or
-- disconnect call is in flight. Buttons visually disable while busy.
UI._conn_inflight = false

function UI.set_buttons_for_state(state)
    -- state ∈ "idle" | "connecting" | "connected" | "disconnecting"
    if state == "connecting" then
        connect_btn.Text = "Connecting…"
        connect_btn.Active = false
        connect_btn.AutoButtonColor = false
        connect_btn.BackgroundColor3 = C.accent_dim
        disconnect_btn.Active = false
    elseif state == "disconnecting" then
        disconnect_btn.Text = "Disconnecting…"
        disconnect_btn.Active = false
        disconnect_btn.AutoButtonColor = false
        connect_btn.Active = false
    elseif state == "connected" then
        connect_btn.Text = "Reconnect"
        connect_btn.Active = true
        connect_btn.AutoButtonColor = false
        connect_btn.BackgroundColor3 = C.bg2
        connect_btn.TextColor3 = C.sub
        disconnect_btn.Text = "Disconnect"
        disconnect_btn.Active = true
    else  -- idle / disconnected
        connect_btn.Text = "Connect"
        connect_btn.Active = true
        connect_btn.AutoButtonColor = false
        connect_btn.BackgroundColor3 = C.accent
        connect_btn.TextColor3 = C.on_accent
        disconnect_btn.Text = "Disconnect"
        disconnect_btn.Active = false  -- nothing to disconnect from
    end
end
UI.set_buttons_for_state("idle")

connect_btn.MouseButton1Click:Connect(function()
    if UI._conn_inflight then
        ui_log("warn", "A connect/disconnect is already in flight — wait")
        return
    end
    -- Flush any unsaved text in the API key box.
    UI._key_save_token = UI._key_save_token + 1
    local typed = key_input.Text:gsub("^%s+", ""):gsub("%s+$", "")
    UI._commit_key(typed)
    if plugin_state.api_key == "" then
        ui_log("err", "Paste an API key into the box above first")
        return
    end

    UI._conn_inflight = true
    UI.set_buttons_for_state("connecting")

    task.spawn(function()
        -- Step 1: nuke any prior server-side liveness row for this api_key
        -- + place_id.  No-op if there isn't one.  This makes Connect
        -- idempotent: works after Studio restart, after orphan, after
        -- mid-turn crash — always.
        ui_log("trace", "Clearing prior session…")
        v5_force_disconnect()
        task.wait(0.4)  -- give the DB write time to commit

        -- Step 2: fresh session id + fresh connect.
        plugin_state.user_disconnected = false
        plugin_state.connected         = false
        plugin_state.session_id        = HttpService:GenerateGUID(false)
        val_session.Text = UI.short_id(plugin_state.session_id)
        ui_log("info", "Connecting to " .. BASE_URL:gsub("^https?://", ""))

        if v5_connect() then
            -- M1: spawn poll workers (was previously inside main_loop).
            -- Bump the generation FIRST so workers from a prior connect
            -- retire instead of stacking (+2 pollers per Reconnect click).
            plugin_state.worker_gen = plugin_state.worker_gen + 1
            for i = 1, POLL_WORKERS do
                task.spawn(poll_worker, i)
            end
            UI.set_buttons_for_state("connected")
        else
            -- v5_connect already logged the specific failure reason
            UI.set_buttons_for_state("idle")
        end
        UI._conn_inflight = false
    end)
end)

disconnect_btn.MouseButton1Click:Connect(function()
    if UI._conn_inflight then
        ui_log("warn", "A connect/disconnect is already in flight — wait")
        return
    end
    if not plugin_state.connected then
        ui_log("warn", "Not connected")
        return
    end
    UI._conn_inflight = true
    UI.set_buttons_for_state("disconnecting")
    task.spawn(function()
        plugin_state.user_disconnected = true
        plugin_state.connected         = false
        pcall(TV.stop)   -- p60: no team bubbles left behind after a disconnect
        -- rev 01090b: stop the freshness watchers so they don't keep firing on
        -- edits (and don't leak connections) while disconnected.
        pcall(_cleanup_freshness_watchers)
        v5_force_disconnect()
        ui_log("warn", "Disconnected")
        UI.set_buttons_for_state("idle")
        UI._conn_inflight = false
    end)
end)

clear_btn.MouseButton1Click:Connect(function()
    for _, r in ipairs(UI._log_rows) do
        if r then r:Destroy() end
    end
    UI._log_rows = {}
    UI._log_seq = 0
end)

-- Toolbar (single button toggles widget) --------------------------------
-- 2026-05-25 rev p18: toolbar name + button label + icon match the V4
-- plugin so the marketplace listing renders the same decal users
-- already know. Empty icon made the button show up blank in Studio
-- Plugins ribbon when installed from the marketplace — invisible
-- entrypoint. Same rbxassetid as pisces_web_plugin.lua:3531.
local toolbar = plugin:CreateToolbar("Pipeline")
local panel_btn = toolbar:CreateButton(
    "Pipeline",
    "Show / hide the Pipeline panel",
    "rbxassetid://128437111011044"
)
panel_btn.ClickableWhenViewportHidden = true
panel_btn:SetActive(widget.Enabled)
panel_btn.Click:Connect(function()
    widget.Enabled = not widget.Enabled
    panel_btn:SetActive(widget.Enabled)
end)
widget:GetPropertyChangedSignal("Enabled"):Connect(function()
    panel_btn:SetActive(widget.Enabled)
end)

-- rev 01090b: freshness safety-reconcile loop. The event watchers handle the
-- fast path (edits push in ~0.3s); this cheap signature walk every 10s catches
-- the edges events miss (in-place rename, reparent, a dropped signal) and is
-- the only path that infers deletions — strictly gated on a complete walk.
task.spawn(function()
    while true do
        task.wait(FRESHNESS_RECONCILE_S)
        if plugin_state.connected and not plugin_state.user_disconnected then
            pcall(v5_freshness_reconcile)
        end
    end
end)

-- Periodic UI refresh ---------------------------------------------------
task.spawn(function()
    while widget and widget.Parent do
        local connected = plugin_state.connected and not plugin_state.user_disconnected

        if connected then
            status_dot.BackgroundColor3 = C.ok
            status_label.Text = "Connected"
            status_label.TextColor3 = C.ok
            val_connection.Text = "<font color='#50FF78'>Connected</font>"
        elseif plugin_state.user_disconnected then
            status_dot.BackgroundColor3 = C.warn
            status_label.Text = "Disconnected"
            status_label.TextColor3 = C.warn
            val_connection.Text = "<font color='#FFDC64'>Disconnected (by you)</font>"
        elseif plugin_state.api_key == "" then
            status_dot.BackgroundColor3 = C.warn
            status_label.Text = "No key"
            status_label.TextColor3 = C.warn
            val_connection.Text = "<font color='#FFDC64'>Waiting for API key</font>"
        else
            status_dot.BackgroundColor3 = C.danger
            status_label.Text = "Offline"
            status_label.TextColor3 = C.danger
            val_connection.Text = "<font color='#FF6464'>Offline</font>"
        end

        val_handled.Text = string.format("<b>%d</b>", plugin_state.calls_handled)

        if plugin_state.last_call_latency_ms > 0 then
            val_latency.Text = string.format(
                "<b>%dms</b> <font color='#A6A6A6'>· %s</font>",
                plugin_state.last_call_latency_ms,
                plugin_state.last_call_label ~= "" and plugin_state.last_call_label or "—"
            )
        else
            val_latency.Text = "<font color='#A6A6A6'>—</font>"
        end

        if plugin_state.last_heartbeat_at > 0 then
            val_heartbeat.Text = string.format(
                "<font color='#F0FFFF'>%s</font>",
                UI.fmt_age(plugin_state.last_heartbeat_at)
            )
        else
            val_heartbeat.Text = "<font color='#A6A6A6'>—</font>"
        end

        val_session.Text = UI.short_id(plugin_state.session_id)

        task.wait(1)
    end
end)

--------------------------------------------------------------------------------
-- BOOT
--------------------------------------------------------------------------------

-- 2026-05-23: NO auto-connect at boot.  Plugin is dormant until the user
-- clicks Connect.  Studio lifecycle events (play-mode toggle, plugin
-- reload, place reopen) will NOT silently start a new session.
if plugin_state.api_key == "" then
    ui_log("warn", "Paste your API key above, then click Connect.")
else
    ui_log("info", "API key loaded — click Connect when ready")
end

--------------------------------------------------------------------------------
-- CLEANUP
--------------------------------------------------------------------------------

plugin.Unloading:Connect(function()
    plugin_state.connected = false
    pcall(TV.stop)
end)

print("[Pipeline] plugin loaded — version " .. PLUGIN_VERSION)
]]></ProtectedString>
			<string name="ScriptGuid">{B4A283E5-F4F9-4E0A-B56B-1CD5D4D2FF39}</string>
			<BinaryString name="AttributesSerialize"></BinaryString>
			<SecurityCapabilities name="Capabilities">0</SecurityCapabilities>
			<bool name="DefinesCapabilities">false</bool>
			<string name="Name">Pipeline</string>
			<int64 name="SourceAssetId">-1</int64>
			<BinaryString name="Tags"></BinaryString>
		</Properties>
	</Item>
</roblox>