LUAU // ARCHITECT v6.4
RUNTIME ACTIVE
VM ENGINE // NOMINAL
000 FPS / OPS
00 // 05
SENIOR ROBLOX DEVELOPER // SYSTEMS ARCHITECT

< ADAM />

Senior Roblox Developer with 6+ years experience engineering high-concurrency systems, atomic lifecycles, and low-latency Luau architectures.

+
SCROLL TO ASSEMBLE 3D ARCHITECTURE
↓
01 // ASSEMBLY STAGE <T> :: STRICT

TYPE SYSTEM: Strict Type Solver

Strict Luau typechecking eliminates runtime errors before code ever touches production. Advanced generic solving, compile-time validation, and zero runtime cost.

100% Type Safety
0.00 ns Runtime Cost
<T, U> Generics
Compile Validation
02 // ASSEMBLY STAGE SIMD // BUFFER

RUNTIME: Bytecode & SIMD Vector

Specialized Luau virtual machine running native SIMD vector instructions for 3D physics (Raycast suspension, spring kinematics) and direct buffer memory control without GC pauses.

Native SIMD Vector
Direct Buffer Memory
0.02 ms Tick Execution
Zero GC Spikes
03 // ASSEMBLY STAGE ATOMIC // LIFECYCLE

ARCHITECTURE: AtomicBinding & Modules

Resilient component binding architecture with deterministic phased lifecycles (Init → Start → Destroy), 100% server authority, and zero-latency client prediction.

Phased Lifecycle Flow
Atomic Instance Binder
100% Server Authority
Delta Replication
SYSTEM TELEMETRY // BENCHMARK READOUTS

6+ YEARS OF ARCHITECTURAL MASTERY

6+ Years
Senior Roblox & Luau Development Experience
2,035+ Lines
Core Architecture in AIService.luau
60 FPS
Rock-Solid Game Tickrate Under Concurrency
0.02 ms
Average Server Tick Cycle Execution Time
100% ASSEMBLED // ALL SYSTEMS SYNCHRONIZED

LAUNCH READY

The official 3D Luau architectural core is unified and primed for high-concurrency production.

Senior Roblox Developer & Systems Architect

Production Architecture & Systems Engineering

Senior Roblox Developer with 6+ years of development experience engineering core architectural libraries, custom pattern binders, phased lifecycle orchestrators, and authoritative server algorithms. Built strictly via Rojo, Wally, and Git.

6+ Years
Senior Roblox & Luau Development Experience
Senior Level
src/server/ServerModules/AIService.luau
2,035 LINES
-- [ProductionCore / ServerModules / AIService.luau]
-- Multi-agent autonomous navigation, raycast obstacle steering & vehicle torque physics
local Players = game:GetService("Players")
local Workspace = game:GetService("Workspace")
local RunService = game:GetService("RunService")
local CollectionService = game:GetService("CollectionService")

local AIService: any = {}
AIService.Metadata = {
    Priority = 8,
}

local _npcs: { [Model]: any } = {}
local _characterVehicleSlowTime: { [Model]: number } = {}
local _charLastSpatialPos: { [Model]: Vector3 } = {}

-- Dynamic safe zone containment with lerped vector pull strength
local function _keepInZone(npc: Model, targetPos: Vector3): Vector3
    if not _zoneService then return targetPos end
    local stormCenter = _zoneService.GetStormCenter()
    local stormRadius = _zoneService.GetStormRadius()
    if not stormCenter or not stormRadius then return targetPos end

    local npcPos = npc:GetPivot().Position
    local distToCenter = Vector2.new(npcPos.X - stormCenter.X, npcPos.Z - stormCenter.Z).Magnitude
    local safetyThreshold = stormRadius * 0.85

    if distToCenter > safetyThreshold then
        local pullStrength = math.clamp((distToCenter - safetyThreshold) / (stormRadius - safetyThreshold), 0, 1)
        local flatCenter = Vector3.new(stormCenter.X, targetPos.Y, stormCenter.Z)
        return targetPos:Lerp(flatCenter, pullStrength)
    end
    return targetPos
end

-- Multi-angle raycast obstacle avoidance for autonomous agents
local function _getObstacleAvoidanceSteerOffset(seat: VehicleSeat, range: number): number
    local cframe = seat.CFrame
    local origin = seat.Position + cframe.LookVector * (seat.Size.Z / 2 + 1)
    
    local rayParams = RaycastParams.new()
    rayParams.FilterType = Enum.RaycastFilterType.Exclude
    rayParams.FilterDescendantsInstances = { seat.Parent }

    local forwardDir = cframe.LookVector * range
    local leftDir = (cframe * CFrame.Angles(0, math.rad(25), 0)).LookVector * range
    local rightDir = (cframe * CFrame.Angles(0, math.rad(-25), 0)).LookVector * range

    local hitForward = Workspace:Raycast(origin, forwardDir, rayParams)
    local hitLeft = Workspace:Raycast(origin, leftDir, rayParams)
    local hitRight = Workspace:Raycast(origin, rightDir, rayParams)

    local steerOffset = 0
    if hitForward then
        local distLeft = hitLeft and (hitLeft.Position - origin).Magnitude or range
        local distRight = hitRight and (hitRight.Position - origin).Magnitude or range
        steerOffset = if distLeft > distRight then -1.0 else 1.0
    elseif hitLeft then
        local leftDist = (hitLeft.Position - origin).Magnitude
        steerOffset = (1 - (leftDist / range)) * 0.8
    elseif hitRight then
        local rightDist = (hitRight.Position - origin).Magnitude
        steerOffset = -(1 - (rightDist / range)) * 0.8
    end
    return steerOffset
end

-- Server-side vehicle physics & torque velocity computation
local function _updateVehiclePhysicsServer(car: Model, throttleInput: number, steeringInput: number, deltaTime: number)
    local chassis = car:FindFirstChild("Chassis") :: BasePart?
    local engine = car:FindFirstChild("Engine")
    local steering = car:FindFirstChild("Steering")
    local wheels = car:FindFirstChild("Wheels")
    if not (chassis and engine and steering and wheels) then return end

    -- Convert relative linear velocity to MPH
    local relativeVelocity = chassis.CFrame:VectorToObjectSpace(chassis.AssemblyLinearVelocity)
    local forwardSpeed = (-relativeVelocity.Z / 5280) * 3600

    -- [REDACTED: Non-linear torque curve interpolation and Differential Motor sync]
    local torqueAlpha = math.clamp(math.abs(forwardSpeed) / 70, 0, 1)
    local torque = 25000 + (5000 - 25000) * torqueAlpha

    -- [REDACTED: Tactical scoring evaluation & Pathfinding compute]
end

return AIService

Core Systems & Libraries

Custom-built architectural libraries and authoritative server systems powering enterprise-grade Roblox game modes.

Live Demo • Interaction Engine

AAA Contextual Interaction & Facility State Pipeline

InteractionController.luau • World-Space HUD • Authoritative Hold Sessions

Production-grade contextual interaction architecture featuring zero-trust server validation, dual-mode instant/hold prompts, 3D viewport-projected HUD with screen-edge clamping, multi-objective facility protocol state machines, and synchronized procedural VFX.

InteractionController.luau World-Space HUD Authoritative Hold Facility State Bus Zero-Trust Validation
Live Demo • Procedural Generator

Deterministic Procedural Layout & Room Generator

DungeonGenerator.luau • Branching Grid Walker • BFS Path Solver

High-performance grid-based dungeon generation framework with sub-millisecond graph solving (< 0.1 ms in Luau), automated BFS reachability validation, decoupled off-workspace assembly, real-time 2D radar minimap, and zero-leak Cleaner lifecycle pipelines.

DungeonGenerator.luau Branching Walker BFS Validation < 0.1ms Solve Cleaner Lifecycle
Live Demo • AI Core

Autonomous AI, Vehicle & Swarm Combat Core

PathfindingService • Raycast Avoidance • State Machine • Battle Royale AI

Full server-side multi-agent engine featuring dynamic raycast obstacle avoidance (predictive multi-ray steering cones), autonomous vehicle hijacking with server-side torque simulation, Battle Royale storm zone retention algorithms, and pluggable tactical state machines (ROAM, CHASE, ATTACK, DRIVING) with zero-lag replication.

AIService.luau Raycast Vectors Vehicle Physics State Machine Swarm Tactics
Live Demo • Combat Core

Authoritative Combat & Combo Engine

AntiCheatService • Combo Chains • Posture Stun

Server-authoritative martial arts melee controller with dynamic combo branching (Jab, Kick, Uppercut, Slam, Throw), hit-stop impact pauses, floating combat damage, posture/stun meter depletion, and anti-reach exploit enforcement with Players:BanAsync.

AntiCheatService.luau Combo Chains Hit-Stop Frames Players:BanAsync
Live Demo • Traversal Core

Fluid Parkour & Traversal Controller

ParkourController.luau • Ledge Grabbing • Stamina Curve

Procedural raycast locomotion engine featuring dynamic wall climbing, ledge hanging, mantle vaulting, and stamina fatigue curves. Decouples client prediction from authoritative stance synchronization for fluid 60 FPS transitions.

ParkourController.luau Ledge Grabbing Dynamic Mantling Stamina Recovery
Live Demo • GPS & Radar

Tactical Minimap & Waypoint GPS Engine

MinimapController.luau • Polar Projection • Viewport Pooling

High-performance rotating tactical radar HUD with clamped circular boundary math, camera-relative orientation tracking, dynamic distance stud calculations, and interactive map marker placement running under 0.5ms per frame.

MinimapController.luau 2D/3D Projection Sub-0.5ms Render Dynamic Markers
Live Demo • Airdrops & Physics

Physics-Driven Airdrop & Loot System

SupplyDropService.luau • Aerodynamic Drag • Flare Particles

Server-scheduled tactical supply drop system with parachute sway physics, terminal velocity dampening, ground impact triggers, volumetric red smoke signaling beacons, and instant loot weapon rollout into player hotbars.

SupplyDropService.luau Physics Drag Smoke Flares Hotbar Rollout
Live Demo • Radial UI & Data

Radial Inventory & Synchronized Data Engine

InventoryService.luau • RadialWheel.luau • Atomic Grants

High-polish radial equipment wheel coupled with an authoritative player data backend. Features 6 circular slot allocations, mouse-angle tracking, smooth tweening, synchronized item drops with 3D world interaction prompts, and admin-level atomic stat adjustments.

InventoryService.luau RadialWheel.luau Atomic Data Grants Server-Client Sync
01

Atomic Tree Pattern Binding Library

AtomicBinding.luau • Path Resolver • Teardown Dtors

A custom pattern-matching library for Roblox instance hierarchies. Resolves complex multi-branch manifests dynamically, handles child additions/removals with zero race conditions, and guarantees strict teardown execution (dtors) with integrated MicroProfiler instrumentation.

AtomicBinding.luau Instance Tree Binder Lifecycle Dtors Zero Leaks
02

Phased Lifecycle & Boot Orchestrator

ModuleLoader.luau • Phased Init/Start • Client Pacing

Enterprise module loading architecture featuring discrete bootstrap scopes (Shared, Server, Client), two-stage lifecycle execution (Init → Start), client-side step pacing to eliminate frame stalls, and real-time boot progress tracking percentages.

ModuleLoader.luau Phased Bootstrap Init / Start Client Pacing
03

Character Ability & Action Pipeline

AbilityService.luau • Cooldown Security • AntiCheat Whitelist

Authoritative server-side ability dispatching engine with high-precision timestamp rate-limiting (os.clock()), dynamic modular service routing, player disconnect garbage collection, and coordinated anti-cheat physics whitelisting during high-velocity bursts or dash actions.

AbilityService.luau Rate Limiting AntiCheat Whitelisting Dynamic Dispatch
04

Proximity Interaction & Dynamic Prompts

InteractionController.luau • TagService • Throttled Heartbeat

Client-side interaction framework designed for high-density environments (doors, generators, chests, puzzles). Watches CollectionService tags with Scythe zero-allocation numeric scopes, utilizing a throttled 5 Hz distance evaluation loop to maintain a solid 60 FPS without per-frame overhead.

InteractionController.luau CollectionService Throttled 5 Hz Memory Cleanups
05

Dynamic Spatial Zone & Storm Orchestrator

ZoneService.luau • Cubic Hermite Smoothstep • Radial Damage

Multi-phase spatial danger boundary manager for round-based game modes. Interpolates circle shrinking using cubic Hermite curves (3t² - 2t³) for smooth replication, coordinates network events with client visualizers, and performs throttled 1 Hz out-of-bounds radial damage.

ZoneService.luau Hermite Smoothstep Phased Rounds Radial Damage Tick

Production Code Showcase

Direct implementations extracted from production codebase architecture. Demonstrates type safety, algorithmic rigor, and resilient server-side design.

Source: src/server/ServerModules/DungeonGenerator.luau • Branching Grid Walker algorithm & BFS reachability validator
--!strict

local DungeonTypes = require(script.Parent.DungeonTypes)
local DungeonGrid = require(script.Parent.DungeonGrid)
local DungeonConfig = require(script.Parent.DungeonConfig)

type DirectionName = DungeonTypes.DirectionName
type RoomType = DungeonTypes.RoomType
type RoomNode = DungeonTypes.RoomNode
type GenerationResult = DungeonTypes.GenerationResult
type GridPosition = DungeonTypes.GridPosition

local DungeonGenerator = {}

-- Static constants frozen to guarantee immutability (Rule 163)
local DirectionsOrder: { DirectionName } = table.freeze({ "North", "East", "South", "West" })

-- Internal scratchpad buffers for zero-allocation shuffling (Rule 57)
local ScratchPrimary: { DirectionName } = { "North", "East", "South", "West" }
local ScratchSecondary: { DirectionName } = { "North", "East", "South", "West" }

-- Internal helper: in-place Fisher-Yates shuffle (Rule 57)
local function _shuffleIntoBuffer(rng: Random, buffer: { DirectionName })
	buffer[1] = DirectionsOrder[1]
	buffer[2] = DirectionsOrder[2]
	buffer[3] = DirectionsOrder[3]
	buffer[4] = DirectionsOrder[4]

	for i = 4, 2, -1 do
		local j = rng:NextInteger(1, i)
		local temp = buffer[i]
		buffer[i] = buffer[j]
		buffer[j] = temp
	end
end

-- Internal helper: classify room archetype based on door topology (Rule 57)
local function _classifyHallway(doors: DungeonTypes.DoorDirections, doorCount: number): RoomType
	if doorCount == 1 then
		return "DeadEnd"
	elseif doorCount == 2 then
		if (doors.North and doors.South) or (doors.East and doors.West) then
			return "HallwayStraight"
		end
		return "HallwayCorner"
	elseif doorCount == 3 then
		return "HallwayTee"
	elseif doorCount >= 4 then
		return "HallwayCross"
	end
	return "DeadEnd"
end

function DungeonGenerator.generate(overrideSeed: number?, overrideRoomCount: number?): GenerationResult
	local startTime = os.clock()

	-- Rule 75 & Rule 163: Isolated Random instance + numeric separators
	local seed = if typeof(overrideSeed) == "number"
		then math.floor(overrideSeed)
		else Random.new():NextInteger(100_000, 999_999)

	local targetRooms = if typeof(overrideRoomCount) == "number"
		then math.clamp(math.floor(overrideRoomCount), DungeonConfig.MinRoomCount, DungeonConfig.MaxRoomCount)
		else DungeonConfig.DefaultRoomCount

	local rng = Random.new(seed)
	local cellSize = DungeonConfig.CellSize

	-- Pre-allocated capacity for room list to avoid dynamic resizing
	local occupied: { [string]: RoomNode } = {}
	local roomList: { RoomNode } = table.create(targetRooms)

	local function _createNode(pos: GridPosition, depth: number): RoomNode
		local id = DungeonGrid.toKey(pos)
		local node: RoomNode = {
			id = id,
			gridPos = pos,
			worldPos = DungeonGrid.gridToWorld(pos, cellSize, 0),
			roomType = "HallwayStraight",
			doors = { North = false, South = false, East = false, West = false },
			doorCount = 0,
			depthFromStart = depth,
			neighbors = {},
		}
		occupied[id] = node
		table.insert(roomList, node)
		return node
	end

	local function _connectNodes(a: RoomNode, b: RoomNode, dirFromA: DirectionName)
		local dirFromB = DungeonGrid.OPPOSITE_DIRECTIONS[dirFromA]
		if not a.doors[dirFromA] then
			a.doors[dirFromA] = true
			a.doorCount += 1
			a.neighbors[dirFromA] = b.id
		end
		if not b.doors[dirFromB] then
			b.doors[dirFromB] = true
			b.doorCount += 1
			b.neighbors[dirFromB] = a.id
		end
	end

	-- 1. Initialize Start Room at origin (0, 0)
	local startNode = _createNode({ x = 0, y = 0 }, 0)
	startNode.roomType = "Start"

	-- 2. Build Critical Path (Main spine of the dungeon)
	local mainPathTarget = math.max(4, math.floor(targetRooms * DungeonConfig.MainPathRatio))
	local currentNode = startNode
	local mainSpineNodes: { RoomNode } = table.create(mainPathTarget + 1)
	table.insert(mainSpineNodes, startNode)

	for _ = 1, mainPathTarget do
		_shuffleIntoBuffer(rng, ScratchPrimary)
		local stepped = false

		for i = 1, 4 do
			local dir = ScratchPrimary[i]
			local nextPos = DungeonGrid.getNeighborPos(currentNode.gridPos, dir)
			local key = DungeonGrid.toKey(nextPos)

			if not occupied[key] then
				local nextNode = _createNode(nextPos, currentNode.depthFromStart + 1)
				_connectNodes(currentNode, nextNode, dir)
				currentNode = nextNode
				table.insert(mainSpineNodes, nextNode)
				stepped = true
				break
			end
		end

		if not stepped then
			-- Backtrack along the spine to find an unblocked branching point
			for bi = #mainSpineNodes - 1, 1, -1 do
				local prior = mainSpineNodes[bi]
				_shuffleIntoBuffer(rng, ScratchSecondary)

				for i = 1, 4 do
					local dir = ScratchSecondary[i]
					local nextPos = DungeonGrid.getNeighborPos(prior.gridPos, dir)
					local key = DungeonGrid.toKey(nextPos)

					if not occupied[key] then
						local nextNode = _createNode(nextPos, prior.depthFromStart + 1)
						_connectNodes(prior, nextNode, dir)
						currentNode = nextNode
						table.insert(mainSpineNodes, nextNode)
						stepped = true
						break
					end
				end

				if stepped then
					break
				end
			end

			if not stepped then
				break
			end
		end
	end

	local mainSpineCount = #roomList

	-- 3. Branching Expansion (Secondary branches)
	local attempts = 0
	local maxAttempts = targetRooms * 15

	while #roomList < targetRooms and attempts < maxAttempts do
		attempts += 1
		local parentIndex = rng:NextInteger(1, #roomList)
		local parentNode = roomList[parentIndex]

		if rng:NextNumber() <= DungeonConfig.BranchProbability then
			_shuffleIntoBuffer(rng, ScratchPrimary)
			for i = 1, 4 do
				local dir = ScratchPrimary[i]
				local nextPos = DungeonGrid.getNeighborPos(parentNode.gridPos, dir)
				local key = DungeonGrid.toKey(nextPos)

				if not occupied[key] then
					local newNode = _createNode(nextPos, parentNode.depthFromStart + 1)
					_connectNodes(parentNode, newNode, dir)
					break
				end
			end
		end
	end

	local branchCount = #roomList - mainSpineCount

	-- 4. Determine Exit Room (Maximum topological depth from Start)
	local exitCandidate: RoomNode = startNode
	local maxDepth = 0

	for i = 1, #roomList do
		local node = roomList[i]
		if node.id ~= startNode.id and node.depthFromStart > maxDepth then
			maxDepth = node.depthFromStart
			exitCandidate = node
		end
	end

	exitCandidate.roomType = "Exit"

	-- 5. Classify Dead Ends and Loot Vaults
	local maxLootRooms = math.max(1, math.floor(targetRooms * DungeonConfig.MaxLootRoomRatio))
	local lootRooms: { RoomNode } = table.create(maxLootRooms)

	for i = 1, #roomList do
		local node = roomList[i]
		if node.id == startNode.id then
			node.roomType = "Start"
		elseif node.id == exitCandidate.id then
			node.roomType = "Exit"
		else
			local defaultClass = _classifyHallway(node.doors, node.doorCount)
			if defaultClass == "DeadEnd" then
				if rng:NextNumber() <= DungeonConfig.LootRoomProbability and #lootRooms < maxLootRooms then
					node.roomType = "Loot"
					table.insert(lootRooms, node)
				else
					node.roomType = "DeadEnd"
				end
			else
				node.roomType = defaultClass
			end
		end
	end

	-- 6. Verification: Reachability Check via Breadth-First Search (BFS)
	local visited: { [string]: boolean } = { [startNode.id] = true }
	local queue: { RoomNode } = table.create(targetRooms)
	queue[1] = startNode
	local head = 1

	while head <= #queue do
		local curr = queue[head]
		head += 1

		-- Generalized Luau iteration (Rule 163)
		for _, neighborId in curr.neighbors do
			if not visited[neighborId] and occupied[neighborId] then
				visited[neighborId] = true
				table.insert(queue, occupied[neighborId])
			end
		end
	end

	local isReachable = (visited[exitCandidate.id] == true)
	local genDuration = (os.clock() - startTime) * 1_000

	local result: GenerationResult = {
		seed = seed,
		rooms = occupied,
		roomList = roomList,
		startRoom = startNode,
		exitRoom = exitCandidate,
		lootRooms = lootRooms,
		totalRooms = #roomList,
		mainSpineCount = mainSpineCount,
		branchCount = branchCount,
		maxDepth = maxDepth,
		generationTimeMs = math.round(genDuration * 1_000) / 1_000,
		isReachable = isReachable,
		hasCollisions = false,
	}

	return result
end

return table.freeze(DungeonGenerator)
Source: src/shared/SharedModules/AtomicBinding.luau • Recursive tree pattern binder & destructor lifecycle
--!strict
-- [ProductionCore / Shared / SharedModules / AtomicBinding.luau]
-- Custom pattern-matching library: Resolves hierarchical instance trees with automated destructors

local RootAlias = "root"

local function parsePath(pathStr: string): { string }
	local pathArray = string.split(pathStr, "/")
	for idx = #pathArray, 1, -1 do
		if pathArray[idx] == "" then
			table.remove(pathArray, idx)
		end
	end
	return pathArray
end

local function isManifestResolved(resolvedManifest: { [string]: Instance }, manifestSizeTarget: number): boolean
	local manifestSize = 0
	for _ in pairs(resolvedManifest) do
		manifestSize += 1
	end
	assert(manifestSize <= manifestSizeTarget, tostring(manifestSize))
	return manifestSize == manifestSizeTarget
end

local function unbindNodeDescend(node: any, resolvedManifest: { [string]: Instance })
	if node.instance == nil then return end
	node.instance = nil
	local connections = node.connections
	if connections then
		for _, conn in ipairs(connections) do
			conn:Disconnect()
		end
		table.clear(connections)
	end
	if resolvedManifest and node.alias then
		resolvedManifest[node.alias] = nil
	end
	local children = node.children
	if children then
		for _, childNode in pairs(children) do
			unbindNodeDescend(childNode, resolvedManifest)
		end
	end
end

local AtomicBinding = {}
AtomicBinding.__index = AtomicBinding

export type Destructor = () -> () | RBXScriptConnection | Instance | { Destroy: (any) -> () } | { destroy: (any) -> () } | any
export type BoundCallback = (manifest: { [string]: Instance }) -> Destructor?

function AtomicBinding.new(manifest: { [string]: string }, boundFn: BoundCallback)
	local parsedManifest = {}
	local manifestSizeTarget = 1
	for alias, rawPath in pairs(manifest) do
		parsedManifest[alias] = parsePath(rawPath)
		manifestSizeTarget += 1
	end
	return setmetatable({
		_boundFn = boundFn,
		_parsedManifest = parsedManifest,
		_manifestSizeTarget = manifestSizeTarget,
		_boundRoots = {} :: { [Instance]: boolean },
		_dtorMap = {} :: { [Instance]: Destructor? },
		_connections = {},
		_rootInstToRootNode = {},
		_rootInstToManifest = {} :: { [Instance]: { [string]: Instance } },
	}, AtomicBinding)
end

function AtomicBinding:_startBoundFn(root: Instance, resolvedManifest: { [string]: Instance })
	if self._boundRoots[root] then
		return
	end
	self._boundRoots[root] = true
	local success, dtor = pcall(self._boundFn, resolvedManifest)
	if success then
		self._dtorMap[root] = dtor
	else
		warn(string.format("[AtomicBinding] Error executing bound callback on %s: %s", root:GetFullName(), tostring(dtor)))
	end
end

function AtomicBinding:_stopBoundFn(root: Instance)
	if not self._boundRoots[root] then return end
	self._boundRoots[root] = nil
	local dtor = self._dtorMap[root]
	self._dtorMap[root] = nil
	if dtor == nil then return end

	pcall(function()
		local dtorType = typeof(dtor)
		if dtorType == "function" then
			(dtor :: () -> ())()
		elseif dtorType == "RBXScriptConnection" then
			(dtor :: RBXScriptConnection):Disconnect()
		elseif dtorType == "Instance" then
			(dtor :: Instance):Destroy()
		elseif dtorType == "thread" then
			if coroutine.status(dtor :: thread) ~= "dead" then
				task.cancel(dtor :: thread)
			end
		elseif dtorType == "table" then
			local tbl = dtor :: any
			if typeof(tbl.Destroy) == "function" then
				tbl:Destroy()
			elseif typeof(tbl.destroy) == "function" then
				tbl:destroy()
			elseif typeof(tbl.Disconnect) == "function" then
				tbl:Disconnect()
			end
		end
	end)
end

function AtomicBinding:bindRoot(root: Instance)
	debug.profilebegin("AtomicBinding:BindRoot")
	local parsedManifest = self._parsedManifest
	local rootInstToRootNode = self._rootInstToRootNode
	local rootInstToManifest = self._rootInstToManifest
	local manifestSizeTarget = self._manifestSizeTarget
	assert(rootInstToManifest[root] == nil, "Root instance is already bound")

	local resolvedManifest: { [string]: Instance } = {}
	rootInstToManifest[root] = resolvedManifest

	local rootNode = {
		alias = RootAlias,
		instance = root,
		children = {},
		connections = {},
	}
	rootInstToRootNode[root] = rootNode

	-- Build hierarchical search tree from path segments
	for alias, parsedPath in pairs(parsedManifest) do
		local parentNode = rootNode
		for idx, childName in ipairs(parsedPath) do
			local leaf = idx == #parsedPath
			local childNode = parentNode.children[childName] or {}
			if leaf then
				childNode.alias = alias
			else
				childNode.children = childNode.children or {}
				childNode.connections = childNode.connections or {}
			end
			parentNode.children[childName] = childNode
			parentNode = childNode
		end
	end

	local function processNode(node: any)
		local instance = assert(node.instance)
		local children = node.children
		if node.alias then resolvedManifest[node.alias] = instance end

		if children then
			local function processAddChild(childInstance: Instance)
				local childNode = children[childInstance.Name]
				if not childNode or childNode.instance ~= nil then return end
				childNode.instance = childInstance
				processNode(childNode)
			end

			local function processDeleteChild(childInstance: Instance)
				local childNode = children[childInstance.Name]
				if not childNode or childNode.instance ~= childInstance then return end
				self:_stopBoundFn(root)
				unbindNodeDescend(childNode, resolvedManifest)

				-- Check if a matching replacement sibling already exists
				for _, sibling in ipairs(instance:GetChildren()) do
					if sibling.Name == childInstance.Name and sibling ~= childInstance then
						processAddChild(sibling)
						break
					end
				end
			end

			for _, child in ipairs(instance:GetChildren()) do processAddChild(child) end
			table.insert(node.connections, instance.ChildAdded:Connect(processAddChild))
			table.insert(node.connections, instance.ChildRemoved:Connect(processDeleteChild))
		end

		if isManifestResolved(resolvedManifest, manifestSizeTarget) then
			self:_startBoundFn(root, resolvedManifest)
		end
	end

	processNode(rootNode)
	debug.profileend()
end

function AtomicBinding:unbindRoot(root: Instance)
	self:_stopBoundFn(root)
	local rootNode = self._rootInstToRootNode[root]
	if rootNode then
		unbindNodeDescend(rootNode, self._rootInstToManifest[root])
		self._rootInstToRootNode[root] = nil
	end
	self._rootInstToManifest[root] = nil
	self._boundRoots[root] = nil
end

function AtomicBinding:destroy()
	for root in pairs(self._rootInstToManifest) do
		self:unbindRoot(root)
	end
	table.clear(self._rootInstToRootNode)
	table.clear(self._rootInstToManifest)
	table.clear(self._dtorMap)
	table.clear(self._boundRoots)
end
AtomicBinding.Destroy = AtomicBinding.destroy

return AtomicBinding
Source: src/shared/ModuleLoader.luau • Phased lifecycle orchestration (Init / Start) & boot pacing
--!strict
-- [ProductionCore / Shared / ModuleLoader.luau]
-- Core bootstrap lifecycle engine: Handles phased Init/Start, client pacing, and dependency resolution

local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local ModuleLoader = {}
local ModuleCache: { [string]: any } = {}
local ScopeBootStateByName = { Shared = false, Server = false, Client = false }

export type LifecycleUnit = {
	Name: string,
	Loaded: any,
	Priority: number,
}

local function CreateScopeBootProgressState(ScopeName: string)
	return {
		ScopeName = ScopeName,
		CurrentModuleName = "Preparing",
		CurrentPhaseName = "Boot",
		CurrentModulePercent = 0,
		CompletedStepCount = 0,
		TotalStepCount = 0,
		Percent = 0,
		IsComplete = false,
	}
end

local function CalculateScopeBootPercent(CompletedStepCount: number, TotalStepCount: number): number
	if TotalStepCount <= 0 then return 100 end
	local RawPercent = (CompletedStepCount / TotalStepCount) * 100
	return math.clamp(math.floor(RawPercent + 0.5), 0, 100)
end

local function CountLifecyclePhaseSteps(LifecycleUnits: { LifecycleUnit }, PhaseName: string): number
	local Count = 0
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			Count += 1
		end
	end
	return Count
end

local ScopeBootProgress: { [string]: any } = {}

local function ExecuteLifecyclePhase(ScopeName: string, LifecycleUnits: { LifecycleUnit }, PhaseName: string, Context: any)
	local progress = ScopeBootProgress[ScopeName]
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			if progress then
				progress.CurrentModuleName = Unit.Name
				progress.CurrentPhaseName = PhaseName
			end

			debug.profilebegin(ScopeName .. ":" .. Unit.Name .. ":" .. PhaseName)
			if PhaseName == "Start" then
				-- Asynchronous Start dispatch ensures services initialize without thread blocking
				task.spawn(function()
					local success, err = pcall(function()
						Loaded[PhaseName](Context)
					end)
					if not success then
						warn(string.format("[ModuleLoader] Error during asynchronous %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
					end
				end)
			else
				local success, err = pcall(function()
					Loaded[PhaseName](Context)
				end)
				if not success then
					error(string.format("[ModuleLoader] Error during %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
				end
			end
			debug.profileend()

			if progress then
				progress.CompletedStepCount += 1
				progress.Percent = CalculateScopeBootPercent(progress.CompletedStepCount, progress.TotalStepCount)
			end
		end
	end
end

-- Resolve module instance from a dot-delimited path
local function ResolveModuleInstance(scope: string, path: string): ModuleScript?
	local current: Instance? = nil

	if scope == "Shared" or path:match("^Packages%.") or path:match("^SharedModules%.") then
		current = ReplicatedStorage
	elseif scope == "Server" or path:match("^ServerModules%.") then
		local sss = game:GetService("ServerScriptService")
		current = sss
	else
		current = ReplicatedStorage
	end

	local parts = string.split(path, ".")
	for _, part in ipairs(parts) do
		if not current then return nil end
		current = current:FindFirstChild(part)
	end

	if current and current:IsA("ModuleScript") then
		return current :: ModuleScript
	end
	return nil
end

function ModuleLoader.Register(name: string, module: any)
	ModuleCache[name] = module
	local simpleName = name:match("([^%.]+)--!strict
-- [ProductionCore / Shared / ModuleLoader.luau]
-- Core bootstrap lifecycle engine: Handles phased Init/Start, client pacing, and dependency resolution

local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local ModuleLoader = {}
local ModuleCache: { [string]: any } = {}
local ScopeBootStateByName = { Shared = false, Server = false, Client = false }

export type LifecycleUnit = {
	Name: string,
	Loaded: any,
	Priority: number,
}

local function CreateScopeBootProgressState(ScopeName: string)
	return {
		ScopeName = ScopeName,
		CurrentModuleName = "Preparing",
		CurrentPhaseName = "Boot",
		CurrentModulePercent = 0,
		CompletedStepCount = 0,
		TotalStepCount = 0,
		Percent = 0,
		IsComplete = false,
	}
end

local function CalculateScopeBootPercent(CompletedStepCount: number, TotalStepCount: number): number
	if TotalStepCount <= 0 then return 100 end
	local RawPercent = (CompletedStepCount / TotalStepCount) * 100
	return math.clamp(math.floor(RawPercent + 0.5), 0, 100)
end

local function CountLifecyclePhaseSteps(LifecycleUnits: { LifecycleUnit }, PhaseName: string): number
	local Count = 0
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			Count += 1
		end
	end
	return Count
end

local ScopeBootProgress: { [string]: any } = {}

local function ExecuteLifecyclePhase(ScopeName: string, LifecycleUnits: { LifecycleUnit }, PhaseName: string, Context: any)
	local progress = ScopeBootProgress[ScopeName]
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			if progress then
				progress.CurrentModuleName = Unit.Name
				progress.CurrentPhaseName = PhaseName
			end

			debug.profilebegin(ScopeName .. ":" .. Unit.Name .. ":" .. PhaseName)
			if PhaseName == "Start" then
				-- Asynchronous Start dispatch ensures services initialize without thread blocking
				task.spawn(function()
					local success, err = pcall(function()
						Loaded[PhaseName](Context)
					end)
					if not success then
						warn(string.format("[ModuleLoader] Error during asynchronous %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
					end
				end)
			else
				local success, err = pcall(function()
					Loaded[PhaseName](Context)
				end)
				if not success then
					error(string.format("[ModuleLoader] Error during %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
				end
			end
			debug.profileend()

			if progress then
				progress.CompletedStepCount += 1
				progress.Percent = CalculateScopeBootPercent(progress.CompletedStepCount, progress.TotalStepCount)
			end
		end
	end
end

-- Resolve module instance from a dot-delimited path
local function ResolveModuleInstance(scope: string, path: string): ModuleScript?
	local current: Instance? = nil

	if scope == "Shared" or path:match("^Packages%.") or path:match("^SharedModules%.") then
		current = ReplicatedStorage
	elseif scope == "Server" or path:match("^ServerModules%.") then
		local sss = game:GetService("ServerScriptService")
		current = sss
	else
		current = ReplicatedStorage
	end

	local parts = string.split(path, ".")
	for _, part in ipairs(parts) do
		if not current then return nil end
		current = current:FindFirstChild(part)
	end

	if current and current:IsA("ModuleScript") then
		return current :: ModuleScript
	end
	return nil
end

function ModuleLoader.Register(name: string, module: any)
	ModuleCache[name] = module
	local simpleName = name:match("([^%.]+)--!strict
-- [ProductionCore / Shared / ModuleLoader.luau]
-- Core bootstrap lifecycle engine: Handles phased Init/Start, client pacing, and dependency resolution

local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local ModuleLoader = {}
local ModuleCache: { [string]: any } = {}
local ScopeBootStateByName = { Shared = false, Server = false, Client = false }

export type LifecycleUnit = {
	Name: string,
	Loaded: any,
	Priority: number,
}

local function CreateScopeBootProgressState(ScopeName: string)
	return {
		ScopeName = ScopeName,
		CurrentModuleName = "Preparing",
		CurrentPhaseName = "Boot",
		CurrentModulePercent = 0,
		CompletedStepCount = 0,
		TotalStepCount = 0,
		Percent = 0,
		IsComplete = false,
	}
end

local function CalculateScopeBootPercent(CompletedStepCount: number, TotalStepCount: number): number
	if TotalStepCount <= 0 then return 100 end
	local RawPercent = (CompletedStepCount / TotalStepCount) * 100
	return math.clamp(math.floor(RawPercent + 0.5), 0, 100)
end

local function CountLifecyclePhaseSteps(LifecycleUnits: { LifecycleUnit }, PhaseName: string): number
	local Count = 0
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			Count += 1
		end
	end
	return Count
end

local ScopeBootProgress: { [string]: any } = {}

local function ExecuteLifecyclePhase(ScopeName: string, LifecycleUnits: { LifecycleUnit }, PhaseName: string, Context: any)
	local progress = ScopeBootProgress[ScopeName]
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			if progress then
				progress.CurrentModuleName = Unit.Name
				progress.CurrentPhaseName = PhaseName
			end

			debug.profilebegin(ScopeName .. ":" .. Unit.Name .. ":" .. PhaseName)
			if PhaseName == "Start" then
				-- Asynchronous Start dispatch ensures services initialize without thread blocking
				task.spawn(function()
					local success, err = pcall(function()
						Loaded[PhaseName](Context)
					end)
					if not success then
						warn(string.format("[ModuleLoader] Error during asynchronous %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
					end
				end)
			else
				local success, err = pcall(function()
					Loaded[PhaseName](Context)
				end)
				if not success then
					error(string.format("[ModuleLoader] Error during %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
				end
			end
			debug.profileend()

			if progress then
				progress.CompletedStepCount += 1
				progress.Percent = CalculateScopeBootPercent(progress.CompletedStepCount, progress.TotalStepCount)
			end
		end
	end
end

-- Resolve module instance from a dot-delimited path
local function ResolveModuleInstance(scope: string, path: string): ModuleScript?
	local current: Instance? = nil

	if scope == "Shared" or path:match("^Packages%.") or path:match("^SharedModules%.") then
		current = ReplicatedStorage
	elseif scope == "Server" or path:match("^ServerModules%.") then
		local sss = game:GetService("ServerScriptService")
		current = sss
	else
		current = ReplicatedStorage
	end

	local parts = string.split(path, ".")
	for _, part in ipairs(parts) do
		if not current then return nil end
		current = current:FindFirstChild(part)
	end

	if current and current:IsA("ModuleScript") then
		return current :: ModuleScript
	end
	return nil
end

function ModuleLoader.Register(name: string, module: any)
	ModuleCache[name] = module
	local simpleName = name:match("([^%.]+)--!strict
-- [ProductionCore / Shared / ModuleLoader.luau]
-- Core bootstrap lifecycle engine: Handles phased Init/Start, client pacing, and dependency resolution

local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local ModuleLoader = {}
local ModuleCache: { [string]: any } = {}
local ScopeBootStateByName = { Shared = false, Server = false, Client = false }

export type LifecycleUnit = {
	Name: string,
	Loaded: any,
	Priority: number,
}

local function CreateScopeBootProgressState(ScopeName: string)
	return {
		ScopeName = ScopeName,
		CurrentModuleName = "Preparing",
		CurrentPhaseName = "Boot",
		CurrentModulePercent = 0,
		CompletedStepCount = 0,
		TotalStepCount = 0,
		Percent = 0,
		IsComplete = false,
	}
end

local function CalculateScopeBootPercent(CompletedStepCount: number, TotalStepCount: number): number
	if TotalStepCount <= 0 then return 100 end
	local RawPercent = (CompletedStepCount / TotalStepCount) * 100
	return math.clamp(math.floor(RawPercent + 0.5), 0, 100)
end

local function CountLifecyclePhaseSteps(LifecycleUnits: { LifecycleUnit }, PhaseName: string): number
	local Count = 0
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			Count += 1
		end
	end
	return Count
end

local ScopeBootProgress: { [string]: any } = {}

local function ExecuteLifecyclePhase(ScopeName: string, LifecycleUnits: { LifecycleUnit }, PhaseName: string, Context: any)
	local progress = ScopeBootProgress[ScopeName]
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			if progress then
				progress.CurrentModuleName = Unit.Name
				progress.CurrentPhaseName = PhaseName
			end

			debug.profilebegin(ScopeName .. ":" .. Unit.Name .. ":" .. PhaseName)
			if PhaseName == "Start" then
				-- Asynchronous Start dispatch ensures services initialize without thread blocking
				task.spawn(function()
					local success, err = pcall(function()
						Loaded[PhaseName](Context)
					end)
					if not success then
						warn(string.format("[ModuleLoader] Error during asynchronous %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
					end
				end)
			else
				local success, err = pcall(function()
					Loaded[PhaseName](Context)
				end)
				if not success then
					error(string.format("[ModuleLoader] Error during %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
				end
			end
			debug.profileend()

			if progress then
				progress.CompletedStepCount += 1
				progress.Percent = CalculateScopeBootPercent(progress.CompletedStepCount, progress.TotalStepCount)
			end
		end
	end
end

-- Resolve module instance from a dot-delimited path
local function ResolveModuleInstance(scope: string, path: string): ModuleScript?
	local current: Instance? = nil

	if scope == "Shared" or path:match("^Packages%.") or path:match("^SharedModules%.") then
		current = ReplicatedStorage
	elseif scope == "Server" or path:match("^ServerModules%.") then
		local sss = game:GetService("ServerScriptService")
		current = sss
	else
		current = ReplicatedStorage
	end

	local parts = string.split(path, ".")
	for _, part in ipairs(parts) do
		if not current then return nil end
		current = current:FindFirstChild(part)
	end

	if current and current:IsA("ModuleScript") then
		return current :: ModuleScript
	end
	return nil
end

function ModuleLoader.Register(name: string, module: any)
	ModuleCache[name] = module
	local simpleName = name:match("([^%.]+)--!strict
-- [ProductionCore / Shared / ModuleLoader.luau]
-- Core bootstrap lifecycle engine: Handles phased Init/Start, client pacing, and dependency resolution

local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local ModuleLoader = {}
local ModuleCache: { [string]: any } = {}
local ScopeBootStateByName = { Shared = false, Server = false, Client = false }

export type LifecycleUnit = {
	Name: string,
	Loaded: any,
	Priority: number,
}

local function CreateScopeBootProgressState(ScopeName: string)
	return {
		ScopeName = ScopeName,
		CurrentModuleName = "Preparing",
		CurrentPhaseName = "Boot",
		CurrentModulePercent = 0,
		CompletedStepCount = 0,
		TotalStepCount = 0,
		Percent = 0,
		IsComplete = false,
	}
end

local function CalculateScopeBootPercent(CompletedStepCount: number, TotalStepCount: number): number
	if TotalStepCount <= 0 then return 100 end
	local RawPercent = (CompletedStepCount / TotalStepCount) * 100
	return math.clamp(math.floor(RawPercent + 0.5), 0, 100)
end

local function CountLifecyclePhaseSteps(LifecycleUnits: { LifecycleUnit }, PhaseName: string): number
	local Count = 0
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			Count += 1
		end
	end
	return Count
end

local ScopeBootProgress: { [string]: any } = {}

local function ExecuteLifecyclePhase(ScopeName: string, LifecycleUnits: { LifecycleUnit }, PhaseName: string, Context: any)
	local progress = ScopeBootProgress[ScopeName]
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			if progress then
				progress.CurrentModuleName = Unit.Name
				progress.CurrentPhaseName = PhaseName
			end

			debug.profilebegin(ScopeName .. ":" .. Unit.Name .. ":" .. PhaseName)
			if PhaseName == "Start" then
				-- Asynchronous Start dispatch ensures services initialize without thread blocking
				task.spawn(function()
					local success, err = pcall(function()
						Loaded[PhaseName](Context)
					end)
					if not success then
						warn(string.format("[ModuleLoader] Error during asynchronous %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
					end
				end)
			else
				local success, err = pcall(function()
					Loaded[PhaseName](Context)
				end)
				if not success then
					error(string.format("[ModuleLoader] Error during %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
				end
			end
			debug.profileend()

			if progress then
				progress.CompletedStepCount += 1
				progress.Percent = CalculateScopeBootPercent(progress.CompletedStepCount, progress.TotalStepCount)
			end
		end
	end
end

-- Resolve module instance from a dot-delimited path
local function ResolveModuleInstance(scope: string, path: string): ModuleScript?
	local current: Instance? = nil

	if scope == "Shared" or path:match("^Packages%.") or path:match("^SharedModules%.") then
		current = ReplicatedStorage
	elseif scope == "Server" or path:match("^ServerModules%.") then
		local sss = game:GetService("ServerScriptService")
		current = sss
	else
		current = ReplicatedStorage
	end

	local parts = string.split(path, ".")
	for _, part in ipairs(parts) do
		if not current then return nil end
		current = current:FindFirstChild(part)
	end

	if current and current:IsA("ModuleScript") then
		return current :: ModuleScript
	end
	return nil
end

function ModuleLoader.Register(name: string, module: any)
	ModuleCache[name] = module
	local simpleName = name:match("([^%.]+)--!strict
-- [ProductionCore / Shared / ModuleLoader.luau]
-- Core bootstrap lifecycle engine: Handles phased Init/Start, client pacing, and dependency resolution

local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local ModuleLoader = {}
local ModuleCache: { [string]: any } = {}
local ScopeBootStateByName = { Shared = false, Server = false, Client = false }

export type LifecycleUnit = {
	Name: string,
	Loaded: any,
	Priority: number,
}

local function CreateScopeBootProgressState(ScopeName: string)
	return {
		ScopeName = ScopeName,
		CurrentModuleName = "Preparing",
		CurrentPhaseName = "Boot",
		CurrentModulePercent = 0,
		CompletedStepCount = 0,
		TotalStepCount = 0,
		Percent = 0,
		IsComplete = false,
	}
end

local function CalculateScopeBootPercent(CompletedStepCount: number, TotalStepCount: number): number
	if TotalStepCount <= 0 then return 100 end
	local RawPercent = (CompletedStepCount / TotalStepCount) * 100
	return math.clamp(math.floor(RawPercent + 0.5), 0, 100)
end

local function CountLifecyclePhaseSteps(LifecycleUnits: { LifecycleUnit }, PhaseName: string): number
	local Count = 0
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			Count += 1
		end
	end
	return Count
end

local ScopeBootProgress: { [string]: any } = {}

local function ExecuteLifecyclePhase(ScopeName: string, LifecycleUnits: { LifecycleUnit }, PhaseName: string, Context: any)
	local progress = ScopeBootProgress[ScopeName]
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			if progress then
				progress.CurrentModuleName = Unit.Name
				progress.CurrentPhaseName = PhaseName
			end

			debug.profilebegin(ScopeName .. ":" .. Unit.Name .. ":" .. PhaseName)
			if PhaseName == "Start" then
				-- Asynchronous Start dispatch ensures services initialize without thread blocking
				task.spawn(function()
					local success, err = pcall(function()
						Loaded[PhaseName](Context)
					end)
					if not success then
						warn(string.format("[ModuleLoader] Error during asynchronous %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
					end
				end)
			else
				local success, err = pcall(function()
					Loaded[PhaseName](Context)
				end)
				if not success then
					error(string.format("[ModuleLoader] Error during %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
				end
			end
			debug.profileend()

			if progress then
				progress.CompletedStepCount += 1
				progress.Percent = CalculateScopeBootPercent(progress.CompletedStepCount, progress.TotalStepCount)
			end
		end
	end
end

-- Resolve module instance from a dot-delimited path
local function ResolveModuleInstance(scope: string, path: string): ModuleScript?
	local current: Instance? = nil

	if scope == "Shared" or path:match("^Packages%.") or path:match("^SharedModules%.") then
		current = ReplicatedStorage
	elseif scope == "Server" or path:match("^ServerModules%.") then
		local sss = game:GetService("ServerScriptService")
		current = sss
	else
		current = ReplicatedStorage
	end

	local parts = string.split(path, ".")
	for _, part in ipairs(parts) do
		if not current then return nil end
		current = current:FindFirstChild(part)
	end

	if current and current:IsA("ModuleScript") then
		return current :: ModuleScript
	end
	return nil
end

function ModuleLoader.Register(name: string, module: any)
	ModuleCache[name] = module
	local simpleName = name:match("([^%.]+)--!strict
-- [ProductionCore / Shared / ModuleLoader.luau]
-- Core bootstrap lifecycle engine: Handles phased Init/Start, client pacing, and dependency resolution

local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local ModuleLoader = {}
local ModuleCache: { [string]: any } = {}
local ScopeBootStateByName = { Shared = false, Server = false, Client = false }

export type LifecycleUnit = {
	Name: string,
	Loaded: any,
	Priority: number,
}

local function CreateScopeBootProgressState(ScopeName: string)
	return {
		ScopeName = ScopeName,
		CurrentModuleName = "Preparing",
		CurrentPhaseName = "Boot",
		CurrentModulePercent = 0,
		CompletedStepCount = 0,
		TotalStepCount = 0,
		Percent = 0,
		IsComplete = false,
	}
end

local function CalculateScopeBootPercent(CompletedStepCount: number, TotalStepCount: number): number
	if TotalStepCount <= 0 then return 100 end
	local RawPercent = (CompletedStepCount / TotalStepCount) * 100
	return math.clamp(math.floor(RawPercent + 0.5), 0, 100)
end

local function CountLifecyclePhaseSteps(LifecycleUnits: { LifecycleUnit }, PhaseName: string): number
	local Count = 0
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			Count += 1
		end
	end
	return Count
end

local ScopeBootProgress: { [string]: any } = {}

local function ExecuteLifecyclePhase(ScopeName: string, LifecycleUnits: { LifecycleUnit }, PhaseName: string, Context: any)
	local progress = ScopeBootProgress[ScopeName]
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			if progress then
				progress.CurrentModuleName = Unit.Name
				progress.CurrentPhaseName = PhaseName
			end

			debug.profilebegin(ScopeName .. ":" .. Unit.Name .. ":" .. PhaseName)
			if PhaseName == "Start" then
				-- Asynchronous Start dispatch ensures services initialize without thread blocking
				task.spawn(function()
					local success, err = pcall(function()
						Loaded[PhaseName](Context)
					end)
					if not success then
						warn(string.format("[ModuleLoader] Error during asynchronous %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
					end
				end)
			else
				local success, err = pcall(function()
					Loaded[PhaseName](Context)
				end)
				if not success then
					error(string.format("[ModuleLoader] Error during %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
				end
			end
			debug.profileend()

			if progress then
				progress.CompletedStepCount += 1
				progress.Percent = CalculateScopeBootPercent(progress.CompletedStepCount, progress.TotalStepCount)
			end
		end
	end
end

-- Resolve module instance from a dot-delimited path
local function ResolveModuleInstance(scope: string, path: string): ModuleScript?
	local current: Instance? = nil

	if scope == "Shared" or path:match("^Packages%.") or path:match("^SharedModules%.") then
		current = ReplicatedStorage
	elseif scope == "Server" or path:match("^ServerModules%.") then
		local sss = game:GetService("ServerScriptService")
		current = sss
	else
		current = ReplicatedStorage
	end

	local parts = string.split(path, ".")
	for _, part in ipairs(parts) do
		if not current then return nil end
		current = current:FindFirstChild(part)
	end

	if current and current:IsA("ModuleScript") then
		return current :: ModuleScript
	end
	return nil
end

function ModuleLoader.Register(name: string, module: any)
	ModuleCache[name] = module
	local simpleName = name:match("([^%.]+)--!strict
-- [ProductionCore / Shared / ModuleLoader.luau]
-- Core bootstrap lifecycle engine: Handles phased Init/Start, client pacing, and dependency resolution

local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local ModuleLoader = {}
local ModuleCache: { [string]: any } = {}
local ScopeBootStateByName = { Shared = false, Server = false, Client = false }

export type LifecycleUnit = {
	Name: string,
	Loaded: any,
	Priority: number,
}

local function CreateScopeBootProgressState(ScopeName: string)
	return {
		ScopeName = ScopeName,
		CurrentModuleName = "Preparing",
		CurrentPhaseName = "Boot",
		CurrentModulePercent = 0,
		CompletedStepCount = 0,
		TotalStepCount = 0,
		Percent = 0,
		IsComplete = false,
	}
end

local function CalculateScopeBootPercent(CompletedStepCount: number, TotalStepCount: number): number
	if TotalStepCount <= 0 then return 100 end
	local RawPercent = (CompletedStepCount / TotalStepCount) * 100
	return math.clamp(math.floor(RawPercent + 0.5), 0, 100)
end

local function CountLifecyclePhaseSteps(LifecycleUnits: { LifecycleUnit }, PhaseName: string): number
	local Count = 0
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			Count += 1
		end
	end
	return Count
end

local function ExecuteLifecyclePhase(ScopeName: string, LifecycleUnits: { LifecycleUnit }, PhaseName: string, Context: any)
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			debug.profilebegin(ScopeName .. ":" .. Unit.Name .. ":" .. PhaseName)
			local success, err = pcall(function()
				Loaded[PhaseName](Context)
			end)
			debug.profileend()
			if not success then
				error(string.format("[ModuleLoader] Error during %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
			end
		end
	end
end

-- Resolve module instance from a dot-delimited path
local function ResolveModuleInstance(scope: string, path: string): ModuleScript?
	local current: Instance? = nil

	if scope == "Shared" or path:match("^Packages%.") or path:match("^SharedModules%.") then
		current = ReplicatedStorage
	elseif scope == "Server" or path:match("^ServerModules%.") then
		local sss = game:GetService("ServerScriptService")
		current = sss
	else
		current = ReplicatedStorage
	end

	local parts = string.split(path, ".")
	for _, part in ipairs(parts) do
		if not current then return nil end
		current = current:FindFirstChild(part)
	end

	if current and current:IsA("ModuleScript") then
		return current :: ModuleScript
	end
	return nil
end

function ModuleLoader.Register(name: string, module: any)
	ModuleCache[name] = module
end

function ModuleLoader.Require(scope: string, path: string): any
	local cacheKey = scope .. ":" .. path
	if ModuleCache[cacheKey] ~= nil then
		return ModuleCache[cacheKey]
	end
	if ModuleCache[path] ~= nil then
		return ModuleCache[path]
	end

	local inst = ResolveModuleInstance(scope, path)
	if inst then
		local loaded = require(inst)
		ModuleCache[cacheKey] = loaded
		ModuleCache[path] = loaded
		return loaded
	end

	-- Check fallback in cache under simple name
	local simpleName = path:match("([^%.]+)$") or path
	if ModuleCache[simpleName] ~= nil then
		return ModuleCache[simpleName]
	end

	error(string.format("[ModuleLoader] Could not resolve module '%s' in scope '%s'", path, scope))
end

function ModuleLoader.RequireShared(path: string): any
	return ModuleLoader.Require("Shared", path)
end

function ModuleLoader.RequireScoped(path: string): any
	local isServer = RunService:IsServer()
	local scope = if isServer then "Server" else "Client"
	return ModuleLoader.Require(scope, path)
end

function ModuleLoader.Boot(scopeName: string, container: Instance)
	local units: { LifecycleUnit } = {}

	for _, descendant in ipairs(container:GetDescendants()) do
		if descendant:IsA("ModuleScript") then
			local success, loaded = pcall(require, descendant)
			if success then
				local priority = 10
				if type(loaded) == "table" and type(loaded.Metadata) == "table" and type(loaded.Metadata.Priority) == "number" then
					priority = loaded.Metadata.Priority
				end
				table.insert(units, {
					Name = descendant.Name,
					Loaded = loaded,
					Priority = priority,
				})
				ModuleCache[descendant.Name] = loaded
			else
				warn(string.format("[ModuleLoader] Failed to require %s: %s", descendant:GetFullName(), tostring(loaded)))
			end
		end
	end

	-- Sort by Priority descending (higher priority inits first)
	table.sort(units, function(a, b)
		return a.Priority > b.Priority
	end)

	local context = {
		ModuleLoader = ModuleLoader,
	}

	-- Phase 1: Synchronous Init
	ExecuteLifecyclePhase(scopeName, units, "Init", context)

	-- Phase 2: Asynchronous Start
	ExecuteLifecyclePhase(scopeName, units, "Start", context)

	ScopeBootStateByName[scopeName] = true
	print(string.format("[ModuleLoader] Scope '%s' boot completed (%d modules).", scopeName, #units))
end

return ModuleLoaderquot;)
	if simpleName and ModuleCache[simpleName] == nil then
		ModuleCache[simpleName] = module
	end
end

function ModuleLoader.GetBootProgress(scopeName: string): any?
	return ScopeBootProgress[scopeName]
end

function ModuleLoader.Require(scope: string, path: string): any
	local cacheKey = scope .. ":" .. path
	if ModuleCache[cacheKey] ~= nil then
		return ModuleCache[cacheKey]
	end
	if ModuleCache[path] ~= nil then
		return ModuleCache[path]
	end

	local inst = ResolveModuleInstance(scope, path)
	if inst then
		local loaded = require(inst)
		ModuleCache[cacheKey] = loaded
		ModuleCache[path] = loaded
		return loaded
	end

	-- Check fallback in cache under simple name
	local simpleName = path:match("([^%.]+)--!strict
-- [ProductionCore / Shared / ModuleLoader.luau]
-- Core bootstrap lifecycle engine: Handles phased Init/Start, client pacing, and dependency resolution

local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local ModuleLoader = {}
local ModuleCache: { [string]: any } = {}
local ScopeBootStateByName = { Shared = false, Server = false, Client = false }

export type LifecycleUnit = {
	Name: string,
	Loaded: any,
	Priority: number,
}

local function CreateScopeBootProgressState(ScopeName: string)
	return {
		ScopeName = ScopeName,
		CurrentModuleName = "Preparing",
		CurrentPhaseName = "Boot",
		CurrentModulePercent = 0,
		CompletedStepCount = 0,
		TotalStepCount = 0,
		Percent = 0,
		IsComplete = false,
	}
end

local function CalculateScopeBootPercent(CompletedStepCount: number, TotalStepCount: number): number
	if TotalStepCount <= 0 then return 100 end
	local RawPercent = (CompletedStepCount / TotalStepCount) * 100
	return math.clamp(math.floor(RawPercent + 0.5), 0, 100)
end

local function CountLifecyclePhaseSteps(LifecycleUnits: { LifecycleUnit }, PhaseName: string): number
	local Count = 0
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			Count += 1
		end
	end
	return Count
end

local ScopeBootProgress: { [string]: any } = {}

local function ExecuteLifecyclePhase(ScopeName: string, LifecycleUnits: { LifecycleUnit }, PhaseName: string, Context: any)
	local progress = ScopeBootProgress[ScopeName]
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			if progress then
				progress.CurrentModuleName = Unit.Name
				progress.CurrentPhaseName = PhaseName
			end

			debug.profilebegin(ScopeName .. ":" .. Unit.Name .. ":" .. PhaseName)
			if PhaseName == "Start" then
				-- Asynchronous Start dispatch ensures services initialize without thread blocking
				task.spawn(function()
					local success, err = pcall(function()
						Loaded[PhaseName](Context)
					end)
					if not success then
						warn(string.format("[ModuleLoader] Error during asynchronous %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
					end
				end)
			else
				local success, err = pcall(function()
					Loaded[PhaseName](Context)
				end)
				if not success then
					error(string.format("[ModuleLoader] Error during %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
				end
			end
			debug.profileend()

			if progress then
				progress.CompletedStepCount += 1
				progress.Percent = CalculateScopeBootPercent(progress.CompletedStepCount, progress.TotalStepCount)
			end
		end
	end
end

-- Resolve module instance from a dot-delimited path
local function ResolveModuleInstance(scope: string, path: string): ModuleScript?
	local current: Instance? = nil

	if scope == "Shared" or path:match("^Packages%.") or path:match("^SharedModules%.") then
		current = ReplicatedStorage
	elseif scope == "Server" or path:match("^ServerModules%.") then
		local sss = game:GetService("ServerScriptService")
		current = sss
	else
		current = ReplicatedStorage
	end

	local parts = string.split(path, ".")
	for _, part in ipairs(parts) do
		if not current then return nil end
		current = current:FindFirstChild(part)
	end

	if current and current:IsA("ModuleScript") then
		return current :: ModuleScript
	end
	return nil
end

function ModuleLoader.Register(name: string, module: any)
	ModuleCache[name] = module
	local simpleName = name:match("([^%.]+)--!strict
-- [ProductionCore / Shared / ModuleLoader.luau]
-- Core bootstrap lifecycle engine: Handles phased Init/Start, client pacing, and dependency resolution

local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local ModuleLoader = {}
local ModuleCache: { [string]: any } = {}
local ScopeBootStateByName = { Shared = false, Server = false, Client = false }

export type LifecycleUnit = {
	Name: string,
	Loaded: any,
	Priority: number,
}

local function CreateScopeBootProgressState(ScopeName: string)
	return {
		ScopeName = ScopeName,
		CurrentModuleName = "Preparing",
		CurrentPhaseName = "Boot",
		CurrentModulePercent = 0,
		CompletedStepCount = 0,
		TotalStepCount = 0,
		Percent = 0,
		IsComplete = false,
	}
end

local function CalculateScopeBootPercent(CompletedStepCount: number, TotalStepCount: number): number
	if TotalStepCount <= 0 then return 100 end
	local RawPercent = (CompletedStepCount / TotalStepCount) * 100
	return math.clamp(math.floor(RawPercent + 0.5), 0, 100)
end

local function CountLifecyclePhaseSteps(LifecycleUnits: { LifecycleUnit }, PhaseName: string): number
	local Count = 0
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			Count += 1
		end
	end
	return Count
end

local ScopeBootProgress: { [string]: any } = {}

local function ExecuteLifecyclePhase(ScopeName: string, LifecycleUnits: { LifecycleUnit }, PhaseName: string, Context: any)
	local progress = ScopeBootProgress[ScopeName]
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			if progress then
				progress.CurrentModuleName = Unit.Name
				progress.CurrentPhaseName = PhaseName
			end

			debug.profilebegin(ScopeName .. ":" .. Unit.Name .. ":" .. PhaseName)
			if PhaseName == "Start" then
				-- Asynchronous Start dispatch ensures services initialize without thread blocking
				task.spawn(function()
					local success, err = pcall(function()
						Loaded[PhaseName](Context)
					end)
					if not success then
						warn(string.format("[ModuleLoader] Error during asynchronous %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
					end
				end)
			else
				local success, err = pcall(function()
					Loaded[PhaseName](Context)
				end)
				if not success then
					error(string.format("[ModuleLoader] Error during %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
				end
			end
			debug.profileend()

			if progress then
				progress.CompletedStepCount += 1
				progress.Percent = CalculateScopeBootPercent(progress.CompletedStepCount, progress.TotalStepCount)
			end
		end
	end
end

-- Resolve module instance from a dot-delimited path
local function ResolveModuleInstance(scope: string, path: string): ModuleScript?
	local current: Instance? = nil

	if scope == "Shared" or path:match("^Packages%.") or path:match("^SharedModules%.") then
		current = ReplicatedStorage
	elseif scope == "Server" or path:match("^ServerModules%.") then
		local sss = game:GetService("ServerScriptService")
		current = sss
	else
		current = ReplicatedStorage
	end

	local parts = string.split(path, ".")
	for _, part in ipairs(parts) do
		if not current then return nil end
		current = current:FindFirstChild(part)
	end

	if current and current:IsA("ModuleScript") then
		return current :: ModuleScript
	end
	return nil
end

function ModuleLoader.Register(name: string, module: any)
	ModuleCache[name] = module
	local simpleName = name:match("([^%.]+)--!strict
-- [ProductionCore / Shared / ModuleLoader.luau]
-- Core bootstrap lifecycle engine: Handles phased Init/Start, client pacing, and dependency resolution

local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local ModuleLoader = {}
local ModuleCache: { [string]: any } = {}
local ScopeBootStateByName = { Shared = false, Server = false, Client = false }

export type LifecycleUnit = {
	Name: string,
	Loaded: any,
	Priority: number,
}

local function CreateScopeBootProgressState(ScopeName: string)
	return {
		ScopeName = ScopeName,
		CurrentModuleName = "Preparing",
		CurrentPhaseName = "Boot",
		CurrentModulePercent = 0,
		CompletedStepCount = 0,
		TotalStepCount = 0,
		Percent = 0,
		IsComplete = false,
	}
end

local function CalculateScopeBootPercent(CompletedStepCount: number, TotalStepCount: number): number
	if TotalStepCount <= 0 then return 100 end
	local RawPercent = (CompletedStepCount / TotalStepCount) * 100
	return math.clamp(math.floor(RawPercent + 0.5), 0, 100)
end

local function CountLifecyclePhaseSteps(LifecycleUnits: { LifecycleUnit }, PhaseName: string): number
	local Count = 0
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			Count += 1
		end
	end
	return Count
end

local ScopeBootProgress: { [string]: any } = {}

local function ExecuteLifecyclePhase(ScopeName: string, LifecycleUnits: { LifecycleUnit }, PhaseName: string, Context: any)
	local progress = ScopeBootProgress[ScopeName]
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			if progress then
				progress.CurrentModuleName = Unit.Name
				progress.CurrentPhaseName = PhaseName
			end

			debug.profilebegin(ScopeName .. ":" .. Unit.Name .. ":" .. PhaseName)
			if PhaseName == "Start" then
				-- Asynchronous Start dispatch ensures services initialize without thread blocking
				task.spawn(function()
					local success, err = pcall(function()
						Loaded[PhaseName](Context)
					end)
					if not success then
						warn(string.format("[ModuleLoader] Error during asynchronous %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
					end
				end)
			else
				local success, err = pcall(function()
					Loaded[PhaseName](Context)
				end)
				if not success then
					error(string.format("[ModuleLoader] Error during %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
				end
			end
			debug.profileend()

			if progress then
				progress.CompletedStepCount += 1
				progress.Percent = CalculateScopeBootPercent(progress.CompletedStepCount, progress.TotalStepCount)
			end
		end
	end
end

-- Resolve module instance from a dot-delimited path
local function ResolveModuleInstance(scope: string, path: string): ModuleScript?
	local current: Instance? = nil

	if scope == "Shared" or path:match("^Packages%.") or path:match("^SharedModules%.") then
		current = ReplicatedStorage
	elseif scope == "Server" or path:match("^ServerModules%.") then
		local sss = game:GetService("ServerScriptService")
		current = sss
	else
		current = ReplicatedStorage
	end

	local parts = string.split(path, ".")
	for _, part in ipairs(parts) do
		if not current then return nil end
		current = current:FindFirstChild(part)
	end

	if current and current:IsA("ModuleScript") then
		return current :: ModuleScript
	end
	return nil
end

function ModuleLoader.Register(name: string, module: any)
	ModuleCache[name] = module
	local simpleName = name:match("([^%.]+)--!strict
-- [ProductionCore / Shared / ModuleLoader.luau]
-- Core bootstrap lifecycle engine: Handles phased Init/Start, client pacing, and dependency resolution

local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local ModuleLoader = {}
local ModuleCache: { [string]: any } = {}
local ScopeBootStateByName = { Shared = false, Server = false, Client = false }

export type LifecycleUnit = {
	Name: string,
	Loaded: any,
	Priority: number,
}

local function CreateScopeBootProgressState(ScopeName: string)
	return {
		ScopeName = ScopeName,
		CurrentModuleName = "Preparing",
		CurrentPhaseName = "Boot",
		CurrentModulePercent = 0,
		CompletedStepCount = 0,
		TotalStepCount = 0,
		Percent = 0,
		IsComplete = false,
	}
end

local function CalculateScopeBootPercent(CompletedStepCount: number, TotalStepCount: number): number
	if TotalStepCount <= 0 then return 100 end
	local RawPercent = (CompletedStepCount / TotalStepCount) * 100
	return math.clamp(math.floor(RawPercent + 0.5), 0, 100)
end

local function CountLifecyclePhaseSteps(LifecycleUnits: { LifecycleUnit }, PhaseName: string): number
	local Count = 0
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			Count += 1
		end
	end
	return Count
end

local ScopeBootProgress: { [string]: any } = {}

local function ExecuteLifecyclePhase(ScopeName: string, LifecycleUnits: { LifecycleUnit }, PhaseName: string, Context: any)
	local progress = ScopeBootProgress[ScopeName]
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			if progress then
				progress.CurrentModuleName = Unit.Name
				progress.CurrentPhaseName = PhaseName
			end

			debug.profilebegin(ScopeName .. ":" .. Unit.Name .. ":" .. PhaseName)
			if PhaseName == "Start" then
				-- Asynchronous Start dispatch ensures services initialize without thread blocking
				task.spawn(function()
					local success, err = pcall(function()
						Loaded[PhaseName](Context)
					end)
					if not success then
						warn(string.format("[ModuleLoader] Error during asynchronous %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
					end
				end)
			else
				local success, err = pcall(function()
					Loaded[PhaseName](Context)
				end)
				if not success then
					error(string.format("[ModuleLoader] Error during %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
				end
			end
			debug.profileend()

			if progress then
				progress.CompletedStepCount += 1
				progress.Percent = CalculateScopeBootPercent(progress.CompletedStepCount, progress.TotalStepCount)
			end
		end
	end
end

-- Resolve module instance from a dot-delimited path
local function ResolveModuleInstance(scope: string, path: string): ModuleScript?
	local current: Instance? = nil

	if scope == "Shared" or path:match("^Packages%.") or path:match("^SharedModules%.") then
		current = ReplicatedStorage
	elseif scope == "Server" or path:match("^ServerModules%.") then
		local sss = game:GetService("ServerScriptService")
		current = sss
	else
		current = ReplicatedStorage
	end

	local parts = string.split(path, ".")
	for _, part in ipairs(parts) do
		if not current then return nil end
		current = current:FindFirstChild(part)
	end

	if current and current:IsA("ModuleScript") then
		return current :: ModuleScript
	end
	return nil
end

function ModuleLoader.Register(name: string, module: any)
	ModuleCache[name] = module
	local simpleName = name:match("([^%.]+)--!strict
-- [ProductionCore / Shared / ModuleLoader.luau]
-- Core bootstrap lifecycle engine: Handles phased Init/Start, client pacing, and dependency resolution

local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local ModuleLoader = {}
local ModuleCache: { [string]: any } = {}
local ScopeBootStateByName = { Shared = false, Server = false, Client = false }

export type LifecycleUnit = {
	Name: string,
	Loaded: any,
	Priority: number,
}

local function CreateScopeBootProgressState(ScopeName: string)
	return {
		ScopeName = ScopeName,
		CurrentModuleName = "Preparing",
		CurrentPhaseName = "Boot",
		CurrentModulePercent = 0,
		CompletedStepCount = 0,
		TotalStepCount = 0,
		Percent = 0,
		IsComplete = false,
	}
end

local function CalculateScopeBootPercent(CompletedStepCount: number, TotalStepCount: number): number
	if TotalStepCount <= 0 then return 100 end
	local RawPercent = (CompletedStepCount / TotalStepCount) * 100
	return math.clamp(math.floor(RawPercent + 0.5), 0, 100)
end

local function CountLifecyclePhaseSteps(LifecycleUnits: { LifecycleUnit }, PhaseName: string): number
	local Count = 0
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			Count += 1
		end
	end
	return Count
end

local ScopeBootProgress: { [string]: any } = {}

local function ExecuteLifecyclePhase(ScopeName: string, LifecycleUnits: { LifecycleUnit }, PhaseName: string, Context: any)
	local progress = ScopeBootProgress[ScopeName]
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			if progress then
				progress.CurrentModuleName = Unit.Name
				progress.CurrentPhaseName = PhaseName
			end

			debug.profilebegin(ScopeName .. ":" .. Unit.Name .. ":" .. PhaseName)
			if PhaseName == "Start" then
				-- Asynchronous Start dispatch ensures services initialize without thread blocking
				task.spawn(function()
					local success, err = pcall(function()
						Loaded[PhaseName](Context)
					end)
					if not success then
						warn(string.format("[ModuleLoader] Error during asynchronous %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
					end
				end)
			else
				local success, err = pcall(function()
					Loaded[PhaseName](Context)
				end)
				if not success then
					error(string.format("[ModuleLoader] Error during %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
				end
			end
			debug.profileend()

			if progress then
				progress.CompletedStepCount += 1
				progress.Percent = CalculateScopeBootPercent(progress.CompletedStepCount, progress.TotalStepCount)
			end
		end
	end
end

-- Resolve module instance from a dot-delimited path
local function ResolveModuleInstance(scope: string, path: string): ModuleScript?
	local current: Instance? = nil

	if scope == "Shared" or path:match("^Packages%.") or path:match("^SharedModules%.") then
		current = ReplicatedStorage
	elseif scope == "Server" or path:match("^ServerModules%.") then
		local sss = game:GetService("ServerScriptService")
		current = sss
	else
		current = ReplicatedStorage
	end

	local parts = string.split(path, ".")
	for _, part in ipairs(parts) do
		if not current then return nil end
		current = current:FindFirstChild(part)
	end

	if current and current:IsA("ModuleScript") then
		return current :: ModuleScript
	end
	return nil
end

function ModuleLoader.Register(name: string, module: any)
	ModuleCache[name] = module
	local simpleName = name:match("([^%.]+)--!strict
-- [ProductionCore / Shared / ModuleLoader.luau]
-- Core bootstrap lifecycle engine: Handles phased Init/Start, client pacing, and dependency resolution

local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local ModuleLoader = {}
local ModuleCache: { [string]: any } = {}
local ScopeBootStateByName = { Shared = false, Server = false, Client = false }

export type LifecycleUnit = {
	Name: string,
	Loaded: any,
	Priority: number,
}

local function CreateScopeBootProgressState(ScopeName: string)
	return {
		ScopeName = ScopeName,
		CurrentModuleName = "Preparing",
		CurrentPhaseName = "Boot",
		CurrentModulePercent = 0,
		CompletedStepCount = 0,
		TotalStepCount = 0,
		Percent = 0,
		IsComplete = false,
	}
end

local function CalculateScopeBootPercent(CompletedStepCount: number, TotalStepCount: number): number
	if TotalStepCount <= 0 then return 100 end
	local RawPercent = (CompletedStepCount / TotalStepCount) * 100
	return math.clamp(math.floor(RawPercent + 0.5), 0, 100)
end

local function CountLifecyclePhaseSteps(LifecycleUnits: { LifecycleUnit }, PhaseName: string): number
	local Count = 0
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			Count += 1
		end
	end
	return Count
end

local ScopeBootProgress: { [string]: any } = {}

local function ExecuteLifecyclePhase(ScopeName: string, LifecycleUnits: { LifecycleUnit }, PhaseName: string, Context: any)
	local progress = ScopeBootProgress[ScopeName]
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			if progress then
				progress.CurrentModuleName = Unit.Name
				progress.CurrentPhaseName = PhaseName
			end

			debug.profilebegin(ScopeName .. ":" .. Unit.Name .. ":" .. PhaseName)
			if PhaseName == "Start" then
				-- Asynchronous Start dispatch ensures services initialize without thread blocking
				task.spawn(function()
					local success, err = pcall(function()
						Loaded[PhaseName](Context)
					end)
					if not success then
						warn(string.format("[ModuleLoader] Error during asynchronous %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
					end
				end)
			else
				local success, err = pcall(function()
					Loaded[PhaseName](Context)
				end)
				if not success then
					error(string.format("[ModuleLoader] Error during %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
				end
			end
			debug.profileend()

			if progress then
				progress.CompletedStepCount += 1
				progress.Percent = CalculateScopeBootPercent(progress.CompletedStepCount, progress.TotalStepCount)
			end
		end
	end
end

-- Resolve module instance from a dot-delimited path
local function ResolveModuleInstance(scope: string, path: string): ModuleScript?
	local current: Instance? = nil

	if scope == "Shared" or path:match("^Packages%.") or path:match("^SharedModules%.") then
		current = ReplicatedStorage
	elseif scope == "Server" or path:match("^ServerModules%.") then
		local sss = game:GetService("ServerScriptService")
		current = sss
	else
		current = ReplicatedStorage
	end

	local parts = string.split(path, ".")
	for _, part in ipairs(parts) do
		if not current then return nil end
		current = current:FindFirstChild(part)
	end

	if current and current:IsA("ModuleScript") then
		return current :: ModuleScript
	end
	return nil
end

function ModuleLoader.Register(name: string, module: any)
	ModuleCache[name] = module
	local simpleName = name:match("([^%.]+)--!strict
-- [ProductionCore / Shared / ModuleLoader.luau]
-- Core bootstrap lifecycle engine: Handles phased Init/Start, client pacing, and dependency resolution

local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local ModuleLoader = {}
local ModuleCache: { [string]: any } = {}
local ScopeBootStateByName = { Shared = false, Server = false, Client = false }

export type LifecycleUnit = {
	Name: string,
	Loaded: any,
	Priority: number,
}

local function CreateScopeBootProgressState(ScopeName: string)
	return {
		ScopeName = ScopeName,
		CurrentModuleName = "Preparing",
		CurrentPhaseName = "Boot",
		CurrentModulePercent = 0,
		CompletedStepCount = 0,
		TotalStepCount = 0,
		Percent = 0,
		IsComplete = false,
	}
end

local function CalculateScopeBootPercent(CompletedStepCount: number, TotalStepCount: number): number
	if TotalStepCount <= 0 then return 100 end
	local RawPercent = (CompletedStepCount / TotalStepCount) * 100
	return math.clamp(math.floor(RawPercent + 0.5), 0, 100)
end

local function CountLifecyclePhaseSteps(LifecycleUnits: { LifecycleUnit }, PhaseName: string): number
	local Count = 0
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			Count += 1
		end
	end
	return Count
end

local function ExecuteLifecyclePhase(ScopeName: string, LifecycleUnits: { LifecycleUnit }, PhaseName: string, Context: any)
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			debug.profilebegin(ScopeName .. ":" .. Unit.Name .. ":" .. PhaseName)
			local success, err = pcall(function()
				Loaded[PhaseName](Context)
			end)
			debug.profileend()
			if not success then
				error(string.format("[ModuleLoader] Error during %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
			end
		end
	end
end

-- Resolve module instance from a dot-delimited path
local function ResolveModuleInstance(scope: string, path: string): ModuleScript?
	local current: Instance? = nil

	if scope == "Shared" or path:match("^Packages%.") or path:match("^SharedModules%.") then
		current = ReplicatedStorage
	elseif scope == "Server" or path:match("^ServerModules%.") then
		local sss = game:GetService("ServerScriptService")
		current = sss
	else
		current = ReplicatedStorage
	end

	local parts = string.split(path, ".")
	for _, part in ipairs(parts) do
		if not current then return nil end
		current = current:FindFirstChild(part)
	end

	if current and current:IsA("ModuleScript") then
		return current :: ModuleScript
	end
	return nil
end

function ModuleLoader.Register(name: string, module: any)
	ModuleCache[name] = module
end

function ModuleLoader.Require(scope: string, path: string): any
	local cacheKey = scope .. ":" .. path
	if ModuleCache[cacheKey] ~= nil then
		return ModuleCache[cacheKey]
	end
	if ModuleCache[path] ~= nil then
		return ModuleCache[path]
	end

	local inst = ResolveModuleInstance(scope, path)
	if inst then
		local loaded = require(inst)
		ModuleCache[cacheKey] = loaded
		ModuleCache[path] = loaded
		return loaded
	end

	-- Check fallback in cache under simple name
	local simpleName = path:match("([^%.]+)$") or path
	if ModuleCache[simpleName] ~= nil then
		return ModuleCache[simpleName]
	end

	error(string.format("[ModuleLoader] Could not resolve module '%s' in scope '%s'", path, scope))
end

function ModuleLoader.RequireShared(path: string): any
	return ModuleLoader.Require("Shared", path)
end

function ModuleLoader.RequireScoped(path: string): any
	local isServer = RunService:IsServer()
	local scope = if isServer then "Server" else "Client"
	return ModuleLoader.Require(scope, path)
end

function ModuleLoader.Boot(scopeName: string, container: Instance)
	local units: { LifecycleUnit } = {}

	for _, descendant in ipairs(container:GetDescendants()) do
		if descendant:IsA("ModuleScript") then
			local success, loaded = pcall(require, descendant)
			if success then
				local priority = 10
				if type(loaded) == "table" and type(loaded.Metadata) == "table" and type(loaded.Metadata.Priority) == "number" then
					priority = loaded.Metadata.Priority
				end
				table.insert(units, {
					Name = descendant.Name,
					Loaded = loaded,
					Priority = priority,
				})
				ModuleCache[descendant.Name] = loaded
			else
				warn(string.format("[ModuleLoader] Failed to require %s: %s", descendant:GetFullName(), tostring(loaded)))
			end
		end
	end

	-- Sort by Priority descending (higher priority inits first)
	table.sort(units, function(a, b)
		return a.Priority > b.Priority
	end)

	local context = {
		ModuleLoader = ModuleLoader,
	}

	-- Phase 1: Synchronous Init
	ExecuteLifecyclePhase(scopeName, units, "Init", context)

	-- Phase 2: Asynchronous Start
	ExecuteLifecyclePhase(scopeName, units, "Start", context)

	ScopeBootStateByName[scopeName] = true
	print(string.format("[ModuleLoader] Scope '%s' boot completed (%d modules).", scopeName, #units))
end

return ModuleLoaderquot;) or path
	if ModuleCache[simpleName] ~= nil then
		return ModuleCache[simpleName]
	end

	error(string.format("[ModuleLoader] Could not resolve module '%s' in scope '%s'", path, scope))
end

function ModuleLoader.RequireShared(path: string): any
	return ModuleLoader.Require("Shared", path)
end

function ModuleLoader.RequireScoped(path: string): any
	local isServer = RunService:IsServer()
	local scope = if isServer then "Server" else "Client"
	return ModuleLoader.Require(scope, path)
end

function ModuleLoader.Boot(scopeName: string, container: Instance)
	local units: { LifecycleUnit } = {}

	for _, descendant in ipairs(container:GetDescendants()) do
		if descendant:IsA("ModuleScript") then
			local success, loaded
			if (descendant :: any)._module ~= nil then
				success, loaded = true, (descendant :: any)._module
			else
				success, loaded = pcall(require, descendant)
			end
			if success then
				local priority = 10
				if type(loaded) == "table" and type(loaded.Metadata) == "table" and type(loaded.Metadata.Priority) == "number" then
					priority = loaded.Metadata.Priority
				end
				table.insert(units, {
					Name = descendant.Name,
					Loaded = loaded,
					Priority = priority,
				})
				ModuleCache[descendant.Name] = loaded
			else
				warn(string.format("[ModuleLoader] Failed to require %s: %s", descendant:GetFullName(), tostring(loaded)))
			end
		end
	end

	-- Sort by Priority descending (higher priority inits first)
	table.sort(units, function(a, b)
		return a.Priority > b.Priority
	end)

	local totalSteps = CountLifecyclePhaseSteps(units, "Init") + CountLifecyclePhaseSteps(units, "Start")
	local progress = CreateScopeBootProgressState(scopeName)
	progress.TotalStepCount = totalSteps
	ScopeBootProgress[scopeName] = progress

	local context = {
		ModuleLoader = ModuleLoader,
	}

	-- Phase 1: Synchronous Init
	ExecuteLifecyclePhase(scopeName, units, "Init", context)

	-- Phase 2: Asynchronous Start
	ExecuteLifecyclePhase(scopeName, units, "Start", context)

	progress.IsComplete = true
	progress.Percent = 100
	ScopeBootStateByName[scopeName] = true
	print(string.format("[ModuleLoader] Scope '%s' boot completed (%d modules).", scopeName, #units))
end

return ModuleLoader
quot;)
	if simpleName and ModuleCache[simpleName] == nil then
		ModuleCache[simpleName] = module
	end
end

function ModuleLoader.GetBootProgress(scopeName: string): any?
	return ScopeBootProgress[scopeName]
end

function ModuleLoader.Require(scope: string, path: string): any
	local cacheKey = scope .. ":" .. path
	if ModuleCache[cacheKey] ~= nil then
		return ModuleCache[cacheKey]
	end
	if ModuleCache[path] ~= nil then
		return ModuleCache[path]
	end

	local inst = ResolveModuleInstance(scope, path)
	if inst then
		local loaded = require(inst)
		ModuleCache[cacheKey] = loaded
		ModuleCache[path] = loaded
		return loaded
	end

	-- Check fallback in cache under simple name
	local simpleName = path:match("([^%.]+)--!strict
-- [ProductionCore / Shared / ModuleLoader.luau]
-- Core bootstrap lifecycle engine: Handles phased Init/Start, client pacing, and dependency resolution

local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local ModuleLoader = {}
local ModuleCache: { [string]: any } = {}
local ScopeBootStateByName = { Shared = false, Server = false, Client = false }

export type LifecycleUnit = {
	Name: string,
	Loaded: any,
	Priority: number,
}

local function CreateScopeBootProgressState(ScopeName: string)
	return {
		ScopeName = ScopeName,
		CurrentModuleName = "Preparing",
		CurrentPhaseName = "Boot",
		CurrentModulePercent = 0,
		CompletedStepCount = 0,
		TotalStepCount = 0,
		Percent = 0,
		IsComplete = false,
	}
end

local function CalculateScopeBootPercent(CompletedStepCount: number, TotalStepCount: number): number
	if TotalStepCount <= 0 then return 100 end
	local RawPercent = (CompletedStepCount / TotalStepCount) * 100
	return math.clamp(math.floor(RawPercent + 0.5), 0, 100)
end

local function CountLifecyclePhaseSteps(LifecycleUnits: { LifecycleUnit }, PhaseName: string): number
	local Count = 0
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			Count += 1
		end
	end
	return Count
end

local ScopeBootProgress: { [string]: any } = {}

local function ExecuteLifecyclePhase(ScopeName: string, LifecycleUnits: { LifecycleUnit }, PhaseName: string, Context: any)
	local progress = ScopeBootProgress[ScopeName]
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			if progress then
				progress.CurrentModuleName = Unit.Name
				progress.CurrentPhaseName = PhaseName
			end

			debug.profilebegin(ScopeName .. ":" .. Unit.Name .. ":" .. PhaseName)
			if PhaseName == "Start" then
				-- Asynchronous Start dispatch ensures services initialize without thread blocking
				task.spawn(function()
					local success, err = pcall(function()
						Loaded[PhaseName](Context)
					end)
					if not success then
						warn(string.format("[ModuleLoader] Error during asynchronous %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
					end
				end)
			else
				local success, err = pcall(function()
					Loaded[PhaseName](Context)
				end)
				if not success then
					error(string.format("[ModuleLoader] Error during %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
				end
			end
			debug.profileend()

			if progress then
				progress.CompletedStepCount += 1
				progress.Percent = CalculateScopeBootPercent(progress.CompletedStepCount, progress.TotalStepCount)
			end
		end
	end
end

-- Resolve module instance from a dot-delimited path
local function ResolveModuleInstance(scope: string, path: string): ModuleScript?
	local current: Instance? = nil

	if scope == "Shared" or path:match("^Packages%.") or path:match("^SharedModules%.") then
		current = ReplicatedStorage
	elseif scope == "Server" or path:match("^ServerModules%.") then
		local sss = game:GetService("ServerScriptService")
		current = sss
	else
		current = ReplicatedStorage
	end

	local parts = string.split(path, ".")
	for _, part in ipairs(parts) do
		if not current then return nil end
		current = current:FindFirstChild(part)
	end

	if current and current:IsA("ModuleScript") then
		return current :: ModuleScript
	end
	return nil
end

function ModuleLoader.Register(name: string, module: any)
	ModuleCache[name] = module
	local simpleName = name:match("([^%.]+)--!strict
-- [ProductionCore / Shared / ModuleLoader.luau]
-- Core bootstrap lifecycle engine: Handles phased Init/Start, client pacing, and dependency resolution

local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local ModuleLoader = {}
local ModuleCache: { [string]: any } = {}
local ScopeBootStateByName = { Shared = false, Server = false, Client = false }

export type LifecycleUnit = {
	Name: string,
	Loaded: any,
	Priority: number,
}

local function CreateScopeBootProgressState(ScopeName: string)
	return {
		ScopeName = ScopeName,
		CurrentModuleName = "Preparing",
		CurrentPhaseName = "Boot",
		CurrentModulePercent = 0,
		CompletedStepCount = 0,
		TotalStepCount = 0,
		Percent = 0,
		IsComplete = false,
	}
end

local function CalculateScopeBootPercent(CompletedStepCount: number, TotalStepCount: number): number
	if TotalStepCount <= 0 then return 100 end
	local RawPercent = (CompletedStepCount / TotalStepCount) * 100
	return math.clamp(math.floor(RawPercent + 0.5), 0, 100)
end

local function CountLifecyclePhaseSteps(LifecycleUnits: { LifecycleUnit }, PhaseName: string): number
	local Count = 0
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			Count += 1
		end
	end
	return Count
end

local ScopeBootProgress: { [string]: any } = {}

local function ExecuteLifecyclePhase(ScopeName: string, LifecycleUnits: { LifecycleUnit }, PhaseName: string, Context: any)
	local progress = ScopeBootProgress[ScopeName]
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			if progress then
				progress.CurrentModuleName = Unit.Name
				progress.CurrentPhaseName = PhaseName
			end

			debug.profilebegin(ScopeName .. ":" .. Unit.Name .. ":" .. PhaseName)
			if PhaseName == "Start" then
				-- Asynchronous Start dispatch ensures services initialize without thread blocking
				task.spawn(function()
					local success, err = pcall(function()
						Loaded[PhaseName](Context)
					end)
					if not success then
						warn(string.format("[ModuleLoader] Error during asynchronous %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
					end
				end)
			else
				local success, err = pcall(function()
					Loaded[PhaseName](Context)
				end)
				if not success then
					error(string.format("[ModuleLoader] Error during %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
				end
			end
			debug.profileend()

			if progress then
				progress.CompletedStepCount += 1
				progress.Percent = CalculateScopeBootPercent(progress.CompletedStepCount, progress.TotalStepCount)
			end
		end
	end
end

-- Resolve module instance from a dot-delimited path
local function ResolveModuleInstance(scope: string, path: string): ModuleScript?
	local current: Instance? = nil

	if scope == "Shared" or path:match("^Packages%.") or path:match("^SharedModules%.") then
		current = ReplicatedStorage
	elseif scope == "Server" or path:match("^ServerModules%.") then
		local sss = game:GetService("ServerScriptService")
		current = sss
	else
		current = ReplicatedStorage
	end

	local parts = string.split(path, ".")
	for _, part in ipairs(parts) do
		if not current then return nil end
		current = current:FindFirstChild(part)
	end

	if current and current:IsA("ModuleScript") then
		return current :: ModuleScript
	end
	return nil
end

function ModuleLoader.Register(name: string, module: any)
	ModuleCache[name] = module
	local simpleName = name:match("([^%.]+)--!strict
-- [ProductionCore / Shared / ModuleLoader.luau]
-- Core bootstrap lifecycle engine: Handles phased Init/Start, client pacing, and dependency resolution

local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local ModuleLoader = {}
local ModuleCache: { [string]: any } = {}
local ScopeBootStateByName = { Shared = false, Server = false, Client = false }

export type LifecycleUnit = {
	Name: string,
	Loaded: any,
	Priority: number,
}

local function CreateScopeBootProgressState(ScopeName: string)
	return {
		ScopeName = ScopeName,
		CurrentModuleName = "Preparing",
		CurrentPhaseName = "Boot",
		CurrentModulePercent = 0,
		CompletedStepCount = 0,
		TotalStepCount = 0,
		Percent = 0,
		IsComplete = false,
	}
end

local function CalculateScopeBootPercent(CompletedStepCount: number, TotalStepCount: number): number
	if TotalStepCount <= 0 then return 100 end
	local RawPercent = (CompletedStepCount / TotalStepCount) * 100
	return math.clamp(math.floor(RawPercent + 0.5), 0, 100)
end

local function CountLifecyclePhaseSteps(LifecycleUnits: { LifecycleUnit }, PhaseName: string): number
	local Count = 0
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			Count += 1
		end
	end
	return Count
end

local ScopeBootProgress: { [string]: any } = {}

local function ExecuteLifecyclePhase(ScopeName: string, LifecycleUnits: { LifecycleUnit }, PhaseName: string, Context: any)
	local progress = ScopeBootProgress[ScopeName]
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			if progress then
				progress.CurrentModuleName = Unit.Name
				progress.CurrentPhaseName = PhaseName
			end

			debug.profilebegin(ScopeName .. ":" .. Unit.Name .. ":" .. PhaseName)
			if PhaseName == "Start" then
				-- Asynchronous Start dispatch ensures services initialize without thread blocking
				task.spawn(function()
					local success, err = pcall(function()
						Loaded[PhaseName](Context)
					end)
					if not success then
						warn(string.format("[ModuleLoader] Error during asynchronous %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
					end
				end)
			else
				local success, err = pcall(function()
					Loaded[PhaseName](Context)
				end)
				if not success then
					error(string.format("[ModuleLoader] Error during %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
				end
			end
			debug.profileend()

			if progress then
				progress.CompletedStepCount += 1
				progress.Percent = CalculateScopeBootPercent(progress.CompletedStepCount, progress.TotalStepCount)
			end
		end
	end
end

-- Resolve module instance from a dot-delimited path
local function ResolveModuleInstance(scope: string, path: string): ModuleScript?
	local current: Instance? = nil

	if scope == "Shared" or path:match("^Packages%.") or path:match("^SharedModules%.") then
		current = ReplicatedStorage
	elseif scope == "Server" or path:match("^ServerModules%.") then
		local sss = game:GetService("ServerScriptService")
		current = sss
	else
		current = ReplicatedStorage
	end

	local parts = string.split(path, ".")
	for _, part in ipairs(parts) do
		if not current then return nil end
		current = current:FindFirstChild(part)
	end

	if current and current:IsA("ModuleScript") then
		return current :: ModuleScript
	end
	return nil
end

function ModuleLoader.Register(name: string, module: any)
	ModuleCache[name] = module
	local simpleName = name:match("([^%.]+)--!strict
-- [ProductionCore / Shared / ModuleLoader.luau]
-- Core bootstrap lifecycle engine: Handles phased Init/Start, client pacing, and dependency resolution

local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local ModuleLoader = {}
local ModuleCache: { [string]: any } = {}
local ScopeBootStateByName = { Shared = false, Server = false, Client = false }

export type LifecycleUnit = {
	Name: string,
	Loaded: any,
	Priority: number,
}

local function CreateScopeBootProgressState(ScopeName: string)
	return {
		ScopeName = ScopeName,
		CurrentModuleName = "Preparing",
		CurrentPhaseName = "Boot",
		CurrentModulePercent = 0,
		CompletedStepCount = 0,
		TotalStepCount = 0,
		Percent = 0,
		IsComplete = false,
	}
end

local function CalculateScopeBootPercent(CompletedStepCount: number, TotalStepCount: number): number
	if TotalStepCount <= 0 then return 100 end
	local RawPercent = (CompletedStepCount / TotalStepCount) * 100
	return math.clamp(math.floor(RawPercent + 0.5), 0, 100)
end

local function CountLifecyclePhaseSteps(LifecycleUnits: { LifecycleUnit }, PhaseName: string): number
	local Count = 0
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			Count += 1
		end
	end
	return Count
end

local ScopeBootProgress: { [string]: any } = {}

local function ExecuteLifecyclePhase(ScopeName: string, LifecycleUnits: { LifecycleUnit }, PhaseName: string, Context: any)
	local progress = ScopeBootProgress[ScopeName]
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			if progress then
				progress.CurrentModuleName = Unit.Name
				progress.CurrentPhaseName = PhaseName
			end

			debug.profilebegin(ScopeName .. ":" .. Unit.Name .. ":" .. PhaseName)
			if PhaseName == "Start" then
				-- Asynchronous Start dispatch ensures services initialize without thread blocking
				task.spawn(function()
					local success, err = pcall(function()
						Loaded[PhaseName](Context)
					end)
					if not success then
						warn(string.format("[ModuleLoader] Error during asynchronous %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
					end
				end)
			else
				local success, err = pcall(function()
					Loaded[PhaseName](Context)
				end)
				if not success then
					error(string.format("[ModuleLoader] Error during %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
				end
			end
			debug.profileend()

			if progress then
				progress.CompletedStepCount += 1
				progress.Percent = CalculateScopeBootPercent(progress.CompletedStepCount, progress.TotalStepCount)
			end
		end
	end
end

-- Resolve module instance from a dot-delimited path
local function ResolveModuleInstance(scope: string, path: string): ModuleScript?
	local current: Instance? = nil

	if scope == "Shared" or path:match("^Packages%.") or path:match("^SharedModules%.") then
		current = ReplicatedStorage
	elseif scope == "Server" or path:match("^ServerModules%.") then
		local sss = game:GetService("ServerScriptService")
		current = sss
	else
		current = ReplicatedStorage
	end

	local parts = string.split(path, ".")
	for _, part in ipairs(parts) do
		if not current then return nil end
		current = current:FindFirstChild(part)
	end

	if current and current:IsA("ModuleScript") then
		return current :: ModuleScript
	end
	return nil
end

function ModuleLoader.Register(name: string, module: any)
	ModuleCache[name] = module
	local simpleName = name:match("([^%.]+)--!strict
-- [ProductionCore / Shared / ModuleLoader.luau]
-- Core bootstrap lifecycle engine: Handles phased Init/Start, client pacing, and dependency resolution

local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local ModuleLoader = {}
local ModuleCache: { [string]: any } = {}
local ScopeBootStateByName = { Shared = false, Server = false, Client = false }

export type LifecycleUnit = {
	Name: string,
	Loaded: any,
	Priority: number,
}

local function CreateScopeBootProgressState(ScopeName: string)
	return {
		ScopeName = ScopeName,
		CurrentModuleName = "Preparing",
		CurrentPhaseName = "Boot",
		CurrentModulePercent = 0,
		CompletedStepCount = 0,
		TotalStepCount = 0,
		Percent = 0,
		IsComplete = false,
	}
end

local function CalculateScopeBootPercent(CompletedStepCount: number, TotalStepCount: number): number
	if TotalStepCount <= 0 then return 100 end
	local RawPercent = (CompletedStepCount / TotalStepCount) * 100
	return math.clamp(math.floor(RawPercent + 0.5), 0, 100)
end

local function CountLifecyclePhaseSteps(LifecycleUnits: { LifecycleUnit }, PhaseName: string): number
	local Count = 0
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			Count += 1
		end
	end
	return Count
end

local ScopeBootProgress: { [string]: any } = {}

local function ExecuteLifecyclePhase(ScopeName: string, LifecycleUnits: { LifecycleUnit }, PhaseName: string, Context: any)
	local progress = ScopeBootProgress[ScopeName]
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			if progress then
				progress.CurrentModuleName = Unit.Name
				progress.CurrentPhaseName = PhaseName
			end

			debug.profilebegin(ScopeName .. ":" .. Unit.Name .. ":" .. PhaseName)
			if PhaseName == "Start" then
				-- Asynchronous Start dispatch ensures services initialize without thread blocking
				task.spawn(function()
					local success, err = pcall(function()
						Loaded[PhaseName](Context)
					end)
					if not success then
						warn(string.format("[ModuleLoader] Error during asynchronous %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
					end
				end)
			else
				local success, err = pcall(function()
					Loaded[PhaseName](Context)
				end)
				if not success then
					error(string.format("[ModuleLoader] Error during %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
				end
			end
			debug.profileend()

			if progress then
				progress.CompletedStepCount += 1
				progress.Percent = CalculateScopeBootPercent(progress.CompletedStepCount, progress.TotalStepCount)
			end
		end
	end
end

-- Resolve module instance from a dot-delimited path
local function ResolveModuleInstance(scope: string, path: string): ModuleScript?
	local current: Instance? = nil

	if scope == "Shared" or path:match("^Packages%.") or path:match("^SharedModules%.") then
		current = ReplicatedStorage
	elseif scope == "Server" or path:match("^ServerModules%.") then
		local sss = game:GetService("ServerScriptService")
		current = sss
	else
		current = ReplicatedStorage
	end

	local parts = string.split(path, ".")
	for _, part in ipairs(parts) do
		if not current then return nil end
		current = current:FindFirstChild(part)
	end

	if current and current:IsA("ModuleScript") then
		return current :: ModuleScript
	end
	return nil
end

function ModuleLoader.Register(name: string, module: any)
	ModuleCache[name] = module
	local simpleName = name:match("([^%.]+)--!strict
-- [ProductionCore / Shared / ModuleLoader.luau]
-- Core bootstrap lifecycle engine: Handles phased Init/Start, client pacing, and dependency resolution

local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local ModuleLoader = {}
local ModuleCache: { [string]: any } = {}
local ScopeBootStateByName = { Shared = false, Server = false, Client = false }

export type LifecycleUnit = {
	Name: string,
	Loaded: any,
	Priority: number,
}

local function CreateScopeBootProgressState(ScopeName: string)
	return {
		ScopeName = ScopeName,
		CurrentModuleName = "Preparing",
		CurrentPhaseName = "Boot",
		CurrentModulePercent = 0,
		CompletedStepCount = 0,
		TotalStepCount = 0,
		Percent = 0,
		IsComplete = false,
	}
end

local function CalculateScopeBootPercent(CompletedStepCount: number, TotalStepCount: number): number
	if TotalStepCount <= 0 then return 100 end
	local RawPercent = (CompletedStepCount / TotalStepCount) * 100
	return math.clamp(math.floor(RawPercent + 0.5), 0, 100)
end

local function CountLifecyclePhaseSteps(LifecycleUnits: { LifecycleUnit }, PhaseName: string): number
	local Count = 0
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			Count += 1
		end
	end
	return Count
end

local function ExecuteLifecyclePhase(ScopeName: string, LifecycleUnits: { LifecycleUnit }, PhaseName: string, Context: any)
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			debug.profilebegin(ScopeName .. ":" .. Unit.Name .. ":" .. PhaseName)
			local success, err = pcall(function()
				Loaded[PhaseName](Context)
			end)
			debug.profileend()
			if not success then
				error(string.format("[ModuleLoader] Error during %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
			end
		end
	end
end

-- Resolve module instance from a dot-delimited path
local function ResolveModuleInstance(scope: string, path: string): ModuleScript?
	local current: Instance? = nil

	if scope == "Shared" or path:match("^Packages%.") or path:match("^SharedModules%.") then
		current = ReplicatedStorage
	elseif scope == "Server" or path:match("^ServerModules%.") then
		local sss = game:GetService("ServerScriptService")
		current = sss
	else
		current = ReplicatedStorage
	end

	local parts = string.split(path, ".")
	for _, part in ipairs(parts) do
		if not current then return nil end
		current = current:FindFirstChild(part)
	end

	if current and current:IsA("ModuleScript") then
		return current :: ModuleScript
	end
	return nil
end

function ModuleLoader.Register(name: string, module: any)
	ModuleCache[name] = module
end

function ModuleLoader.Require(scope: string, path: string): any
	local cacheKey = scope .. ":" .. path
	if ModuleCache[cacheKey] ~= nil then
		return ModuleCache[cacheKey]
	end
	if ModuleCache[path] ~= nil then
		return ModuleCache[path]
	end

	local inst = ResolveModuleInstance(scope, path)
	if inst then
		local loaded = require(inst)
		ModuleCache[cacheKey] = loaded
		ModuleCache[path] = loaded
		return loaded
	end

	-- Check fallback in cache under simple name
	local simpleName = path:match("([^%.]+)$") or path
	if ModuleCache[simpleName] ~= nil then
		return ModuleCache[simpleName]
	end

	error(string.format("[ModuleLoader] Could not resolve module '%s' in scope '%s'", path, scope))
end

function ModuleLoader.RequireShared(path: string): any
	return ModuleLoader.Require("Shared", path)
end

function ModuleLoader.RequireScoped(path: string): any
	local isServer = RunService:IsServer()
	local scope = if isServer then "Server" else "Client"
	return ModuleLoader.Require(scope, path)
end

function ModuleLoader.Boot(scopeName: string, container: Instance)
	local units: { LifecycleUnit } = {}

	for _, descendant in ipairs(container:GetDescendants()) do
		if descendant:IsA("ModuleScript") then
			local success, loaded = pcall(require, descendant)
			if success then
				local priority = 10
				if type(loaded) == "table" and type(loaded.Metadata) == "table" and type(loaded.Metadata.Priority) == "number" then
					priority = loaded.Metadata.Priority
				end
				table.insert(units, {
					Name = descendant.Name,
					Loaded = loaded,
					Priority = priority,
				})
				ModuleCache[descendant.Name] = loaded
			else
				warn(string.format("[ModuleLoader] Failed to require %s: %s", descendant:GetFullName(), tostring(loaded)))
			end
		end
	end

	-- Sort by Priority descending (higher priority inits first)
	table.sort(units, function(a, b)
		return a.Priority > b.Priority
	end)

	local context = {
		ModuleLoader = ModuleLoader,
	}

	-- Phase 1: Synchronous Init
	ExecuteLifecyclePhase(scopeName, units, "Init", context)

	-- Phase 2: Asynchronous Start
	ExecuteLifecyclePhase(scopeName, units, "Start", context)

	ScopeBootStateByName[scopeName] = true
	print(string.format("[ModuleLoader] Scope '%s' boot completed (%d modules).", scopeName, #units))
end

return ModuleLoaderquot;) or path
	if ModuleCache[simpleName] ~= nil then
		return ModuleCache[simpleName]
	end

	error(string.format("[ModuleLoader] Could not resolve module '%s' in scope '%s'", path, scope))
end

function ModuleLoader.RequireShared(path: string): any
	return ModuleLoader.Require("Shared", path)
end

function ModuleLoader.RequireScoped(path: string): any
	local isServer = RunService:IsServer()
	local scope = if isServer then "Server" else "Client"
	return ModuleLoader.Require(scope, path)
end

function ModuleLoader.Boot(scopeName: string, container: Instance)
	local units: { LifecycleUnit } = {}

	for _, descendant in ipairs(container:GetDescendants()) do
		if descendant:IsA("ModuleScript") then
			local success, loaded
			if (descendant :: any)._module ~= nil then
				success, loaded = true, (descendant :: any)._module
			else
				success, loaded = pcall(require, descendant)
			end
			if success then
				local priority = 10
				if type(loaded) == "table" and type(loaded.Metadata) == "table" and type(loaded.Metadata.Priority) == "number" then
					priority = loaded.Metadata.Priority
				end
				table.insert(units, {
					Name = descendant.Name,
					Loaded = loaded,
					Priority = priority,
				})
				ModuleCache[descendant.Name] = loaded
			else
				warn(string.format("[ModuleLoader] Failed to require %s: %s", descendant:GetFullName(), tostring(loaded)))
			end
		end
	end

	-- Sort by Priority descending (higher priority inits first)
	table.sort(units, function(a, b)
		return a.Priority > b.Priority
	end)

	local totalSteps = CountLifecyclePhaseSteps(units, "Init") + CountLifecyclePhaseSteps(units, "Start")
	local progress = CreateScopeBootProgressState(scopeName)
	progress.TotalStepCount = totalSteps
	ScopeBootProgress[scopeName] = progress

	local context = {
		ModuleLoader = ModuleLoader,
	}

	-- Phase 1: Synchronous Init
	ExecuteLifecyclePhase(scopeName, units, "Init", context)

	-- Phase 2: Asynchronous Start
	ExecuteLifecyclePhase(scopeName, units, "Start", context)

	progress.IsComplete = true
	progress.Percent = 100
	ScopeBootStateByName[scopeName] = true
	print(string.format("[ModuleLoader] Scope '%s' boot completed (%d modules).", scopeName, #units))
end

return ModuleLoader
quot;)
	if simpleName and ModuleCache[simpleName] == nil then
		ModuleCache[simpleName] = module
	end
end

function ModuleLoader.GetBootProgress(scopeName: string): any?
	return ScopeBootProgress[scopeName]
end

function ModuleLoader.Require(scope: string, path: string): any
	local cacheKey = scope .. ":" .. path
	if ModuleCache[cacheKey] ~= nil then
		return ModuleCache[cacheKey]
	end
	if ModuleCache[path] ~= nil then
		return ModuleCache[path]
	end

	local inst = ResolveModuleInstance(scope, path)
	if inst then
		local loaded = require(inst)
		ModuleCache[cacheKey] = loaded
		ModuleCache[path] = loaded
		return loaded
	end

	-- Check fallback in cache under simple name
	local simpleName = path:match("([^%.]+)--!strict
-- [ProductionCore / Shared / ModuleLoader.luau]
-- Core bootstrap lifecycle engine: Handles phased Init/Start, client pacing, and dependency resolution

local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local ModuleLoader = {}
local ModuleCache: { [string]: any } = {}
local ScopeBootStateByName = { Shared = false, Server = false, Client = false }

export type LifecycleUnit = {
	Name: string,
	Loaded: any,
	Priority: number,
}

local function CreateScopeBootProgressState(ScopeName: string)
	return {
		ScopeName = ScopeName,
		CurrentModuleName = "Preparing",
		CurrentPhaseName = "Boot",
		CurrentModulePercent = 0,
		CompletedStepCount = 0,
		TotalStepCount = 0,
		Percent = 0,
		IsComplete = false,
	}
end

local function CalculateScopeBootPercent(CompletedStepCount: number, TotalStepCount: number): number
	if TotalStepCount <= 0 then return 100 end
	local RawPercent = (CompletedStepCount / TotalStepCount) * 100
	return math.clamp(math.floor(RawPercent + 0.5), 0, 100)
end

local function CountLifecyclePhaseSteps(LifecycleUnits: { LifecycleUnit }, PhaseName: string): number
	local Count = 0
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			Count += 1
		end
	end
	return Count
end

local ScopeBootProgress: { [string]: any } = {}

local function ExecuteLifecyclePhase(ScopeName: string, LifecycleUnits: { LifecycleUnit }, PhaseName: string, Context: any)
	local progress = ScopeBootProgress[ScopeName]
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			if progress then
				progress.CurrentModuleName = Unit.Name
				progress.CurrentPhaseName = PhaseName
			end

			debug.profilebegin(ScopeName .. ":" .. Unit.Name .. ":" .. PhaseName)
			if PhaseName == "Start" then
				-- Asynchronous Start dispatch ensures services initialize without thread blocking
				task.spawn(function()
					local success, err = pcall(function()
						Loaded[PhaseName](Context)
					end)
					if not success then
						warn(string.format("[ModuleLoader] Error during asynchronous %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
					end
				end)
			else
				local success, err = pcall(function()
					Loaded[PhaseName](Context)
				end)
				if not success then
					error(string.format("[ModuleLoader] Error during %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
				end
			end
			debug.profileend()

			if progress then
				progress.CompletedStepCount += 1
				progress.Percent = CalculateScopeBootPercent(progress.CompletedStepCount, progress.TotalStepCount)
			end
		end
	end
end

-- Resolve module instance from a dot-delimited path
local function ResolveModuleInstance(scope: string, path: string): ModuleScript?
	local current: Instance? = nil

	if scope == "Shared" or path:match("^Packages%.") or path:match("^SharedModules%.") then
		current = ReplicatedStorage
	elseif scope == "Server" or path:match("^ServerModules%.") then
		local sss = game:GetService("ServerScriptService")
		current = sss
	else
		current = ReplicatedStorage
	end

	local parts = string.split(path, ".")
	for _, part in ipairs(parts) do
		if not current then return nil end
		current = current:FindFirstChild(part)
	end

	if current and current:IsA("ModuleScript") then
		return current :: ModuleScript
	end
	return nil
end

function ModuleLoader.Register(name: string, module: any)
	ModuleCache[name] = module
	local simpleName = name:match("([^%.]+)--!strict
-- [ProductionCore / Shared / ModuleLoader.luau]
-- Core bootstrap lifecycle engine: Handles phased Init/Start, client pacing, and dependency resolution

local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local ModuleLoader = {}
local ModuleCache: { [string]: any } = {}
local ScopeBootStateByName = { Shared = false, Server = false, Client = false }

export type LifecycleUnit = {
	Name: string,
	Loaded: any,
	Priority: number,
}

local function CreateScopeBootProgressState(ScopeName: string)
	return {
		ScopeName = ScopeName,
		CurrentModuleName = "Preparing",
		CurrentPhaseName = "Boot",
		CurrentModulePercent = 0,
		CompletedStepCount = 0,
		TotalStepCount = 0,
		Percent = 0,
		IsComplete = false,
	}
end

local function CalculateScopeBootPercent(CompletedStepCount: number, TotalStepCount: number): number
	if TotalStepCount <= 0 then return 100 end
	local RawPercent = (CompletedStepCount / TotalStepCount) * 100
	return math.clamp(math.floor(RawPercent + 0.5), 0, 100)
end

local function CountLifecyclePhaseSteps(LifecycleUnits: { LifecycleUnit }, PhaseName: string): number
	local Count = 0
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			Count += 1
		end
	end
	return Count
end

local ScopeBootProgress: { [string]: any } = {}

local function ExecuteLifecyclePhase(ScopeName: string, LifecycleUnits: { LifecycleUnit }, PhaseName: string, Context: any)
	local progress = ScopeBootProgress[ScopeName]
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			if progress then
				progress.CurrentModuleName = Unit.Name
				progress.CurrentPhaseName = PhaseName
			end

			debug.profilebegin(ScopeName .. ":" .. Unit.Name .. ":" .. PhaseName)
			if PhaseName == "Start" then
				-- Asynchronous Start dispatch ensures services initialize without thread blocking
				task.spawn(function()
					local success, err = pcall(function()
						Loaded[PhaseName](Context)
					end)
					if not success then
						warn(string.format("[ModuleLoader] Error during asynchronous %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
					end
				end)
			else
				local success, err = pcall(function()
					Loaded[PhaseName](Context)
				end)
				if not success then
					error(string.format("[ModuleLoader] Error during %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
				end
			end
			debug.profileend()

			if progress then
				progress.CompletedStepCount += 1
				progress.Percent = CalculateScopeBootPercent(progress.CompletedStepCount, progress.TotalStepCount)
			end
		end
	end
end

-- Resolve module instance from a dot-delimited path
local function ResolveModuleInstance(scope: string, path: string): ModuleScript?
	local current: Instance? = nil

	if scope == "Shared" or path:match("^Packages%.") or path:match("^SharedModules%.") then
		current = ReplicatedStorage
	elseif scope == "Server" or path:match("^ServerModules%.") then
		local sss = game:GetService("ServerScriptService")
		current = sss
	else
		current = ReplicatedStorage
	end

	local parts = string.split(path, ".")
	for _, part in ipairs(parts) do
		if not current then return nil end
		current = current:FindFirstChild(part)
	end

	if current and current:IsA("ModuleScript") then
		return current :: ModuleScript
	end
	return nil
end

function ModuleLoader.Register(name: string, module: any)
	ModuleCache[name] = module
	local simpleName = name:match("([^%.]+)--!strict
-- [ProductionCore / Shared / ModuleLoader.luau]
-- Core bootstrap lifecycle engine: Handles phased Init/Start, client pacing, and dependency resolution

local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local ModuleLoader = {}
local ModuleCache: { [string]: any } = {}
local ScopeBootStateByName = { Shared = false, Server = false, Client = false }

export type LifecycleUnit = {
	Name: string,
	Loaded: any,
	Priority: number,
}

local function CreateScopeBootProgressState(ScopeName: string)
	return {
		ScopeName = ScopeName,
		CurrentModuleName = "Preparing",
		CurrentPhaseName = "Boot",
		CurrentModulePercent = 0,
		CompletedStepCount = 0,
		TotalStepCount = 0,
		Percent = 0,
		IsComplete = false,
	}
end

local function CalculateScopeBootPercent(CompletedStepCount: number, TotalStepCount: number): number
	if TotalStepCount <= 0 then return 100 end
	local RawPercent = (CompletedStepCount / TotalStepCount) * 100
	return math.clamp(math.floor(RawPercent + 0.5), 0, 100)
end

local function CountLifecyclePhaseSteps(LifecycleUnits: { LifecycleUnit }, PhaseName: string): number
	local Count = 0
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			Count += 1
		end
	end
	return Count
end

local ScopeBootProgress: { [string]: any } = {}

local function ExecuteLifecyclePhase(ScopeName: string, LifecycleUnits: { LifecycleUnit }, PhaseName: string, Context: any)
	local progress = ScopeBootProgress[ScopeName]
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			if progress then
				progress.CurrentModuleName = Unit.Name
				progress.CurrentPhaseName = PhaseName
			end

			debug.profilebegin(ScopeName .. ":" .. Unit.Name .. ":" .. PhaseName)
			if PhaseName == "Start" then
				-- Asynchronous Start dispatch ensures services initialize without thread blocking
				task.spawn(function()
					local success, err = pcall(function()
						Loaded[PhaseName](Context)
					end)
					if not success then
						warn(string.format("[ModuleLoader] Error during asynchronous %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
					end
				end)
			else
				local success, err = pcall(function()
					Loaded[PhaseName](Context)
				end)
				if not success then
					error(string.format("[ModuleLoader] Error during %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
				end
			end
			debug.profileend()

			if progress then
				progress.CompletedStepCount += 1
				progress.Percent = CalculateScopeBootPercent(progress.CompletedStepCount, progress.TotalStepCount)
			end
		end
	end
end

-- Resolve module instance from a dot-delimited path
local function ResolveModuleInstance(scope: string, path: string): ModuleScript?
	local current: Instance? = nil

	if scope == "Shared" or path:match("^Packages%.") or path:match("^SharedModules%.") then
		current = ReplicatedStorage
	elseif scope == "Server" or path:match("^ServerModules%.") then
		local sss = game:GetService("ServerScriptService")
		current = sss
	else
		current = ReplicatedStorage
	end

	local parts = string.split(path, ".")
	for _, part in ipairs(parts) do
		if not current then return nil end
		current = current:FindFirstChild(part)
	end

	if current and current:IsA("ModuleScript") then
		return current :: ModuleScript
	end
	return nil
end

function ModuleLoader.Register(name: string, module: any)
	ModuleCache[name] = module
	local simpleName = name:match("([^%.]+)--!strict
-- [ProductionCore / Shared / ModuleLoader.luau]
-- Core bootstrap lifecycle engine: Handles phased Init/Start, client pacing, and dependency resolution

local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local ModuleLoader = {}
local ModuleCache: { [string]: any } = {}
local ScopeBootStateByName = { Shared = false, Server = false, Client = false }

export type LifecycleUnit = {
	Name: string,
	Loaded: any,
	Priority: number,
}

local function CreateScopeBootProgressState(ScopeName: string)
	return {
		ScopeName = ScopeName,
		CurrentModuleName = "Preparing",
		CurrentPhaseName = "Boot",
		CurrentModulePercent = 0,
		CompletedStepCount = 0,
		TotalStepCount = 0,
		Percent = 0,
		IsComplete = false,
	}
end

local function CalculateScopeBootPercent(CompletedStepCount: number, TotalStepCount: number): number
	if TotalStepCount <= 0 then return 100 end
	local RawPercent = (CompletedStepCount / TotalStepCount) * 100
	return math.clamp(math.floor(RawPercent + 0.5), 0, 100)
end

local function CountLifecyclePhaseSteps(LifecycleUnits: { LifecycleUnit }, PhaseName: string): number
	local Count = 0
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			Count += 1
		end
	end
	return Count
end

local ScopeBootProgress: { [string]: any } = {}

local function ExecuteLifecyclePhase(ScopeName: string, LifecycleUnits: { LifecycleUnit }, PhaseName: string, Context: any)
	local progress = ScopeBootProgress[ScopeName]
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			if progress then
				progress.CurrentModuleName = Unit.Name
				progress.CurrentPhaseName = PhaseName
			end

			debug.profilebegin(ScopeName .. ":" .. Unit.Name .. ":" .. PhaseName)
			if PhaseName == "Start" then
				-- Asynchronous Start dispatch ensures services initialize without thread blocking
				task.spawn(function()
					local success, err = pcall(function()
						Loaded[PhaseName](Context)
					end)
					if not success then
						warn(string.format("[ModuleLoader] Error during asynchronous %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
					end
				end)
			else
				local success, err = pcall(function()
					Loaded[PhaseName](Context)
				end)
				if not success then
					error(string.format("[ModuleLoader] Error during %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
				end
			end
			debug.profileend()

			if progress then
				progress.CompletedStepCount += 1
				progress.Percent = CalculateScopeBootPercent(progress.CompletedStepCount, progress.TotalStepCount)
			end
		end
	end
end

-- Resolve module instance from a dot-delimited path
local function ResolveModuleInstance(scope: string, path: string): ModuleScript?
	local current: Instance? = nil

	if scope == "Shared" or path:match("^Packages%.") or path:match("^SharedModules%.") then
		current = ReplicatedStorage
	elseif scope == "Server" or path:match("^ServerModules%.") then
		local sss = game:GetService("ServerScriptService")
		current = sss
	else
		current = ReplicatedStorage
	end

	local parts = string.split(path, ".")
	for _, part in ipairs(parts) do
		if not current then return nil end
		current = current:FindFirstChild(part)
	end

	if current and current:IsA("ModuleScript") then
		return current :: ModuleScript
	end
	return nil
end

function ModuleLoader.Register(name: string, module: any)
	ModuleCache[name] = module
	local simpleName = name:match("([^%.]+)--!strict
-- [ProductionCore / Shared / ModuleLoader.luau]
-- Core bootstrap lifecycle engine: Handles phased Init/Start, client pacing, and dependency resolution

local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local ModuleLoader = {}
local ModuleCache: { [string]: any } = {}
local ScopeBootStateByName = { Shared = false, Server = false, Client = false }

export type LifecycleUnit = {
	Name: string,
	Loaded: any,
	Priority: number,
}

local function CreateScopeBootProgressState(ScopeName: string)
	return {
		ScopeName = ScopeName,
		CurrentModuleName = "Preparing",
		CurrentPhaseName = "Boot",
		CurrentModulePercent = 0,
		CompletedStepCount = 0,
		TotalStepCount = 0,
		Percent = 0,
		IsComplete = false,
	}
end

local function CalculateScopeBootPercent(CompletedStepCount: number, TotalStepCount: number): number
	if TotalStepCount <= 0 then return 100 end
	local RawPercent = (CompletedStepCount / TotalStepCount) * 100
	return math.clamp(math.floor(RawPercent + 0.5), 0, 100)
end

local function CountLifecyclePhaseSteps(LifecycleUnits: { LifecycleUnit }, PhaseName: string): number
	local Count = 0
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			Count += 1
		end
	end
	return Count
end

local function ExecuteLifecyclePhase(ScopeName: string, LifecycleUnits: { LifecycleUnit }, PhaseName: string, Context: any)
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			debug.profilebegin(ScopeName .. ":" .. Unit.Name .. ":" .. PhaseName)
			local success, err = pcall(function()
				Loaded[PhaseName](Context)
			end)
			debug.profileend()
			if not success then
				error(string.format("[ModuleLoader] Error during %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
			end
		end
	end
end

-- Resolve module instance from a dot-delimited path
local function ResolveModuleInstance(scope: string, path: string): ModuleScript?
	local current: Instance? = nil

	if scope == "Shared" or path:match("^Packages%.") or path:match("^SharedModules%.") then
		current = ReplicatedStorage
	elseif scope == "Server" or path:match("^ServerModules%.") then
		local sss = game:GetService("ServerScriptService")
		current = sss
	else
		current = ReplicatedStorage
	end

	local parts = string.split(path, ".")
	for _, part in ipairs(parts) do
		if not current then return nil end
		current = current:FindFirstChild(part)
	end

	if current and current:IsA("ModuleScript") then
		return current :: ModuleScript
	end
	return nil
end

function ModuleLoader.Register(name: string, module: any)
	ModuleCache[name] = module
end

function ModuleLoader.Require(scope: string, path: string): any
	local cacheKey = scope .. ":" .. path
	if ModuleCache[cacheKey] ~= nil then
		return ModuleCache[cacheKey]
	end
	if ModuleCache[path] ~= nil then
		return ModuleCache[path]
	end

	local inst = ResolveModuleInstance(scope, path)
	if inst then
		local loaded = require(inst)
		ModuleCache[cacheKey] = loaded
		ModuleCache[path] = loaded
		return loaded
	end

	-- Check fallback in cache under simple name
	local simpleName = path:match("([^%.]+)$") or path
	if ModuleCache[simpleName] ~= nil then
		return ModuleCache[simpleName]
	end

	error(string.format("[ModuleLoader] Could not resolve module '%s' in scope '%s'", path, scope))
end

function ModuleLoader.RequireShared(path: string): any
	return ModuleLoader.Require("Shared", path)
end

function ModuleLoader.RequireScoped(path: string): any
	local isServer = RunService:IsServer()
	local scope = if isServer then "Server" else "Client"
	return ModuleLoader.Require(scope, path)
end

function ModuleLoader.Boot(scopeName: string, container: Instance)
	local units: { LifecycleUnit } = {}

	for _, descendant in ipairs(container:GetDescendants()) do
		if descendant:IsA("ModuleScript") then
			local success, loaded = pcall(require, descendant)
			if success then
				local priority = 10
				if type(loaded) == "table" and type(loaded.Metadata) == "table" and type(loaded.Metadata.Priority) == "number" then
					priority = loaded.Metadata.Priority
				end
				table.insert(units, {
					Name = descendant.Name,
					Loaded = loaded,
					Priority = priority,
				})
				ModuleCache[descendant.Name] = loaded
			else
				warn(string.format("[ModuleLoader] Failed to require %s: %s", descendant:GetFullName(), tostring(loaded)))
			end
		end
	end

	-- Sort by Priority descending (higher priority inits first)
	table.sort(units, function(a, b)
		return a.Priority > b.Priority
	end)

	local context = {
		ModuleLoader = ModuleLoader,
	}

	-- Phase 1: Synchronous Init
	ExecuteLifecyclePhase(scopeName, units, "Init", context)

	-- Phase 2: Asynchronous Start
	ExecuteLifecyclePhase(scopeName, units, "Start", context)

	ScopeBootStateByName[scopeName] = true
	print(string.format("[ModuleLoader] Scope '%s' boot completed (%d modules).", scopeName, #units))
end

return ModuleLoaderquot;) or path
	if ModuleCache[simpleName] ~= nil then
		return ModuleCache[simpleName]
	end

	error(string.format("[ModuleLoader] Could not resolve module '%s' in scope '%s'", path, scope))
end

function ModuleLoader.RequireShared(path: string): any
	return ModuleLoader.Require("Shared", path)
end

function ModuleLoader.RequireScoped(path: string): any
	local isServer = RunService:IsServer()
	local scope = if isServer then "Server" else "Client"
	return ModuleLoader.Require(scope, path)
end

function ModuleLoader.Boot(scopeName: string, container: Instance)
	local units: { LifecycleUnit } = {}

	for _, descendant in ipairs(container:GetDescendants()) do
		if descendant:IsA("ModuleScript") then
			local success, loaded
			if (descendant :: any)._module ~= nil then
				success, loaded = true, (descendant :: any)._module
			else
				success, loaded = pcall(require, descendant)
			end
			if success then
				local priority = 10
				if type(loaded) == "table" and type(loaded.Metadata) == "table" and type(loaded.Metadata.Priority) == "number" then
					priority = loaded.Metadata.Priority
				end
				table.insert(units, {
					Name = descendant.Name,
					Loaded = loaded,
					Priority = priority,
				})
				ModuleCache[descendant.Name] = loaded
			else
				warn(string.format("[ModuleLoader] Failed to require %s: %s", descendant:GetFullName(), tostring(loaded)))
			end
		end
	end

	-- Sort by Priority descending (higher priority inits first)
	table.sort(units, function(a, b)
		return a.Priority > b.Priority
	end)

	local totalSteps = CountLifecyclePhaseSteps(units, "Init") + CountLifecyclePhaseSteps(units, "Start")
	local progress = CreateScopeBootProgressState(scopeName)
	progress.TotalStepCount = totalSteps
	ScopeBootProgress[scopeName] = progress

	local context = {
		ModuleLoader = ModuleLoader,
	}

	-- Phase 1: Synchronous Init
	ExecuteLifecyclePhase(scopeName, units, "Init", context)

	-- Phase 2: Asynchronous Start
	ExecuteLifecyclePhase(scopeName, units, "Start", context)

	progress.IsComplete = true
	progress.Percent = 100
	ScopeBootStateByName[scopeName] = true
	print(string.format("[ModuleLoader] Scope '%s' boot completed (%d modules).", scopeName, #units))
end

return ModuleLoader
quot;)
	if simpleName and ModuleCache[simpleName] == nil then
		ModuleCache[simpleName] = module
	end
end

function ModuleLoader.GetBootProgress(scopeName: string): any?
	return ScopeBootProgress[scopeName]
end

function ModuleLoader.Require(scope: string, path: string): any
	local cacheKey = scope .. ":" .. path
	if ModuleCache[cacheKey] ~= nil then
		return ModuleCache[cacheKey]
	end
	if ModuleCache[path] ~= nil then
		return ModuleCache[path]
	end

	local inst = ResolveModuleInstance(scope, path)
	if inst then
		local loaded = require(inst)
		ModuleCache[cacheKey] = loaded
		ModuleCache[path] = loaded
		return loaded
	end

	-- Check fallback in cache under simple name
	local simpleName = path:match("([^%.]+)--!strict
-- [ProductionCore / Shared / ModuleLoader.luau]
-- Core bootstrap lifecycle engine: Handles phased Init/Start, client pacing, and dependency resolution

local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local ModuleLoader = {}
local ModuleCache: { [string]: any } = {}
local ScopeBootStateByName = { Shared = false, Server = false, Client = false }

export type LifecycleUnit = {
	Name: string,
	Loaded: any,
	Priority: number,
}

local function CreateScopeBootProgressState(ScopeName: string)
	return {
		ScopeName = ScopeName,
		CurrentModuleName = "Preparing",
		CurrentPhaseName = "Boot",
		CurrentModulePercent = 0,
		CompletedStepCount = 0,
		TotalStepCount = 0,
		Percent = 0,
		IsComplete = false,
	}
end

local function CalculateScopeBootPercent(CompletedStepCount: number, TotalStepCount: number): number
	if TotalStepCount <= 0 then return 100 end
	local RawPercent = (CompletedStepCount / TotalStepCount) * 100
	return math.clamp(math.floor(RawPercent + 0.5), 0, 100)
end

local function CountLifecyclePhaseSteps(LifecycleUnits: { LifecycleUnit }, PhaseName: string): number
	local Count = 0
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			Count += 1
		end
	end
	return Count
end

local ScopeBootProgress: { [string]: any } = {}

local function ExecuteLifecyclePhase(ScopeName: string, LifecycleUnits: { LifecycleUnit }, PhaseName: string, Context: any)
	local progress = ScopeBootProgress[ScopeName]
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			if progress then
				progress.CurrentModuleName = Unit.Name
				progress.CurrentPhaseName = PhaseName
			end

			debug.profilebegin(ScopeName .. ":" .. Unit.Name .. ":" .. PhaseName)
			if PhaseName == "Start" then
				-- Asynchronous Start dispatch ensures services initialize without thread blocking
				task.spawn(function()
					local success, err = pcall(function()
						Loaded[PhaseName](Context)
					end)
					if not success then
						warn(string.format("[ModuleLoader] Error during asynchronous %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
					end
				end)
			else
				local success, err = pcall(function()
					Loaded[PhaseName](Context)
				end)
				if not success then
					error(string.format("[ModuleLoader] Error during %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
				end
			end
			debug.profileend()

			if progress then
				progress.CompletedStepCount += 1
				progress.Percent = CalculateScopeBootPercent(progress.CompletedStepCount, progress.TotalStepCount)
			end
		end
	end
end

-- Resolve module instance from a dot-delimited path
local function ResolveModuleInstance(scope: string, path: string): ModuleScript?
	local current: Instance? = nil

	if scope == "Shared" or path:match("^Packages%.") or path:match("^SharedModules%.") then
		current = ReplicatedStorage
	elseif scope == "Server" or path:match("^ServerModules%.") then
		local sss = game:GetService("ServerScriptService")
		current = sss
	else
		current = ReplicatedStorage
	end

	local parts = string.split(path, ".")
	for _, part in ipairs(parts) do
		if not current then return nil end
		current = current:FindFirstChild(part)
	end

	if current and current:IsA("ModuleScript") then
		return current :: ModuleScript
	end
	return nil
end

function ModuleLoader.Register(name: string, module: any)
	ModuleCache[name] = module
	local simpleName = name:match("([^%.]+)--!strict
-- [ProductionCore / Shared / ModuleLoader.luau]
-- Core bootstrap lifecycle engine: Handles phased Init/Start, client pacing, and dependency resolution

local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local ModuleLoader = {}
local ModuleCache: { [string]: any } = {}
local ScopeBootStateByName = { Shared = false, Server = false, Client = false }

export type LifecycleUnit = {
	Name: string,
	Loaded: any,
	Priority: number,
}

local function CreateScopeBootProgressState(ScopeName: string)
	return {
		ScopeName = ScopeName,
		CurrentModuleName = "Preparing",
		CurrentPhaseName = "Boot",
		CurrentModulePercent = 0,
		CompletedStepCount = 0,
		TotalStepCount = 0,
		Percent = 0,
		IsComplete = false,
	}
end

local function CalculateScopeBootPercent(CompletedStepCount: number, TotalStepCount: number): number
	if TotalStepCount <= 0 then return 100 end
	local RawPercent = (CompletedStepCount / TotalStepCount) * 100
	return math.clamp(math.floor(RawPercent + 0.5), 0, 100)
end

local function CountLifecyclePhaseSteps(LifecycleUnits: { LifecycleUnit }, PhaseName: string): number
	local Count = 0
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			Count += 1
		end
	end
	return Count
end

local ScopeBootProgress: { [string]: any } = {}

local function ExecuteLifecyclePhase(ScopeName: string, LifecycleUnits: { LifecycleUnit }, PhaseName: string, Context: any)
	local progress = ScopeBootProgress[ScopeName]
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			if progress then
				progress.CurrentModuleName = Unit.Name
				progress.CurrentPhaseName = PhaseName
			end

			debug.profilebegin(ScopeName .. ":" .. Unit.Name .. ":" .. PhaseName)
			if PhaseName == "Start" then
				-- Asynchronous Start dispatch ensures services initialize without thread blocking
				task.spawn(function()
					local success, err = pcall(function()
						Loaded[PhaseName](Context)
					end)
					if not success then
						warn(string.format("[ModuleLoader] Error during asynchronous %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
					end
				end)
			else
				local success, err = pcall(function()
					Loaded[PhaseName](Context)
				end)
				if not success then
					error(string.format("[ModuleLoader] Error during %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
				end
			end
			debug.profileend()

			if progress then
				progress.CompletedStepCount += 1
				progress.Percent = CalculateScopeBootPercent(progress.CompletedStepCount, progress.TotalStepCount)
			end
		end
	end
end

-- Resolve module instance from a dot-delimited path
local function ResolveModuleInstance(scope: string, path: string): ModuleScript?
	local current: Instance? = nil

	if scope == "Shared" or path:match("^Packages%.") or path:match("^SharedModules%.") then
		current = ReplicatedStorage
	elseif scope == "Server" or path:match("^ServerModules%.") then
		local sss = game:GetService("ServerScriptService")
		current = sss
	else
		current = ReplicatedStorage
	end

	local parts = string.split(path, ".")
	for _, part in ipairs(parts) do
		if not current then return nil end
		current = current:FindFirstChild(part)
	end

	if current and current:IsA("ModuleScript") then
		return current :: ModuleScript
	end
	return nil
end

function ModuleLoader.Register(name: string, module: any)
	ModuleCache[name] = module
	local simpleName = name:match("([^%.]+)--!strict
-- [ProductionCore / Shared / ModuleLoader.luau]
-- Core bootstrap lifecycle engine: Handles phased Init/Start, client pacing, and dependency resolution

local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local ModuleLoader = {}
local ModuleCache: { [string]: any } = {}
local ScopeBootStateByName = { Shared = false, Server = false, Client = false }

export type LifecycleUnit = {
	Name: string,
	Loaded: any,
	Priority: number,
}

local function CreateScopeBootProgressState(ScopeName: string)
	return {
		ScopeName = ScopeName,
		CurrentModuleName = "Preparing",
		CurrentPhaseName = "Boot",
		CurrentModulePercent = 0,
		CompletedStepCount = 0,
		TotalStepCount = 0,
		Percent = 0,
		IsComplete = false,
	}
end

local function CalculateScopeBootPercent(CompletedStepCount: number, TotalStepCount: number): number
	if TotalStepCount <= 0 then return 100 end
	local RawPercent = (CompletedStepCount / TotalStepCount) * 100
	return math.clamp(math.floor(RawPercent + 0.5), 0, 100)
end

local function CountLifecyclePhaseSteps(LifecycleUnits: { LifecycleUnit }, PhaseName: string): number
	local Count = 0
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			Count += 1
		end
	end
	return Count
end

local ScopeBootProgress: { [string]: any } = {}

local function ExecuteLifecyclePhase(ScopeName: string, LifecycleUnits: { LifecycleUnit }, PhaseName: string, Context: any)
	local progress = ScopeBootProgress[ScopeName]
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			if progress then
				progress.CurrentModuleName = Unit.Name
				progress.CurrentPhaseName = PhaseName
			end

			debug.profilebegin(ScopeName .. ":" .. Unit.Name .. ":" .. PhaseName)
			if PhaseName == "Start" then
				-- Asynchronous Start dispatch ensures services initialize without thread blocking
				task.spawn(function()
					local success, err = pcall(function()
						Loaded[PhaseName](Context)
					end)
					if not success then
						warn(string.format("[ModuleLoader] Error during asynchronous %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
					end
				end)
			else
				local success, err = pcall(function()
					Loaded[PhaseName](Context)
				end)
				if not success then
					error(string.format("[ModuleLoader] Error during %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
				end
			end
			debug.profileend()

			if progress then
				progress.CompletedStepCount += 1
				progress.Percent = CalculateScopeBootPercent(progress.CompletedStepCount, progress.TotalStepCount)
			end
		end
	end
end

-- Resolve module instance from a dot-delimited path
local function ResolveModuleInstance(scope: string, path: string): ModuleScript?
	local current: Instance? = nil

	if scope == "Shared" or path:match("^Packages%.") or path:match("^SharedModules%.") then
		current = ReplicatedStorage
	elseif scope == "Server" or path:match("^ServerModules%.") then
		local sss = game:GetService("ServerScriptService")
		current = sss
	else
		current = ReplicatedStorage
	end

	local parts = string.split(path, ".")
	for _, part in ipairs(parts) do
		if not current then return nil end
		current = current:FindFirstChild(part)
	end

	if current and current:IsA("ModuleScript") then
		return current :: ModuleScript
	end
	return nil
end

function ModuleLoader.Register(name: string, module: any)
	ModuleCache[name] = module
	local simpleName = name:match("([^%.]+)--!strict
-- [ProductionCore / Shared / ModuleLoader.luau]
-- Core bootstrap lifecycle engine: Handles phased Init/Start, client pacing, and dependency resolution

local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local ModuleLoader = {}
local ModuleCache: { [string]: any } = {}
local ScopeBootStateByName = { Shared = false, Server = false, Client = false }

export type LifecycleUnit = {
	Name: string,
	Loaded: any,
	Priority: number,
}

local function CreateScopeBootProgressState(ScopeName: string)
	return {
		ScopeName = ScopeName,
		CurrentModuleName = "Preparing",
		CurrentPhaseName = "Boot",
		CurrentModulePercent = 0,
		CompletedStepCount = 0,
		TotalStepCount = 0,
		Percent = 0,
		IsComplete = false,
	}
end

local function CalculateScopeBootPercent(CompletedStepCount: number, TotalStepCount: number): number
	if TotalStepCount <= 0 then return 100 end
	local RawPercent = (CompletedStepCount / TotalStepCount) * 100
	return math.clamp(math.floor(RawPercent + 0.5), 0, 100)
end

local function CountLifecyclePhaseSteps(LifecycleUnits: { LifecycleUnit }, PhaseName: string): number
	local Count = 0
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			Count += 1
		end
	end
	return Count
end

local function ExecuteLifecyclePhase(ScopeName: string, LifecycleUnits: { LifecycleUnit }, PhaseName: string, Context: any)
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			debug.profilebegin(ScopeName .. ":" .. Unit.Name .. ":" .. PhaseName)
			local success, err = pcall(function()
				Loaded[PhaseName](Context)
			end)
			debug.profileend()
			if not success then
				error(string.format("[ModuleLoader] Error during %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
			end
		end
	end
end

-- Resolve module instance from a dot-delimited path
local function ResolveModuleInstance(scope: string, path: string): ModuleScript?
	local current: Instance? = nil

	if scope == "Shared" or path:match("^Packages%.") or path:match("^SharedModules%.") then
		current = ReplicatedStorage
	elseif scope == "Server" or path:match("^ServerModules%.") then
		local sss = game:GetService("ServerScriptService")
		current = sss
	else
		current = ReplicatedStorage
	end

	local parts = string.split(path, ".")
	for _, part in ipairs(parts) do
		if not current then return nil end
		current = current:FindFirstChild(part)
	end

	if current and current:IsA("ModuleScript") then
		return current :: ModuleScript
	end
	return nil
end

function ModuleLoader.Register(name: string, module: any)
	ModuleCache[name] = module
end

function ModuleLoader.Require(scope: string, path: string): any
	local cacheKey = scope .. ":" .. path
	if ModuleCache[cacheKey] ~= nil then
		return ModuleCache[cacheKey]
	end
	if ModuleCache[path] ~= nil then
		return ModuleCache[path]
	end

	local inst = ResolveModuleInstance(scope, path)
	if inst then
		local loaded = require(inst)
		ModuleCache[cacheKey] = loaded
		ModuleCache[path] = loaded
		return loaded
	end

	-- Check fallback in cache under simple name
	local simpleName = path:match("([^%.]+)$") or path
	if ModuleCache[simpleName] ~= nil then
		return ModuleCache[simpleName]
	end

	error(string.format("[ModuleLoader] Could not resolve module '%s' in scope '%s'", path, scope))
end

function ModuleLoader.RequireShared(path: string): any
	return ModuleLoader.Require("Shared", path)
end

function ModuleLoader.RequireScoped(path: string): any
	local isServer = RunService:IsServer()
	local scope = if isServer then "Server" else "Client"
	return ModuleLoader.Require(scope, path)
end

function ModuleLoader.Boot(scopeName: string, container: Instance)
	local units: { LifecycleUnit } = {}

	for _, descendant in ipairs(container:GetDescendants()) do
		if descendant:IsA("ModuleScript") then
			local success, loaded = pcall(require, descendant)
			if success then
				local priority = 10
				if type(loaded) == "table" and type(loaded.Metadata) == "table" and type(loaded.Metadata.Priority) == "number" then
					priority = loaded.Metadata.Priority
				end
				table.insert(units, {
					Name = descendant.Name,
					Loaded = loaded,
					Priority = priority,
				})
				ModuleCache[descendant.Name] = loaded
			else
				warn(string.format("[ModuleLoader] Failed to require %s: %s", descendant:GetFullName(), tostring(loaded)))
			end
		end
	end

	-- Sort by Priority descending (higher priority inits first)
	table.sort(units, function(a, b)
		return a.Priority > b.Priority
	end)

	local context = {
		ModuleLoader = ModuleLoader,
	}

	-- Phase 1: Synchronous Init
	ExecuteLifecyclePhase(scopeName, units, "Init", context)

	-- Phase 2: Asynchronous Start
	ExecuteLifecyclePhase(scopeName, units, "Start", context)

	ScopeBootStateByName[scopeName] = true
	print(string.format("[ModuleLoader] Scope '%s' boot completed (%d modules).", scopeName, #units))
end

return ModuleLoaderquot;) or path
	if ModuleCache[simpleName] ~= nil then
		return ModuleCache[simpleName]
	end

	error(string.format("[ModuleLoader] Could not resolve module '%s' in scope '%s'", path, scope))
end

function ModuleLoader.RequireShared(path: string): any
	return ModuleLoader.Require("Shared", path)
end

function ModuleLoader.RequireScoped(path: string): any
	local isServer = RunService:IsServer()
	local scope = if isServer then "Server" else "Client"
	return ModuleLoader.Require(scope, path)
end

function ModuleLoader.Boot(scopeName: string, container: Instance)
	local units: { LifecycleUnit } = {}

	for _, descendant in ipairs(container:GetDescendants()) do
		if descendant:IsA("ModuleScript") then
			local success, loaded
			if (descendant :: any)._module ~= nil then
				success, loaded = true, (descendant :: any)._module
			else
				success, loaded = pcall(require, descendant)
			end
			if success then
				local priority = 10
				if type(loaded) == "table" and type(loaded.Metadata) == "table" and type(loaded.Metadata.Priority) == "number" then
					priority = loaded.Metadata.Priority
				end
				table.insert(units, {
					Name = descendant.Name,
					Loaded = loaded,
					Priority = priority,
				})
				ModuleCache[descendant.Name] = loaded
			else
				warn(string.format("[ModuleLoader] Failed to require %s: %s", descendant:GetFullName(), tostring(loaded)))
			end
		end
	end

	-- Sort by Priority descending (higher priority inits first)
	table.sort(units, function(a, b)
		return a.Priority > b.Priority
	end)

	local totalSteps = CountLifecyclePhaseSteps(units, "Init") + CountLifecyclePhaseSteps(units, "Start")
	local progress = CreateScopeBootProgressState(scopeName)
	progress.TotalStepCount = totalSteps
	ScopeBootProgress[scopeName] = progress

	local context = {
		ModuleLoader = ModuleLoader,
	}

	-- Phase 1: Synchronous Init
	ExecuteLifecyclePhase(scopeName, units, "Init", context)

	-- Phase 2: Asynchronous Start
	ExecuteLifecyclePhase(scopeName, units, "Start", context)

	progress.IsComplete = true
	progress.Percent = 100
	ScopeBootStateByName[scopeName] = true
	print(string.format("[ModuleLoader] Scope '%s' boot completed (%d modules).", scopeName, #units))
end

return ModuleLoader
quot;)
	if simpleName and ModuleCache[simpleName] == nil then
		ModuleCache[simpleName] = module
	end
end

function ModuleLoader.GetBootProgress(scopeName: string): any?
	return ScopeBootProgress[scopeName]
end

function ModuleLoader.Require(scope: string, path: string): any
	local cacheKey = scope .. ":" .. path
	if ModuleCache[cacheKey] ~= nil then
		return ModuleCache[cacheKey]
	end
	if ModuleCache[path] ~= nil then
		return ModuleCache[path]
	end

	local inst = ResolveModuleInstance(scope, path)
	if inst then
		local loaded = require(inst)
		ModuleCache[cacheKey] = loaded
		ModuleCache[path] = loaded
		return loaded
	end

	-- Check fallback in cache under simple name
	local simpleName = path:match("([^%.]+)--!strict
-- [ProductionCore / Shared / ModuleLoader.luau]
-- Core bootstrap lifecycle engine: Handles phased Init/Start, client pacing, and dependency resolution

local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local ModuleLoader = {}
local ModuleCache: { [string]: any } = {}
local ScopeBootStateByName = { Shared = false, Server = false, Client = false }

export type LifecycleUnit = {
	Name: string,
	Loaded: any,
	Priority: number,
}

local function CreateScopeBootProgressState(ScopeName: string)
	return {
		ScopeName = ScopeName,
		CurrentModuleName = "Preparing",
		CurrentPhaseName = "Boot",
		CurrentModulePercent = 0,
		CompletedStepCount = 0,
		TotalStepCount = 0,
		Percent = 0,
		IsComplete = false,
	}
end

local function CalculateScopeBootPercent(CompletedStepCount: number, TotalStepCount: number): number
	if TotalStepCount <= 0 then return 100 end
	local RawPercent = (CompletedStepCount / TotalStepCount) * 100
	return math.clamp(math.floor(RawPercent + 0.5), 0, 100)
end

local function CountLifecyclePhaseSteps(LifecycleUnits: { LifecycleUnit }, PhaseName: string): number
	local Count = 0
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			Count += 1
		end
	end
	return Count
end

local ScopeBootProgress: { [string]: any } = {}

local function ExecuteLifecyclePhase(ScopeName: string, LifecycleUnits: { LifecycleUnit }, PhaseName: string, Context: any)
	local progress = ScopeBootProgress[ScopeName]
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			if progress then
				progress.CurrentModuleName = Unit.Name
				progress.CurrentPhaseName = PhaseName
			end

			debug.profilebegin(ScopeName .. ":" .. Unit.Name .. ":" .. PhaseName)
			if PhaseName == "Start" then
				-- Asynchronous Start dispatch ensures services initialize without thread blocking
				task.spawn(function()
					local success, err = pcall(function()
						Loaded[PhaseName](Context)
					end)
					if not success then
						warn(string.format("[ModuleLoader] Error during asynchronous %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
					end
				end)
			else
				local success, err = pcall(function()
					Loaded[PhaseName](Context)
				end)
				if not success then
					error(string.format("[ModuleLoader] Error during %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
				end
			end
			debug.profileend()

			if progress then
				progress.CompletedStepCount += 1
				progress.Percent = CalculateScopeBootPercent(progress.CompletedStepCount, progress.TotalStepCount)
			end
		end
	end
end

-- Resolve module instance from a dot-delimited path
local function ResolveModuleInstance(scope: string, path: string): ModuleScript?
	local current: Instance? = nil

	if scope == "Shared" or path:match("^Packages%.") or path:match("^SharedModules%.") then
		current = ReplicatedStorage
	elseif scope == "Server" or path:match("^ServerModules%.") then
		local sss = game:GetService("ServerScriptService")
		current = sss
	else
		current = ReplicatedStorage
	end

	local parts = string.split(path, ".")
	for _, part in ipairs(parts) do
		if not current then return nil end
		current = current:FindFirstChild(part)
	end

	if current and current:IsA("ModuleScript") then
		return current :: ModuleScript
	end
	return nil
end

function ModuleLoader.Register(name: string, module: any)
	ModuleCache[name] = module
	local simpleName = name:match("([^%.]+)--!strict
-- [ProductionCore / Shared / ModuleLoader.luau]
-- Core bootstrap lifecycle engine: Handles phased Init/Start, client pacing, and dependency resolution

local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local ModuleLoader = {}
local ModuleCache: { [string]: any } = {}
local ScopeBootStateByName = { Shared = false, Server = false, Client = false }

export type LifecycleUnit = {
	Name: string,
	Loaded: any,
	Priority: number,
}

local function CreateScopeBootProgressState(ScopeName: string)
	return {
		ScopeName = ScopeName,
		CurrentModuleName = "Preparing",
		CurrentPhaseName = "Boot",
		CurrentModulePercent = 0,
		CompletedStepCount = 0,
		TotalStepCount = 0,
		Percent = 0,
		IsComplete = false,
	}
end

local function CalculateScopeBootPercent(CompletedStepCount: number, TotalStepCount: number): number
	if TotalStepCount <= 0 then return 100 end
	local RawPercent = (CompletedStepCount / TotalStepCount) * 100
	return math.clamp(math.floor(RawPercent + 0.5), 0, 100)
end

local function CountLifecyclePhaseSteps(LifecycleUnits: { LifecycleUnit }, PhaseName: string): number
	local Count = 0
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			Count += 1
		end
	end
	return Count
end

local ScopeBootProgress: { [string]: any } = {}

local function ExecuteLifecyclePhase(ScopeName: string, LifecycleUnits: { LifecycleUnit }, PhaseName: string, Context: any)
	local progress = ScopeBootProgress[ScopeName]
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			if progress then
				progress.CurrentModuleName = Unit.Name
				progress.CurrentPhaseName = PhaseName
			end

			debug.profilebegin(ScopeName .. ":" .. Unit.Name .. ":" .. PhaseName)
			if PhaseName == "Start" then
				-- Asynchronous Start dispatch ensures services initialize without thread blocking
				task.spawn(function()
					local success, err = pcall(function()
						Loaded[PhaseName](Context)
					end)
					if not success then
						warn(string.format("[ModuleLoader] Error during asynchronous %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
					end
				end)
			else
				local success, err = pcall(function()
					Loaded[PhaseName](Context)
				end)
				if not success then
					error(string.format("[ModuleLoader] Error during %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
				end
			end
			debug.profileend()

			if progress then
				progress.CompletedStepCount += 1
				progress.Percent = CalculateScopeBootPercent(progress.CompletedStepCount, progress.TotalStepCount)
			end
		end
	end
end

-- Resolve module instance from a dot-delimited path
local function ResolveModuleInstance(scope: string, path: string): ModuleScript?
	local current: Instance? = nil

	if scope == "Shared" or path:match("^Packages%.") or path:match("^SharedModules%.") then
		current = ReplicatedStorage
	elseif scope == "Server" or path:match("^ServerModules%.") then
		local sss = game:GetService("ServerScriptService")
		current = sss
	else
		current = ReplicatedStorage
	end

	local parts = string.split(path, ".")
	for _, part in ipairs(parts) do
		if not current then return nil end
		current = current:FindFirstChild(part)
	end

	if current and current:IsA("ModuleScript") then
		return current :: ModuleScript
	end
	return nil
end

function ModuleLoader.Register(name: string, module: any)
	ModuleCache[name] = module
	local simpleName = name:match("([^%.]+)--!strict
-- [ProductionCore / Shared / ModuleLoader.luau]
-- Core bootstrap lifecycle engine: Handles phased Init/Start, client pacing, and dependency resolution

local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local ModuleLoader = {}
local ModuleCache: { [string]: any } = {}
local ScopeBootStateByName = { Shared = false, Server = false, Client = false }

export type LifecycleUnit = {
	Name: string,
	Loaded: any,
	Priority: number,
}

local function CreateScopeBootProgressState(ScopeName: string)
	return {
		ScopeName = ScopeName,
		CurrentModuleName = "Preparing",
		CurrentPhaseName = "Boot",
		CurrentModulePercent = 0,
		CompletedStepCount = 0,
		TotalStepCount = 0,
		Percent = 0,
		IsComplete = false,
	}
end

local function CalculateScopeBootPercent(CompletedStepCount: number, TotalStepCount: number): number
	if TotalStepCount <= 0 then return 100 end
	local RawPercent = (CompletedStepCount / TotalStepCount) * 100
	return math.clamp(math.floor(RawPercent + 0.5), 0, 100)
end

local function CountLifecyclePhaseSteps(LifecycleUnits: { LifecycleUnit }, PhaseName: string): number
	local Count = 0
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			Count += 1
		end
	end
	return Count
end

local function ExecuteLifecyclePhase(ScopeName: string, LifecycleUnits: { LifecycleUnit }, PhaseName: string, Context: any)
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			debug.profilebegin(ScopeName .. ":" .. Unit.Name .. ":" .. PhaseName)
			local success, err = pcall(function()
				Loaded[PhaseName](Context)
			end)
			debug.profileend()
			if not success then
				error(string.format("[ModuleLoader] Error during %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
			end
		end
	end
end

-- Resolve module instance from a dot-delimited path
local function ResolveModuleInstance(scope: string, path: string): ModuleScript?
	local current: Instance? = nil

	if scope == "Shared" or path:match("^Packages%.") or path:match("^SharedModules%.") then
		current = ReplicatedStorage
	elseif scope == "Server" or path:match("^ServerModules%.") then
		local sss = game:GetService("ServerScriptService")
		current = sss
	else
		current = ReplicatedStorage
	end

	local parts = string.split(path, ".")
	for _, part in ipairs(parts) do
		if not current then return nil end
		current = current:FindFirstChild(part)
	end

	if current and current:IsA("ModuleScript") then
		return current :: ModuleScript
	end
	return nil
end

function ModuleLoader.Register(name: string, module: any)
	ModuleCache[name] = module
end

function ModuleLoader.Require(scope: string, path: string): any
	local cacheKey = scope .. ":" .. path
	if ModuleCache[cacheKey] ~= nil then
		return ModuleCache[cacheKey]
	end
	if ModuleCache[path] ~= nil then
		return ModuleCache[path]
	end

	local inst = ResolveModuleInstance(scope, path)
	if inst then
		local loaded = require(inst)
		ModuleCache[cacheKey] = loaded
		ModuleCache[path] = loaded
		return loaded
	end

	-- Check fallback in cache under simple name
	local simpleName = path:match("([^%.]+)$") or path
	if ModuleCache[simpleName] ~= nil then
		return ModuleCache[simpleName]
	end

	error(string.format("[ModuleLoader] Could not resolve module '%s' in scope '%s'", path, scope))
end

function ModuleLoader.RequireShared(path: string): any
	return ModuleLoader.Require("Shared", path)
end

function ModuleLoader.RequireScoped(path: string): any
	local isServer = RunService:IsServer()
	local scope = if isServer then "Server" else "Client"
	return ModuleLoader.Require(scope, path)
end

function ModuleLoader.Boot(scopeName: string, container: Instance)
	local units: { LifecycleUnit } = {}

	for _, descendant in ipairs(container:GetDescendants()) do
		if descendant:IsA("ModuleScript") then
			local success, loaded = pcall(require, descendant)
			if success then
				local priority = 10
				if type(loaded) == "table" and type(loaded.Metadata) == "table" and type(loaded.Metadata.Priority) == "number" then
					priority = loaded.Metadata.Priority
				end
				table.insert(units, {
					Name = descendant.Name,
					Loaded = loaded,
					Priority = priority,
				})
				ModuleCache[descendant.Name] = loaded
			else
				warn(string.format("[ModuleLoader] Failed to require %s: %s", descendant:GetFullName(), tostring(loaded)))
			end
		end
	end

	-- Sort by Priority descending (higher priority inits first)
	table.sort(units, function(a, b)
		return a.Priority > b.Priority
	end)

	local context = {
		ModuleLoader = ModuleLoader,
	}

	-- Phase 1: Synchronous Init
	ExecuteLifecyclePhase(scopeName, units, "Init", context)

	-- Phase 2: Asynchronous Start
	ExecuteLifecyclePhase(scopeName, units, "Start", context)

	ScopeBootStateByName[scopeName] = true
	print(string.format("[ModuleLoader] Scope '%s' boot completed (%d modules).", scopeName, #units))
end

return ModuleLoaderquot;) or path
	if ModuleCache[simpleName] ~= nil then
		return ModuleCache[simpleName]
	end

	error(string.format("[ModuleLoader] Could not resolve module '%s' in scope '%s'", path, scope))
end

function ModuleLoader.RequireShared(path: string): any
	return ModuleLoader.Require("Shared", path)
end

function ModuleLoader.RequireScoped(path: string): any
	local isServer = RunService:IsServer()
	local scope = if isServer then "Server" else "Client"
	return ModuleLoader.Require(scope, path)
end

function ModuleLoader.Boot(scopeName: string, container: Instance)
	local units: { LifecycleUnit } = {}

	for _, descendant in ipairs(container:GetDescendants()) do
		if descendant:IsA("ModuleScript") then
			local success, loaded
			if (descendant :: any)._module ~= nil then
				success, loaded = true, (descendant :: any)._module
			else
				success, loaded = pcall(require, descendant)
			end
			if success then
				local priority = 10
				if type(loaded) == "table" and type(loaded.Metadata) == "table" and type(loaded.Metadata.Priority) == "number" then
					priority = loaded.Metadata.Priority
				end
				table.insert(units, {
					Name = descendant.Name,
					Loaded = loaded,
					Priority = priority,
				})
				ModuleCache[descendant.Name] = loaded
			else
				warn(string.format("[ModuleLoader] Failed to require %s: %s", descendant:GetFullName(), tostring(loaded)))
			end
		end
	end

	-- Sort by Priority descending (higher priority inits first)
	table.sort(units, function(a, b)
		return a.Priority > b.Priority
	end)

	local totalSteps = CountLifecyclePhaseSteps(units, "Init") + CountLifecyclePhaseSteps(units, "Start")
	local progress = CreateScopeBootProgressState(scopeName)
	progress.TotalStepCount = totalSteps
	ScopeBootProgress[scopeName] = progress

	local context = {
		ModuleLoader = ModuleLoader,
	}

	-- Phase 1: Synchronous Init
	ExecuteLifecyclePhase(scopeName, units, "Init", context)

	-- Phase 2: Asynchronous Start
	ExecuteLifecyclePhase(scopeName, units, "Start", context)

	progress.IsComplete = true
	progress.Percent = 100
	ScopeBootStateByName[scopeName] = true
	print(string.format("[ModuleLoader] Scope '%s' boot completed (%d modules).", scopeName, #units))
end

return ModuleLoader
quot;)
	if simpleName and ModuleCache[simpleName] == nil then
		ModuleCache[simpleName] = module
	end
end

function ModuleLoader.GetBootProgress(scopeName: string): any?
	return ScopeBootProgress[scopeName]
end

function ModuleLoader.Require(scope: string, path: string): any
	local cacheKey = scope .. ":" .. path
	if ModuleCache[cacheKey] ~= nil then
		return ModuleCache[cacheKey]
	end
	if ModuleCache[path] ~= nil then
		return ModuleCache[path]
	end

	local inst = ResolveModuleInstance(scope, path)
	if inst then
		local loaded = require(inst)
		ModuleCache[cacheKey] = loaded
		ModuleCache[path] = loaded
		return loaded
	end

	-- Check fallback in cache under simple name
	local simpleName = path:match("([^%.]+)--!strict
-- [ProductionCore / Shared / ModuleLoader.luau]
-- Core bootstrap lifecycle engine: Handles phased Init/Start, client pacing, and dependency resolution

local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local ModuleLoader = {}
local ModuleCache: { [string]: any } = {}
local ScopeBootStateByName = { Shared = false, Server = false, Client = false }

export type LifecycleUnit = {
	Name: string,
	Loaded: any,
	Priority: number,
}

local function CreateScopeBootProgressState(ScopeName: string)
	return {
		ScopeName = ScopeName,
		CurrentModuleName = "Preparing",
		CurrentPhaseName = "Boot",
		CurrentModulePercent = 0,
		CompletedStepCount = 0,
		TotalStepCount = 0,
		Percent = 0,
		IsComplete = false,
	}
end

local function CalculateScopeBootPercent(CompletedStepCount: number, TotalStepCount: number): number
	if TotalStepCount <= 0 then return 100 end
	local RawPercent = (CompletedStepCount / TotalStepCount) * 100
	return math.clamp(math.floor(RawPercent + 0.5), 0, 100)
end

local function CountLifecyclePhaseSteps(LifecycleUnits: { LifecycleUnit }, PhaseName: string): number
	local Count = 0
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			Count += 1
		end
	end
	return Count
end

local ScopeBootProgress: { [string]: any } = {}

local function ExecuteLifecyclePhase(ScopeName: string, LifecycleUnits: { LifecycleUnit }, PhaseName: string, Context: any)
	local progress = ScopeBootProgress[ScopeName]
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			if progress then
				progress.CurrentModuleName = Unit.Name
				progress.CurrentPhaseName = PhaseName
			end

			debug.profilebegin(ScopeName .. ":" .. Unit.Name .. ":" .. PhaseName)
			if PhaseName == "Start" then
				-- Asynchronous Start dispatch ensures services initialize without thread blocking
				task.spawn(function()
					local success, err = pcall(function()
						Loaded[PhaseName](Context)
					end)
					if not success then
						warn(string.format("[ModuleLoader] Error during asynchronous %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
					end
				end)
			else
				local success, err = pcall(function()
					Loaded[PhaseName](Context)
				end)
				if not success then
					error(string.format("[ModuleLoader] Error during %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
				end
			end
			debug.profileend()

			if progress then
				progress.CompletedStepCount += 1
				progress.Percent = CalculateScopeBootPercent(progress.CompletedStepCount, progress.TotalStepCount)
			end
		end
	end
end

-- Resolve module instance from a dot-delimited path
local function ResolveModuleInstance(scope: string, path: string): ModuleScript?
	local current: Instance? = nil

	if scope == "Shared" or path:match("^Packages%.") or path:match("^SharedModules%.") then
		current = ReplicatedStorage
	elseif scope == "Server" or path:match("^ServerModules%.") then
		local sss = game:GetService("ServerScriptService")
		current = sss
	else
		current = ReplicatedStorage
	end

	local parts = string.split(path, ".")
	for _, part in ipairs(parts) do
		if not current then return nil end
		current = current:FindFirstChild(part)
	end

	if current and current:IsA("ModuleScript") then
		return current :: ModuleScript
	end
	return nil
end

function ModuleLoader.Register(name: string, module: any)
	ModuleCache[name] = module
	local simpleName = name:match("([^%.]+)--!strict
-- [ProductionCore / Shared / ModuleLoader.luau]
-- Core bootstrap lifecycle engine: Handles phased Init/Start, client pacing, and dependency resolution

local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local ModuleLoader = {}
local ModuleCache: { [string]: any } = {}
local ScopeBootStateByName = { Shared = false, Server = false, Client = false }

export type LifecycleUnit = {
	Name: string,
	Loaded: any,
	Priority: number,
}

local function CreateScopeBootProgressState(ScopeName: string)
	return {
		ScopeName = ScopeName,
		CurrentModuleName = "Preparing",
		CurrentPhaseName = "Boot",
		CurrentModulePercent = 0,
		CompletedStepCount = 0,
		TotalStepCount = 0,
		Percent = 0,
		IsComplete = false,
	}
end

local function CalculateScopeBootPercent(CompletedStepCount: number, TotalStepCount: number): number
	if TotalStepCount <= 0 then return 100 end
	local RawPercent = (CompletedStepCount / TotalStepCount) * 100
	return math.clamp(math.floor(RawPercent + 0.5), 0, 100)
end

local function CountLifecyclePhaseSteps(LifecycleUnits: { LifecycleUnit }, PhaseName: string): number
	local Count = 0
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			Count += 1
		end
	end
	return Count
end

local function ExecuteLifecyclePhase(ScopeName: string, LifecycleUnits: { LifecycleUnit }, PhaseName: string, Context: any)
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			debug.profilebegin(ScopeName .. ":" .. Unit.Name .. ":" .. PhaseName)
			local success, err = pcall(function()
				Loaded[PhaseName](Context)
			end)
			debug.profileend()
			if not success then
				error(string.format("[ModuleLoader] Error during %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
			end
		end
	end
end

-- Resolve module instance from a dot-delimited path
local function ResolveModuleInstance(scope: string, path: string): ModuleScript?
	local current: Instance? = nil

	if scope == "Shared" or path:match("^Packages%.") or path:match("^SharedModules%.") then
		current = ReplicatedStorage
	elseif scope == "Server" or path:match("^ServerModules%.") then
		local sss = game:GetService("ServerScriptService")
		current = sss
	else
		current = ReplicatedStorage
	end

	local parts = string.split(path, ".")
	for _, part in ipairs(parts) do
		if not current then return nil end
		current = current:FindFirstChild(part)
	end

	if current and current:IsA("ModuleScript") then
		return current :: ModuleScript
	end
	return nil
end

function ModuleLoader.Register(name: string, module: any)
	ModuleCache[name] = module
end

function ModuleLoader.Require(scope: string, path: string): any
	local cacheKey = scope .. ":" .. path
	if ModuleCache[cacheKey] ~= nil then
		return ModuleCache[cacheKey]
	end
	if ModuleCache[path] ~= nil then
		return ModuleCache[path]
	end

	local inst = ResolveModuleInstance(scope, path)
	if inst then
		local loaded = require(inst)
		ModuleCache[cacheKey] = loaded
		ModuleCache[path] = loaded
		return loaded
	end

	-- Check fallback in cache under simple name
	local simpleName = path:match("([^%.]+)$") or path
	if ModuleCache[simpleName] ~= nil then
		return ModuleCache[simpleName]
	end

	error(string.format("[ModuleLoader] Could not resolve module '%s' in scope '%s'", path, scope))
end

function ModuleLoader.RequireShared(path: string): any
	return ModuleLoader.Require("Shared", path)
end

function ModuleLoader.RequireScoped(path: string): any
	local isServer = RunService:IsServer()
	local scope = if isServer then "Server" else "Client"
	return ModuleLoader.Require(scope, path)
end

function ModuleLoader.Boot(scopeName: string, container: Instance)
	local units: { LifecycleUnit } = {}

	for _, descendant in ipairs(container:GetDescendants()) do
		if descendant:IsA("ModuleScript") then
			local success, loaded = pcall(require, descendant)
			if success then
				local priority = 10
				if type(loaded) == "table" and type(loaded.Metadata) == "table" and type(loaded.Metadata.Priority) == "number" then
					priority = loaded.Metadata.Priority
				end
				table.insert(units, {
					Name = descendant.Name,
					Loaded = loaded,
					Priority = priority,
				})
				ModuleCache[descendant.Name] = loaded
			else
				warn(string.format("[ModuleLoader] Failed to require %s: %s", descendant:GetFullName(), tostring(loaded)))
			end
		end
	end

	-- Sort by Priority descending (higher priority inits first)
	table.sort(units, function(a, b)
		return a.Priority > b.Priority
	end)

	local context = {
		ModuleLoader = ModuleLoader,
	}

	-- Phase 1: Synchronous Init
	ExecuteLifecyclePhase(scopeName, units, "Init", context)

	-- Phase 2: Asynchronous Start
	ExecuteLifecyclePhase(scopeName, units, "Start", context)

	ScopeBootStateByName[scopeName] = true
	print(string.format("[ModuleLoader] Scope '%s' boot completed (%d modules).", scopeName, #units))
end

return ModuleLoaderquot;) or path
	if ModuleCache[simpleName] ~= nil then
		return ModuleCache[simpleName]
	end

	error(string.format("[ModuleLoader] Could not resolve module '%s' in scope '%s'", path, scope))
end

function ModuleLoader.RequireShared(path: string): any
	return ModuleLoader.Require("Shared", path)
end

function ModuleLoader.RequireScoped(path: string): any
	local isServer = RunService:IsServer()
	local scope = if isServer then "Server" else "Client"
	return ModuleLoader.Require(scope, path)
end

function ModuleLoader.Boot(scopeName: string, container: Instance)
	local units: { LifecycleUnit } = {}

	for _, descendant in ipairs(container:GetDescendants()) do
		if descendant:IsA("ModuleScript") then
			local success, loaded
			if (descendant :: any)._module ~= nil then
				success, loaded = true, (descendant :: any)._module
			else
				success, loaded = pcall(require, descendant)
			end
			if success then
				local priority = 10
				if type(loaded) == "table" and type(loaded.Metadata) == "table" and type(loaded.Metadata.Priority) == "number" then
					priority = loaded.Metadata.Priority
				end
				table.insert(units, {
					Name = descendant.Name,
					Loaded = loaded,
					Priority = priority,
				})
				ModuleCache[descendant.Name] = loaded
			else
				warn(string.format("[ModuleLoader] Failed to require %s: %s", descendant:GetFullName(), tostring(loaded)))
			end
		end
	end

	-- Sort by Priority descending (higher priority inits first)
	table.sort(units, function(a, b)
		return a.Priority > b.Priority
	end)

	local totalSteps = CountLifecyclePhaseSteps(units, "Init") + CountLifecyclePhaseSteps(units, "Start")
	local progress = CreateScopeBootProgressState(scopeName)
	progress.TotalStepCount = totalSteps
	ScopeBootProgress[scopeName] = progress

	local context = {
		ModuleLoader = ModuleLoader,
	}

	-- Phase 1: Synchronous Init
	ExecuteLifecyclePhase(scopeName, units, "Init", context)

	-- Phase 2: Asynchronous Start
	ExecuteLifecyclePhase(scopeName, units, "Start", context)

	progress.IsComplete = true
	progress.Percent = 100
	ScopeBootStateByName[scopeName] = true
	print(string.format("[ModuleLoader] Scope '%s' boot completed (%d modules).", scopeName, #units))
end

return ModuleLoader
quot;)
	if simpleName and ModuleCache[simpleName] == nil then
		ModuleCache[simpleName] = module
	end
end

function ModuleLoader.GetBootProgress(scopeName: string): any?
	return ScopeBootProgress[scopeName]
end

function ModuleLoader.Require(scope: string, path: string): any
	local cacheKey = scope .. ":" .. path
	if ModuleCache[cacheKey] ~= nil then
		return ModuleCache[cacheKey]
	end
	if ModuleCache[path] ~= nil then
		return ModuleCache[path]
	end

	local inst = ResolveModuleInstance(scope, path)
	if inst then
		local loaded = require(inst)
		ModuleCache[cacheKey] = loaded
		ModuleCache[path] = loaded
		return loaded
	end

	-- Check fallback in cache under simple name
	local simpleName = path:match("([^%.]+)--!strict
-- [ProductionCore / Shared / ModuleLoader.luau]
-- Core bootstrap lifecycle engine: Handles phased Init/Start, client pacing, and dependency resolution

local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local ModuleLoader = {}
local ModuleCache: { [string]: any } = {}
local ScopeBootStateByName = { Shared = false, Server = false, Client = false }

export type LifecycleUnit = {
	Name: string,
	Loaded: any,
	Priority: number,
}

local function CreateScopeBootProgressState(ScopeName: string)
	return {
		ScopeName = ScopeName,
		CurrentModuleName = "Preparing",
		CurrentPhaseName = "Boot",
		CurrentModulePercent = 0,
		CompletedStepCount = 0,
		TotalStepCount = 0,
		Percent = 0,
		IsComplete = false,
	}
end

local function CalculateScopeBootPercent(CompletedStepCount: number, TotalStepCount: number): number
	if TotalStepCount <= 0 then return 100 end
	local RawPercent = (CompletedStepCount / TotalStepCount) * 100
	return math.clamp(math.floor(RawPercent + 0.5), 0, 100)
end

local function CountLifecyclePhaseSteps(LifecycleUnits: { LifecycleUnit }, PhaseName: string): number
	local Count = 0
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			Count += 1
		end
	end
	return Count
end

local function ExecuteLifecyclePhase(ScopeName: string, LifecycleUnits: { LifecycleUnit }, PhaseName: string, Context: any)
	for _, Unit in ipairs(LifecycleUnits) do
		local Loaded = Unit.Loaded
		if type(Loaded) == "table" and type(Loaded[PhaseName]) == "function" then
			debug.profilebegin(ScopeName .. ":" .. Unit.Name .. ":" .. PhaseName)
			local success, err = pcall(function()
				Loaded[PhaseName](Context)
			end)
			debug.profileend()
			if not success then
				error(string.format("[ModuleLoader] Error during %s on %s: %s", PhaseName, Unit.Name, tostring(err)))
			end
		end
	end
end

-- Resolve module instance from a dot-delimited path
local function ResolveModuleInstance(scope: string, path: string): ModuleScript?
	local current: Instance? = nil

	if scope == "Shared" or path:match("^Packages%.") or path:match("^SharedModules%.") then
		current = ReplicatedStorage
	elseif scope == "Server" or path:match("^ServerModules%.") then
		local sss = game:GetService("ServerScriptService")
		current = sss
	else
		current = ReplicatedStorage
	end

	local parts = string.split(path, ".")
	for _, part in ipairs(parts) do
		if not current then return nil end
		current = current:FindFirstChild(part)
	end

	if current and current:IsA("ModuleScript") then
		return current :: ModuleScript
	end
	return nil
end

function ModuleLoader.Register(name: string, module: any)
	ModuleCache[name] = module
end

function ModuleLoader.Require(scope: string, path: string): any
	local cacheKey = scope .. ":" .. path
	if ModuleCache[cacheKey] ~= nil then
		return ModuleCache[cacheKey]
	end
	if ModuleCache[path] ~= nil then
		return ModuleCache[path]
	end

	local inst = ResolveModuleInstance(scope, path)
	if inst then
		local loaded = require(inst)
		ModuleCache[cacheKey] = loaded
		ModuleCache[path] = loaded
		return loaded
	end

	-- Check fallback in cache under simple name
	local simpleName = path:match("([^%.]+)$") or path
	if ModuleCache[simpleName] ~= nil then
		return ModuleCache[simpleName]
	end

	error(string.format("[ModuleLoader] Could not resolve module '%s' in scope '%s'", path, scope))
end

function ModuleLoader.RequireShared(path: string): any
	return ModuleLoader.Require("Shared", path)
end

function ModuleLoader.RequireScoped(path: string): any
	local isServer = RunService:IsServer()
	local scope = if isServer then "Server" else "Client"
	return ModuleLoader.Require(scope, path)
end

function ModuleLoader.Boot(scopeName: string, container: Instance)
	local units: { LifecycleUnit } = {}

	for _, descendant in ipairs(container:GetDescendants()) do
		if descendant:IsA("ModuleScript") then
			local success, loaded = pcall(require, descendant)
			if success then
				local priority = 10
				if type(loaded) == "table" and type(loaded.Metadata) == "table" and type(loaded.Metadata.Priority) == "number" then
					priority = loaded.Metadata.Priority
				end
				table.insert(units, {
					Name = descendant.Name,
					Loaded = loaded,
					Priority = priority,
				})
				ModuleCache[descendant.Name] = loaded
			else
				warn(string.format("[ModuleLoader] Failed to require %s: %s", descendant:GetFullName(), tostring(loaded)))
			end
		end
	end

	-- Sort by Priority descending (higher priority inits first)
	table.sort(units, function(a, b)
		return a.Priority > b.Priority
	end)

	local context = {
		ModuleLoader = ModuleLoader,
	}

	-- Phase 1: Synchronous Init
	ExecuteLifecyclePhase(scopeName, units, "Init", context)

	-- Phase 2: Asynchronous Start
	ExecuteLifecyclePhase(scopeName, units, "Start", context)

	ScopeBootStateByName[scopeName] = true
	print(string.format("[ModuleLoader] Scope '%s' boot completed (%d modules).", scopeName, #units))
end

return ModuleLoaderquot;) or path
	if ModuleCache[simpleName] ~= nil then
		return ModuleCache[simpleName]
	end

	error(string.format("[ModuleLoader] Could not resolve module '%s' in scope '%s'", path, scope))
end

function ModuleLoader.RequireShared(path: string): any
	return ModuleLoader.Require("Shared", path)
end

function ModuleLoader.RequireScoped(path: string): any
	local isServer = RunService:IsServer()
	local scope = if isServer then "Server" else "Client"
	return ModuleLoader.Require(scope, path)
end

function ModuleLoader.Boot(scopeName: string, container: Instance)
	local units: { LifecycleUnit } = {}

	for _, descendant in ipairs(container:GetDescendants()) do
		if descendant:IsA("ModuleScript") then
			local success, loaded
			if (descendant :: any)._module ~= nil then
				success, loaded = true, (descendant :: any)._module
			else
				success, loaded = pcall(require, descendant)
			end
			if success then
				local priority = 10
				if type(loaded) == "table" and type(loaded.Metadata) == "table" and type(loaded.Metadata.Priority) == "number" then
					priority = loaded.Metadata.Priority
				end
				table.insert(units, {
					Name = descendant.Name,
					Loaded = loaded,
					Priority = priority,
				})
				ModuleCache[descendant.Name] = loaded
			else
				warn(string.format("[ModuleLoader] Failed to require %s: %s", descendant:GetFullName(), tostring(loaded)))
			end
		end
	end

	-- Sort by Priority descending (higher priority inits first)
	table.sort(units, function(a, b)
		return a.Priority > b.Priority
	end)

	local totalSteps = CountLifecyclePhaseSteps(units, "Init") + CountLifecyclePhaseSteps(units, "Start")
	local progress = CreateScopeBootProgressState(scopeName)
	progress.TotalStepCount = totalSteps
	ScopeBootProgress[scopeName] = progress

	local context = {
		ModuleLoader = ModuleLoader,
	}

	-- Phase 1: Synchronous Init
	ExecuteLifecyclePhase(scopeName, units, "Init", context)

	-- Phase 2: Asynchronous Start
	ExecuteLifecyclePhase(scopeName, units, "Start", context)

	progress.IsComplete = true
	progress.Percent = 100
	ScopeBootStateByName[scopeName] = true
	print(string.format("[ModuleLoader] Scope '%s' boot completed (%d modules).", scopeName, #units))
end

return ModuleLoader
Source: src/server/ServerModules/AntiCheatService.luau • Suspicion decay, displacement auditing & universe bans
--!strict
-- [ProductionCore / ServerModules / AntiCheatService.luau]
-- Enterprise Authoritative Server Anti-Cheat & Exploit Mitigation Controller.
-- Provides displacement validation, speed-hack suppression, ability bypass coordination, and leak-free memory management.

local Players = game:GetService("Players")
local RunService = game:GetService("RunService")

export type ViolationData = {
	Type: string,
	Details: { [string]: any }?,
	Timestamp: number,
}

export type PlayerState = {
	Player: Player,
	Violations: number,
	SuspicionScore: number,
	JoinTime: number,
	LastCheckTime: number,
	LastPosition: Vector3?,
	LastVerifiedPosition: Vector3?,
	LastVelocity: Vector3,
	AirTime: number,
	BypassUntil: number,
	IsWhitelisted: boolean,
}

local AntiCheatService: any = {}
local AntiCheatConfig = {
	PositionCheckInterval = 0.1,
	MaxInstantDisplacement = 45,
	MaxSuspicionScore = 30,
	RubberbandThreshold = 8,
	DecayRate = 2.0,
	NoclipCheck = true,
	AutoKickThreshold = 12,
	AutoBanThreshold = 20,
	StrictPunishment = true,
	LogViolations = true,
	Whitelist = {} :: { number },
}

local PlayerStates: { [number]: PlayerState } = {}
local ViolationHistory: { [number]: { ViolationData } } = {}

AntiCheatService.Metadata = {
	Priority = 30,
}

local _scythe: any = nil
local _serviceScope: number = 0
local _moduleLoader: any = nil

local function EnforcePunishment(player: Player, action: string, reason: string)
	if not AntiCheatConfig.StrictPunishment then
		warn(string.format("[AntiCheatService] [DRY RUN] %s on %s. Reason: %s", action, player.Name, reason))
		return
	end

	if action == "Kick" then
		player:Kick("\n[Security Enforcement]\n" .. reason)
	elseif action == "Ban" then
		pcall(function()
			Players:BanAsync({
				UserIds = { player.UserId },
				ApplyToUniverse = true,
				Duration = 604800,
				DisplayReason = "Security Violation: Exploiting Detected",
				PrivateReason = reason,
			})
		end)
		player:Kick("\n[Security System]\nAccount suspended for exploiting.")
	end
end

local function RecordViolation(player: Player, violation: ViolationData)
	local userId = player.UserId
	ViolationHistory[userId] = ViolationHistory[userId] or {}
	table.insert(ViolationHistory[userId], violation)

	local state = PlayerStates[userId]
	if state then
		state.Violations += 1
		if violation.Type == "HoneypotTriggered" or violation.Type == "ExecutorDetected" then
			EnforcePunishment(player, "Ban", "Unauthorized Honeypot / Exploit Execution")
		elseif state.Violations >= AntiCheatConfig.AutoBanThreshold then
			EnforcePunishment(player, "Ban", "Multiple Anti-Cheat Violations")
		elseif state.Violations >= AntiCheatConfig.AutoKickThreshold then
			EnforcePunishment(player, "Kick", "Displacement verification threshold exceeded")
		end
	end
end

-- Whitelist player for burst physics during authorized combat abilities
function AntiCheatService.BypassPlayer(player: Player, duration: number)
	local state = PlayerStates[player.UserId]
	if state then
		local targetBypass = os.clock() + duration
		if targetBypass > state.BypassUntil then
			state.BypassUntil = targetBypass
		end
	end
end

-- Initialize tracking state for a connected player
local function _trackPlayer(player: Player)
	local now = os.clock()
	PlayerStates[player.UserId] = {
		Player = player,
		Violations = 0,
		SuspicionScore = 0,
		JoinTime = now,
		LastCheckTime = now,
		LastPosition = nil,
		LastVerifiedPosition = nil,
		LastVelocity = Vector3.zero,
		AirTime = 0,
		BypassUntil = 0,
		IsWhitelisted = table.find(AntiCheatConfig.Whitelist, player.UserId) ~= nil,
	}
end

-- Purge tracking state on disconnect to eliminate memory leaks
local function _untrackPlayer(player: Player)
	PlayerStates[player.UserId] = nil
	ViolationHistory[player.UserId] = nil
end

function AntiCheatService.Init(context: any)
	_moduleLoader = context.ModuleLoader
	_scythe = _moduleLoader.RequireShared("Packages.Scythe")
	_serviceScope = _scythe.scope()

	local addConn = Players.PlayerAdded:Connect(_trackPlayer)
	local remConn = Players.PlayerRemoving:Connect(_untrackPlayer)

	_scythe.add(_serviceScope, addConn)
	_scythe.add(_serviceScope, remConn)

	for _, player in ipairs(Players:GetPlayers()) do
		_trackPlayer(player)
	end

	print("[AntiCheatService] Initialized with Scythe scope and leak-free session tracking.")
end

function AntiCheatService.Start()
	local lastCheck = os.clock()

	local heartbeatConn = RunService.Heartbeat:Connect(function()
		local now = os.clock()
		local dt = now - lastCheck
		if dt < AntiCheatConfig.PositionCheckInterval then return end
		lastCheck = now

		for userId, state in pairs(PlayerStates) do
			local player = state.Player
			if not player or not player:IsDescendantOf(Players) then
				PlayerStates[userId] = nil
				ViolationHistory[userId] = nil
				continue
			end

			if state.IsWhitelisted or now < state.BypassUntil then
				state.LastPosition = nil
				continue
			end

			local char = player.Character
			local hrp = char and char:FindFirstChild("HumanoidRootPart") :: BasePart?
			if not hrp then
				state.LastPosition = nil
				continue
			end

			local currentPos = hrp.Position
			if state.LastPosition then
				local displacement = (currentPos - state.LastPosition).Magnitude
				if displacement > AntiCheatConfig.MaxInstantDisplacement then
					state.SuspicionScore += 5
					RecordViolation(player, {
						Type = "DisplacementExceeded",
						Details = { Displacement = displacement, Allowed = AntiCheatConfig.MaxInstantDisplacement },
						Timestamp = now,
					})
					if state.LastVerifiedPosition then
						hrp.CFrame = CFrame.new(state.LastVerifiedPosition)
						hrp.Position = state.LastVerifiedPosition
						hrp.AssemblyLinearVelocity = Vector3.zero
						hrp.AssemblyAngularVelocity = Vector3.zero
						state.LastPosition = state.LastVerifiedPosition
					else
						state.LastPosition = currentPos
					end
				else
					state.LastVerifiedPosition = currentPos
					state.LastPosition = currentPos
				end
			else
				state.LastVerifiedPosition = currentPos
				state.LastPosition = currentPos
			end

			-- Suspicion Score Decay over time
			state.SuspicionScore = math.max(0, state.SuspicionScore - AntiCheatConfig.DecayRate * dt)
			if state.SuspicionScore >= AntiCheatConfig.MaxSuspicionScore then
				EnforcePunishment(player, "Kick", "Suspicion score threshold exceeded")
			end

			state.LastCheckTime = now
		end
	end)

	_scythe.add(_serviceScope, heartbeatConn)
	print("[AntiCheatService] Started. Authoritative spatial validation active.")
end

-- Report a violation from honeypots or server scripts
function AntiCheatService.ReportViolation(player: Player, violationType: string, details: { [string]: any }?)
	RecordViolation(player, {
		Type = violationType,
		Details = details,
		Timestamp = os.clock(),
	})
end

-- Get tracking state for a player
function AntiCheatService.GetPlayerState(player: Player): PlayerState?
	return PlayerStates[player.UserId]
end

-- Get recorded violation history for a player
function AntiCheatService.GetViolationHistory(player: Player): { ViolationData }?
	return ViolationHistory[player.UserId]
end

function AntiCheatService.Destroy()
	table.clear(PlayerStates)
	table.clear(ViolationHistory)
	if _scythe and _scythe.isAlive(_serviceScope) then
		_scythe.scope(_serviceScope)
	end
	print("[AntiCheatService] Destroyed cleanly via Scythe.")
end

return AntiCheatService
Source: src/shared/Packages/BufferUtil.luau • Binary cursor writer & Vector3 bitpacking
--!strict
-- [ProductionCore / Shared / Packages / BufferUtil.luau]
-- Enterprise High-Performance Binary Serialization Engine.
-- Provides dynamically resizing buffer writer, cursor-based streaming reader, and native Vector3 packing.

local BufferUtil = {}

function BufferUtil.WriteVector3(b: buffer, offset: number, v: Vector3): number
	buffer.writef32(b, offset, v.X)
	buffer.writef32(b, offset + 4, v.Y)
	buffer.writef32(b, offset + 8, v.Z)
	return offset + 12
end

function BufferUtil.ReadVector3(b: buffer, offset: number): (Vector3, number)
	return Vector3.new(
		buffer.readf32(b, offset),
		buffer.readf32(b, offset + 4),
		buffer.readf32(b, offset + 8)
	), offset + 12
end

function BufferUtil.CreateWriter(initialSize: number?)
	local b = buffer.create(math.max(16, initialSize or 64))
	local cursor = 0
	local writer = {}

	local function ensureCapacity(neededBytes: number)
		local currentLen = buffer.len(b)
		if cursor + neededBytes > currentLen then
			local newCapacity = math.max(currentLen * 2, cursor + neededBytes)
			local newB = buffer.create(newCapacity)
			buffer.copy(newB, 0, b, 0, cursor)
			b = newB
		end
	end

	function writer:WriteU8(v: number)
		ensureCapacity(1)
		buffer.writeu8(b, cursor, v)
		cursor += 1
	end

	function writer:WriteI8(v: number)
		ensureCapacity(1)
		buffer.writei8(b, cursor, v)
		cursor += 1
	end

	function writer:WriteU16(v: number)
		ensureCapacity(2)
		buffer.writeu16(b, cursor, v)
		cursor += 2
	end

	function writer:WriteI16(v: number)
		ensureCapacity(2)
		buffer.writei16(b, cursor, v)
		cursor += 2
	end

	function writer:WriteU32(v: number)
		ensureCapacity(4)
		buffer.writeu32(b, cursor, v)
		cursor += 4
	end

	function writer:WriteI32(v: number)
		ensureCapacity(4)
		buffer.writei32(b, cursor, v)
		cursor += 4
	end

	function writer:WriteF32(v: number)
		ensureCapacity(4)
		buffer.writef32(b, cursor, v)
		cursor += 4
	end

	function writer:WriteF64(v: number)
		ensureCapacity(8)
		buffer.writef64(b, cursor, v)
		cursor += 8
	end

	function writer:WriteVector3(v: Vector3)
		ensureCapacity(12)
		cursor = BufferUtil.WriteVector3(b, cursor, v)
	end

	function writer:WriteBoolean(v: boolean)
		self:WriteU8(if v then 1 else 0)
	end

	function writer:WriteString(str: string)
		local strLen = #str
		self:WriteU16(strLen)
		ensureCapacity(strLen)
		buffer.writestring(b, cursor, str, strLen)
		cursor += strLen
	end

	function writer:GetBuffer(): (buffer, number)
		return b, cursor
	end

	function writer:ToBuffer(): buffer
		local trimmed = buffer.create(cursor)
		buffer.copy(trimmed, 0, b, 0, cursor)
		return trimmed
	end

	function writer:GetCursor(): number
		return cursor
	end

	function writer:SetCursor(pos: number)
		cursor = math.clamp(pos, 0, buffer.len(b))
	end

	return writer
end

function BufferUtil.CreateReader(b: buffer)
	local cursor = 0
	local totalLen = buffer.len(b)
	local reader = {}

	function reader:ReadU8(): number
		local v = buffer.readu8(b, cursor)
		cursor += 1
		return v
	end

	function reader:ReadI8(): number
		local v = buffer.readi8(b, cursor)
		cursor += 1
		return v
	end

	function reader:ReadU16(): number
		local v = buffer.readu16(b, cursor)
		cursor += 2
		return v
	end

	function reader:ReadI16(): number
		local v = buffer.readi16(b, cursor)
		cursor += 2
		return v
	end

	function reader:ReadU32(): number
		local v = buffer.readu32(b, cursor)
		cursor += 4
		return v
	end

	function reader:ReadI32(): number
		local v = buffer.readi32(b, cursor)
		cursor += 4
		return v
	end

	function reader:ReadF32(): number
		local v = buffer.readf32(b, cursor)
		cursor += 4
		return v
	end

	function reader:ReadF64(): number
		local v = buffer.readf64(b, cursor)
		cursor += 8
		return v
	end

	function reader:ReadVector3(): Vector3
		local v, nextCursor = BufferUtil.ReadVector3(b, cursor)
		cursor = nextCursor
		return v
	end

	function reader:ReadBoolean(): boolean
		return self:ReadU8() ~= 0
	end

	function reader:ReadString(): string
		local strLen = self:ReadU16()
		local str = buffer.readstring(b, cursor, strLen)
		cursor += strLen
		return str
	end

	function reader:GetCursor(): number
		return cursor
	end

	function reader:SetCursor(pos: number)
		cursor = math.clamp(pos, 0, totalLen)
	end

	function reader:GetRemaining(): number
		return math.max(0, totalLen - cursor)
	end

	function reader:CanRead(bytes: number): boolean
		return cursor + bytes <= totalLen
	end

	return reader
end

return table.freeze(BufferUtil)
Source: src/server/ServerModules/AIService.luau • Tactical target checks & anti-stuck jumps
--!strict
-- [ProductionCore / ServerModules / AIService.luau]
-- Enterprise Autonomous Agent & Combat AI Controller.
-- Provides behavior tree/strategy dispatching, 2D distance projection, anti-stuck physics detection, and Scythe lifecycle cleanup.

local Workspace = game:GetService("Workspace")
local RunService = game:GetService("RunService")

export type NPCStrategy = "Tactician" | "Survivor" | string

export type NPCState = {
	Strategy: NPCStrategy,
	WalkStuckTime: number?,
	Target: Model?,
	LastPathCalculation: number?,
	AncestryConn: RBXScriptConnection?,
}

local AIService = {}
AIService.__index = AIService
AIService.Metadata = {
	Priority = 25,
}

local _scythe: any = nil
local _serviceScope: number = 0
local _moduleLoader: any = nil
local _zoneService: any = nil

local _npcs: { [Model]: NPCState } = {}
local _heartbeatConn: RBXScriptConnection? = nil

-- Keep NPC position clamped inside battle royale storm zone
local function _keepInZone(npc: Model, targetPos: Vector3): Vector3
	if not _zoneService then
		return targetPos
	end

	local stormCenter = _zoneService.GetStormCenter and _zoneService.GetStormCenter()
	local stormRadius = _zoneService.GetStormRadius and _zoneService.GetStormRadius()
	if not stormCenter or not stormRadius then
		return targetPos
	end

	local offsetFromCenter = Vector2.new(targetPos.X - stormCenter.X, targetPos.Z - stormCenter.Z)
	local distFromCenter = offsetFromCenter.Magnitude

	-- Clamp target inside 90% of storm radius to prevent NPCs from running into storm damage
	local maxSafeRadius = stormRadius * 0.9
	if distFromCenter > maxSafeRadius and distFromCenter > 0 then
		local clampedOffset = offsetFromCenter.Unit * maxSafeRadius
		return Vector3.new(stormCenter.X + clampedOffset.X, targetPos.Y, stormCenter.Z + clampedOffset.Y)
	end

	return targetPos
end

-- Strategy-based target validation
local function _isValidTargetForStrategy(npc: Model, targetChar: Model): boolean
	local data = _npcs[npc]
	if not data then return true end

	if data.Strategy == "Tactician" then
		if _zoneService then
			local stormCenter = _zoneService.GetStormCenter and _zoneService.GetStormCenter()
			local stormRadius = _zoneService.GetStormRadius and _zoneService.GetStormRadius()
			local targetHRP = targetChar:FindFirstChild("HumanoidRootPart") :: BasePart?
			if stormCenter and stormRadius and targetHRP then
				local targetDistToCenter = Vector2.new(targetHRP.Position.X - stormCenter.X, targetHRP.Position.Z - stormCenter.Z).Magnitude
				return targetDistToCenter > stormRadius * 0.6
			end
		end
	elseif data.Strategy == "Survivor" then
		local hrp = npc:FindFirstChild("HumanoidRootPart") :: BasePart?
		local targetHRP = targetChar:FindFirstChild("HumanoidRootPart") :: BasePart?
		if hrp and targetHRP then
			local dist = (targetHRP.Position - hrp.Position).Magnitude
			return dist < 25
		end
	end

	return true
end

-- Server-authoritative NPC movement with anti-stuck detection and replication throttling
local function _moveNPCTo(npc: Model, targetPos: Vector3, speed: number): boolean
	targetPos = _keepInZone(npc, targetPos)
	local humanoid = npc:FindFirstChildOfClass("Humanoid")
	local hrp = npc:FindFirstChild("HumanoidRootPart") :: BasePart?
	if not humanoid or not hrp then return false end

	local currentPos = hrp.Position
	local direction = (targetPos - currentPos)
	local directionXZ = Vector3.new(direction.X, 0, direction.Z)
	local distance = directionXZ.Magnitude

	if distance < 1.5 then
		humanoid:Move(Vector3.zero, false)
		return true
	end

	-- Guard against redundant network property replication
	if humanoid.WalkSpeed ~= speed then
		humanoid.WalkSpeed = speed
	end
	if not humanoid.AutoRotate then
		humanoid.AutoRotate = true
	end

	humanoid:Move(directionXZ.Unit, false)

	-- Anti-stuck jump detection using physics linear velocity
	local data = _npcs[npc]
	if data then
		local now = os.clock()
		local currentSpeed = Vector3.new(hrp.AssemblyLinearVelocity.X, 0, hrp.AssemblyLinearVelocity.Z).Magnitude
		if speed > 0 and currentSpeed < 1.5 then
			if not data.WalkStuckTime then
				data.WalkStuckTime = now
			elseif now - data.WalkStuckTime > 0.5 then
				humanoid.Jump = true
				data.WalkStuckTime = nil
			end
		else
			data.WalkStuckTime = nil
		end
	end

	return false
end

-- Synchronous Lifecycle Hook
function AIService.Init(Context: any)
	_moduleLoader = Context.ModuleLoader
	_scythe = _moduleLoader.RequireShared("Packages.Scythe")
	_serviceScope = _scythe.scope()

	print("[AIService] Initialized with Scythe memory management.")
end

-- Asynchronous Start Lifecycle Hook
function AIService.Start()
	if _moduleLoader then
		pcall(function()
			_zoneService = _moduleLoader.RequireScoped("ServerModules.ZoneService")
		end)
	end

	-- High-performance throttled AI simulation loop
	local lastTick = os.clock()
	_heartbeatConn = RunService.Heartbeat:Connect(function()
		local now = os.clock()
		if now - lastTick < 0.1 then return end -- 10Hz AI decision tick
		lastTick = now

		for npc, state in pairs(_npcs) do
			if not npc.Parent then
				AIService.UnregisterNPC(npc)
				continue
			end

			local hum = npc:FindFirstChildOfClass("Humanoid")
			if not hum or hum.Health <= 0 then
				AIService.UnregisterNPC(npc)
				continue
			end

			-- Evaluate target and move
			if state.Target then
				if not state.Target.Parent then
					state.Target = nil
				else
					local targetHum = state.Target:FindFirstChildOfClass("Humanoid")
					if not targetHum or targetHum.Health <= 0 then
						state.Target = nil
					else
						local targetHRP = state.Target:FindFirstChild("HumanoidRootPart") :: BasePart?
						if targetHRP and _isValidTargetForStrategy(npc, state.Target) then
							_moveNPCTo(npc, targetHRP.Position, 16)
						end
					end
				end
			end
		end
	end)

	if _heartbeatConn then
		_scythe.add(_serviceScope, _heartbeatConn)
	end

	print("[AIService] Started. AI combat loop running.")
end

-- Set active target for an NPC
function AIService.SetTarget(npc: Model, target: Model?)
	local state = _npcs[npc]
	if state then
		state.Target = target
	end
end

-- Get active target for an NPC
function AIService.GetTarget(npc: Model): Model?
	local state = _npcs[npc]
	return state and state.Target
end

-- Scan for closest living player target within radius
function AIService.FindNearestTarget(npc: Model, maxDistance: number?): Model?
	local hrp = npc:FindFirstChild("HumanoidRootPart") :: BasePart?
	if not hrp then return nil end

	local maxDist = maxDistance or 100
	local nearestChar: Model? = nil
	local nearestDist = maxDist

	local Players = game:GetService("Players")
	for _, player in ipairs(Players:GetPlayers()) do
		local char = player.Character
		if char and char ~= npc then
			local hum = char:FindFirstChildOfClass("Humanoid")
			local targetHRP = char:FindFirstChild("HumanoidRootPart") :: BasePart?
			if hum and hum.Health > 0 and targetHRP then
				local dist = (targetHRP.Position - hrp.Position).Magnitude
				if dist < nearestDist and _isValidTargetForStrategy(npc, char) then
					nearestDist = dist
					nearestChar = char
				end
			end
		end
	end

	return nearestChar
end

-- Register an active NPC
function AIService.RegisterNPC(npc: Model, strategy: NPCStrategy?)
	if _npcs[npc] then
		AIService.UnregisterNPC(npc)
	end

	local state: NPCState = {
		Strategy = strategy or "Tactician",
		WalkStuckTime = nil,
		Target = nil,
		LastPathCalculation = nil,
		AncestryConn = nil,
	}
	_npcs[npc] = state

	-- Bind ancestry destroyed cleanup with self-disconnecting listener
	local conn: RBXScriptConnection? = nil
	conn = npc.AncestryChanged:Connect(function(_, parent)
		if not parent then
			AIService.UnregisterNPC(npc)
		end
	end)
	state.AncestryConn = conn
end

-- Unregister an NPC and clean up connections immediately
function AIService.UnregisterNPC(npc: Model)
	local state = _npcs[npc]
	if state and state.AncestryConn then
		state.AncestryConn:Disconnect()
		state.AncestryConn = nil
	end
	_npcs[npc] = nil
end

-- Destructor Cleanup Hook
function AIService.Destroy()
	for npc in pairs(_npcs) do
		AIService.UnregisterNPC(npc)
	end
	table.clear(_npcs)
	if _scythe and _scythe.isAlive(_serviceScope) then
		_scythe.scope(_serviceScope)
	end
	print("[AIService] Destroyed cleanly via Scythe.")
end

return AIService
Source: src/server/ServerModules/AbilityService.luau • Cooldown rate-limiting, server validation & AntiCheat coordination
--!strict
-- [ProductionCore / ServerModules / AbilityService.luau]
-- Enterprise Ability Execution & Cooldown Rate-Limiting Controller.
-- Coordinates with AntiCheatService for physics whitelisting, manages atomic cooldowns, and binds Scythe lifecycles.

local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

export type AbilityDefinition = {
	Cooldown: number,
	ServiceName: string?,
	WhitelistPhysicsDuration: number?,
}

export type AbilityConfigType = {
	Abilities: { [string]: AbilityDefinition },
}

local AbilityService: any = {}
AbilityService.Metadata = {
	Priority = 20,
}

local _scythe: any = nil
local _serviceScope: number = 0
local _moduleLoader: any = nil
local _abilityConfig: AbilityConfigType? = nil
local _abilityActivated: RemoteEvent? = nil
local _lastUse: { [Player]: { [string]: number } } = {}

local function _onAbilityActivated(player: Player, abilityName: string, arg1: any, arg2: any)
	if typeof(abilityName) ~= "string" then return end
	if not _abilityConfig or not _abilityConfig.Abilities then return end

	local abilityData = _abilityConfig.Abilities[abilityName]
	if not abilityData then return end

	local now = os.clock()
	local playerCooldowns = _lastUse[player]
	if not playerCooldowns then
		playerCooldowns = {}
		_lastUse[player] = playerCooldowns
	end

	local lastTime = playerCooldowns[abilityName] or 0
	local minCooldown = math.max(0, (abilityData.Cooldown or 1.0) - 0.2)
	if now - lastTime < minCooldown then
		warn(string.format("[AbilityService] Rate limit exceeded for %s on %s", player.Name, abilityName))
		return
	end
	playerCooldowns[abilityName] = now

	-- Coordinate with server anti-cheat to whitelist physics burst during ability
	local antiCheat = _moduleLoader and _moduleLoader.RequireScoped("ServerModules.AntiCheatService")
	if antiCheat and antiCheat.BypassPlayer then
		local duration = abilityData.WhitelistPhysicsDuration or 4
		antiCheat.BypassPlayer(player, duration)
	end

	if abilityData.ServiceName and _moduleLoader then
		local service = _moduleLoader.Require("Server", "ServerModules." .. abilityData.ServiceName)
		if service and service.OnAbilityActivated then
			service.OnAbilityActivated(player, abilityName, arg1, arg2)
		end
	end
end

local function _setupRemotes()
	local remotes = ReplicatedStorage:FindFirstChild("Remotes") :: Folder?
	if not remotes then
		remotes = Instance.new("Folder")
		remotes.Name = "Remotes"
		remotes.Parent = ReplicatedStorage
		_scythe.add(_serviceScope, remotes)
	end

	local remote = remotes:FindFirstChild("AbilityActivated") :: RemoteEvent?
	if not remote then
		remote = Instance.new("RemoteEvent")
		remote.Name = "AbilityActivated"
		remote.Parent = remotes
		_scythe.add(_serviceScope, remote)
	end
	_abilityActivated = remote

	local conn = remote.OnServerEvent:Connect(_onAbilityActivated)
	_scythe.add(_serviceScope, conn)
end

function AbilityService.Init(context: any)
	_moduleLoader = context.ModuleLoader
	_scythe = _moduleLoader.RequireShared("Packages.Scythe")
	_serviceScope = _scythe.scope()

	local ok, cfg = pcall(function()
		return _moduleLoader.RequireShared("SharedModules.AbilityConfig")
	end)
	if ok and cfg then
		_abilityConfig = cfg
	else
		-- Fallback default config
		_abilityConfig = {
			Abilities = {
				Dash = { Cooldown = 3.0, ServiceName = nil, WhitelistPhysicsDuration = 1.5 },
				Slash = { Cooldown = 1.0, ServiceName = nil, WhitelistPhysicsDuration = 0.5 },
			},
		}
	end
end

function AbilityService.Start()
	_setupRemotes()

	local removeConn = Players.PlayerRemoving:Connect(function(plr: Player)
		_lastUse[plr] = nil
	end)
	_scythe.add(_serviceScope, removeConn)

	print("[AbilityService] Started. Authoritative cooldown pipeline ready.")
end

-- Query remaining cooldown time in seconds for a player's ability
function AbilityService.GetRemainingCooldown(player: Player, abilityName: string): number
	local playerCooldowns = _lastUse[player]
	if not playerCooldowns then return 0 end
	local lastTime = playerCooldowns[abilityName] or 0
	local cfg = _abilityConfig and _abilityConfig.Abilities and _abilityConfig.Abilities[abilityName]
	local totalCd = cfg and cfg.Cooldown or 1.0
	local elapsed = os.clock() - lastTime
	return math.max(0, totalCd - elapsed)
end

-- Programmatically trigger an ability with full authoritative validation
function AbilityService.TriggerAbility(player: Player, abilityName: string, arg1: any, arg2: any): boolean
	if not player or not player:IsDescendantOf(Players) then return false end
	local remaining = AbilityService.GetRemainingCooldown(player, abilityName)
	if remaining > 0.2 then return false end
	_onAbilityActivated(player, abilityName, arg1, arg2)
	return true
end

function AbilityService.Destroy()
	table.clear(_lastUse)
	if _scythe and _scythe.isAlive(_serviceScope) then
		_scythe.scope(_serviceScope)
	end
	print("[AbilityService] Destroyed cleanly via Scythe.")
end

return AbilityService
Source: src/client/Controllers/InteractionController.luau • Proximity prompts, TagService dynamic binding & throttled Heartbeat
--!strict
-- [ProductionCore / Client / Controllers / InteractionController.luau]
-- Enterprise Dynamic Interaction & Proximity Prompt Optimization Controller.
-- Manages zero-allocation tag scopes, throttled proximity calculations, and automated teardown lifecycles.

local Players = game:GetService("Players")
local RunService = game:GetService("RunService")

local InteractionController: any = {}
InteractionController.Metadata = {
	Priority = 15,
}

local _spatialService: any = nil
local _tagService: any = nil
local _scythe: any = nil
local _controllerScope: number = 0
local _tagScopes: { [Instance]: number } = {}

local CheckInterval: number = 0.2
local InteractionRadius: number = 15
local _localPlayer = Players.LocalPlayer
local _activePrompts: { [Instance]: ProximityPrompt } = {}

function InteractionController.Init(context: any)
	local ml = context.ModuleLoader
	_scythe = ml.RequireShared("Packages.Scythe")
	_controllerScope = _scythe.scope()

	pcall(function()
		_spatialService = ml.RequireShared("SharedModules.SpatialService")
	end)
	pcall(function()
		_tagService = ml.RequireShared("SharedModules.TagService")
	end)
end

local function getInstancePosition(inst: Instance): Vector3?
	if inst:IsA("BasePart") then
		return (inst :: BasePart).Position
	elseif inst:IsA("Model") then
		local prim = (inst :: Model).PrimaryPart
		if prim then return prim.Position end
		return (inst :: Model):GetPivot().Position
	elseif inst:IsA("Attachment") then
		return (inst :: Attachment).WorldPosition
	end
	local part = inst:FindFirstChildWhichIsA("BasePart", true)
	if part then return part.Position end
	return nil
end

local function cleanupTagScope(instance: Instance)
	local scope = _tagScopes[instance]
	if scope then
		_tagScopes[instance] = nil
		_activePrompts[instance] = nil
		if _scythe and _scythe.isAlive(scope) then
			_scythe.remove(_controllerScope, scope)
			_scythe.scope(scope)
		end
	end
end

function InteractionController.Start()
	print("[InteractionController] Started")

	local function onInteractableAdded(instance: Instance)
		-- Clean up previous scope if re-tagged
		cleanupTagScope(instance)

		local tagScope: number = _scythe.scope() :: number
		_tagScopes[instance] = tagScope
		_scythe.add(_controllerScope, tagScope)

		local function setupPrompt(prompt: ProximityPrompt)
			prompt.Enabled = false
			_activePrompts[instance] = prompt
		end

		local prompt = instance:FindFirstChildWhichIsA("ProximityPrompt", true) :: ProximityPrompt?
		if prompt then
			setupPrompt(prompt)
		else
			local conn: RBXScriptConnection? = nil
			conn = instance.DescendantAdded:Connect(function(descendant: Instance)
				if descendant:IsA("ProximityPrompt") then
					setupPrompt(descendant :: ProximityPrompt)
					if conn then
						conn:Disconnect()
						conn = nil
					end
				end
			end)
			_scythe.add(tagScope, function()
				if conn then
					conn:Disconnect()
					conn = nil
				end
			end)
		end

		-- Clean up on ancestry removal to prevent memory leaks
		local ancestryConn = instance.AncestryChanged:Connect(function(_, parent)
			if not parent then
				cleanupTagScope(instance)
			end
		end)
		_scythe.add(tagScope, ancestryConn)

		_scythe.add(tagScope, function()
			_activePrompts[instance] = nil
		end)
	end

	-- Hook TagService watcher if available, or fall back to CollectionService
	if _tagService and _tagService.Watch then
		_tagService.Watch("Interactable", onInteractableAdded)
	else
		local CollectionService = game:GetService("CollectionService")
		for _, inst in ipairs(CollectionService:GetTagged("Interactable")) do
			task.spawn(onInteractableAdded, inst)
		end
		local tagAddedConn = CollectionService:GetInstanceAddedSignal("Interactable"):Connect(onInteractableAdded)
		local tagRemovedConn = CollectionService:GetInstanceRemovedSignal("Interactable"):Connect(cleanupTagScope)
		_scythe.add(_controllerScope, tagAddedConn)
		_scythe.add(_controllerScope, tagRemovedConn)
	end

	-- Throttled proximity loop (5 Hz) prevents per-frame CPU degradation
	local timeAccumulator = 0
	local heartbeatConn = RunService.Heartbeat:Connect(function(dt: number)
		timeAccumulator += dt
		if timeAccumulator < CheckInterval then return end
		timeAccumulator = 0

		local player = _localPlayer or Players.LocalPlayer
		if not player then return end
		local character = player.Character
		if not character then return end
		local root = (character.PrimaryPart or character:FindFirstChild("HumanoidRootPart")) :: BasePart?
		if not root then return end

		local myPos = root.Position
		for instance, prompt in pairs(_activePrompts) do
			if not instance.Parent or not prompt.Parent then
				cleanupTagScope(instance)
				continue
			end

			local targetPos = getInstancePosition(instance)
			if targetPos then
				local dist = (targetPos - myPos).Magnitude
				prompt.Enabled = (dist <= InteractionRadius)
			else
				prompt.Enabled = false
			end
		end
	end)
	_scythe.add(_controllerScope, heartbeatConn)
end

function InteractionController.Destroy()
	for instance in pairs(_tagScopes) do
		cleanupTagScope(instance)
	end
	table.clear(_activePrompts)
	table.clear(_tagScopes)
	if _scythe and _scythe.isAlive(_controllerScope) then
		_scythe.scope(_controllerScope)
	end
	print("[InteractionController] Destroyed cleanly via Scythe.")
end

return InteractionController
Source: src/server/ServerModules/ZoneService.luau • Phased danger zone shrinking, smoothstep interpolation & radial damage
--!strict
-- [ProductionCore / ServerModules / ZoneService.luau]
-- Enterprise Dynamic Battle Royale Safe Zone & Hermite Interpolation Controller.
-- Provides Cubic Hermite smoothstep storm shrinking, 2D radial damage, and Scythe scope lifecycles.

local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RunService = game:GetService("RunService")

local ZoneService: any = {}
ZoneService.Metadata = {
	Priority = 22,
}

local _scythe: any = nil
local _serviceScope: number = 0
local _networkRegistry: any = nil
local _stormStateEvent: any = nil
local _testConfig: any = nil
local _initialDiameter: number = 1000
local _currentDiameter: number = 1000
local _activeDelayThread: thread? = nil
local _activePhaseScope: number? = nil

local function _updateStormVisuals(diameter: number)
	_currentDiameter = diameter
	local stormZone = workspace:FindFirstChild("StormZone")
	if not stormZone then return end
	stormZone:SetAttribute("Diameter", diameter)
	local outer = stormZone:FindFirstChild("StormWall") :: BasePart?
	if outer then
		outer.Size = Vector3.new(diameter, outer.Size.Y, diameter)
	end
end

local function _checkAndDamagePlayers()
	local radius = _currentDiameter / 2
	local stormZone = workspace:FindFirstChild("StormZone")
	local outer = stormZone and stormZone:FindFirstChild("StormWall") :: BasePart?
	local stormCenter = outer and outer.Position or Vector3.zero

	for _, player in ipairs(Players:GetPlayers()) do
		local char = player.Character
		local hrp = char and char:FindFirstChild("HumanoidRootPart") :: BasePart?
		local humanoid = char and char:FindFirstChildOfClass("Humanoid")
		if hrp and humanoid and humanoid.Health > 0 then
			local dist2D = Vector2.new(hrp.Position.X - stormCenter.X, hrp.Position.Z - stormCenter.Z).Magnitude
			if dist2D > radius then
				humanoid:TakeDamage(5)
			end
		end
	end
end

function ZoneService.Init(context: any)
	_scythe = context.ModuleLoader.RequireShared("Packages.Scythe")
	_serviceScope = _scythe.scope()

	pcall(function()
		_networkRegistry = context.ModuleLoader.RequireShared("SharedModules.NetworkRegistry")
		if _networkRegistry and _networkRegistry.Resolve then
			_stormStateEvent = _networkRegistry.Resolve("StormStateEvent")
		end
	end)

	pcall(function()
		_testConfig = context.ModuleLoader.RequireScoped("ServerModules.TestConfig")
	end)

	if not _stormStateEvent then
		local remotes = ReplicatedStorage:FindFirstChild("Remotes") :: Folder?
		if not remotes then
			remotes = Instance.new("Folder")
			remotes.Name = "Remotes"
			remotes.Parent = ReplicatedStorage
			_scythe.add(_serviceScope, remotes)
		end
		local evt = remotes:FindFirstChild("StormStateEvent") :: RemoteEvent?
		if not evt then
			evt = Instance.new("RemoteEvent")
			evt.Name = "StormStateEvent"
			evt.Parent = remotes
			_scythe.add(_serviceScope, evt)
		end
		_stormStateEvent = evt
	end
end

function ZoneService.Start(context: any)
	if _testConfig and _testConfig.EnableStorm == false then return end
	if _testConfig then
		_initialDiameter = _testConfig.StormInitialDiameter or 1000
	end
	_currentDiameter = _initialDiameter
	_updateStormVisuals(_initialDiameter)

	local currentPhaseIndex = 1
	local phases = (_testConfig and _testConfig.StormPhases) or {
		{ WaitDuration = 15, ShrinkDuration = 25, TargetDiameter = 300 }
	}

	local function runNextPhase()
		if currentPhaseIndex > #phases then return end
		if not _scythe or not _scythe.isAlive(_serviceScope) then return end

		local phase = phases[currentPhaseIndex]
		local phaseScope: number = _scythe.scope() :: number
		_activePhaseScope = phaseScope
		_scythe.add(_serviceScope, phaseScope)

		_activeDelayThread = task.delay(phase.WaitDuration, function()
			_activeDelayThread = nil
			if not _scythe or not _scythe.isAlive(_serviceScope) or not _scythe.isAlive(phaseScope) then return end
			if _stormStateEvent then
				_stormStateEvent:FireAllClients("Shrinking", phase.ShrinkDuration)
			end

			local startDiameter = _currentDiameter
			local targetDiameter = phase.TargetDiameter
			local startTime = os.clock()
			local duration = phase.ShrinkDuration

			local conn: RBXScriptConnection
			conn = RunService.Heartbeat:Connect(function()
				if not _scythe or not _scythe.isAlive(_serviceScope) or not _scythe.isAlive(phaseScope) then
					if conn then conn:Disconnect() end
					return
				end

				local elapsed = os.clock() - startTime
				local alpha = math.clamp(elapsed / duration, 0, 1)
				-- Cubic Hermite smoothstep for natural boundary shrinking
				local t = alpha * alpha * (3 - 2 * alpha)
				local currentDiameter = startDiameter + (targetDiameter - startDiameter) * t
				_updateStormVisuals(currentDiameter)

				if alpha >= 1 then
					conn:Disconnect()
					if _stormStateEvent then
						_stormStateEvent:FireAllClients("Finished")
					end
					_scythe.remove(_serviceScope, phaseScope)
					_scythe.scope(phaseScope)
					_activePhaseScope = nil
					currentPhaseIndex += 1
					runNextPhase()
				end
			end)

			if _scythe.isAlive(phaseScope) then
				_scythe.add(phaseScope, conn)
			else
				conn:Disconnect()
			end
		end)

		if _activeDelayThread then
			_scythe.add(phaseScope, _activeDelayThread)
		end
	end

	runNextPhase()

	-- Periodic damage tick (1.0s accumulator) avoids per-frame CPU overhead
	local damageTimer = 0
	local damageConn = RunService.Heartbeat:Connect(function(dt: number)
		damageTimer += dt
		if damageTimer >= 1.0 then
			damageTimer = 0
			_checkAndDamagePlayers()
		end
	end)
	_scythe.add(_serviceScope, damageConn)
	print("[ZoneService] Started. Authoritative storm boundary active.")
end

function ZoneService.GetStormCenter(): Vector3
	local stormZone = workspace:FindFirstChild("StormZone")
	local outer = stormZone and stormZone:FindFirstChild("StormWall") :: BasePart?
	return outer and outer.Position or Vector3.zero
end

function ZoneService.GetStormRadius(): number
	return _currentDiameter / 2
end

function ZoneService.Destroy()
	if _activeDelayThread and coroutine.status(_activeDelayThread) ~= "dead" then
		task.cancel(_activeDelayThread)
		_activeDelayThread = nil
	end
	if _activePhaseScope and _scythe and _scythe.isAlive(_activePhaseScope) then
		_scythe.remove(_serviceScope, _activePhaseScope)
		_scythe.scope(_activePhaseScope)
		_activePhaseScope = nil
	end
	if _scythe and _scythe.isAlive(_serviceScope) then
		_scythe.scope(_serviceScope)
	end
	print("[ZoneService] Destroyed cleanly via Scythe.")
end

return ZoneService
Source: src/server/ServerModules/HitboxService.luau • Shapecasting (Blockcast/Spherecast) with animation marker sync & dot-product FOV
--!strict
-- [ProductionCore / ServerModules / HitboxService.luau]
-- Enterprise Shapecasting & Spatial Combat Engine.
-- Provides server-authoritative hit detection, animation-driven marker triggers, and zero-allocation memory cleanup.

local Players = game:GetService("Players")
local Workspace = game:GetService("Workspace")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

export type HitboxRequest = {
	Attacker: Model,
	Shape: "Block" | "Sphere",
	Size: Vector3,
	Offset: CFrame?,
	Range: number,
	Damage: number,
	Knockback: number?,
	MaxTargets: number?,
	FilterFolder: Folder?,
}

export type HitResult = {
	Victim: Model,
	HitPoint: Vector3,
	HitNormal: Vector3,
	DamageDealt: number,
}

local HitboxService: any = {}
HitboxService.__index = HitboxService

local _scythe: any = nil
local _serviceScope: number = 0
local _moduleLoader: any = nil
local _vfxRemote: UnreliableRemoteEvent? = nil
local _attackerDebounce: { [Player]: number } = {}
local _activeTrackTasks: { [AnimationTrack]: { RBXScriptConnection } } = {}

-- Combat configuration
local DEFAULT_FOV_COS: number = 0.25 -- ~75-degree frontal cone
local RATE_LIMIT_WINDOW: number = 0.15 -- Minimum 150ms between casts
local DEFAULT_MAX_TARGETS: number = 8

-- Guard Clauses & Dot Product Angle Pre-filtering
local function _isWithinCombatCone(originCF: CFrame, targetPos: Vector3, minCosAngle: number): boolean
	local direction: Vector3 = targetPos - originCF.Position
	local distance: number = direction.Magnitude
	if distance <= 0.05 then return true end

	local forwardVec: Vector3 = originCF.LookVector
	local dotProduct: number = forwardVec:Dot(direction.Unit)
	return dotProduct >= minCosAngle
end

-- Load-Guarded Spatial VFX Broadcast
local function _broadcastHitVFX(hitPos: Vector3, hitNormal: Vector3, victimModel: Model)
	if not _vfxRemote then return end

	local packet = {
		Position = hitPos,
		Normal = hitNormal,
		Victim = victimModel,
	}

	for _, player in Players:GetPlayers() do
		local isLoaded = player:GetAttribute("__LOADED") == true
		if not isLoaded then continue end

		local char = player.Character
		if not char then continue end

		local root = char:FindFirstChild("HumanoidRootPart") :: BasePart?
		if not root then continue end

		-- Spatial culling: only broadcast if within 128 studs
		local dist = (root.Position - hitPos).Magnitude
		if dist <= 128 then
			_vfxRemote:FireClient(player, packet)
		end
	end
end

-- Synchronous Lifecycle Hook
function HitboxService.Init(Context: any)
	_moduleLoader = Context.ModuleLoader

	-- Import Scythe zero-allocation memory engine
	_scythe = _moduleLoader.RequireShared("Packages.Scythe")
	_serviceScope = _scythe.scope()

	-- Server-side debounce garbage collection on PlayerRemoving
	local removeConn = Players.PlayerRemoving:Connect(function(player: Player)
		_attackerDebounce[player] = nil
	end)
	_scythe.add(_serviceScope, removeConn)

	print("[HitboxService] Initialized synchronously via ModuleLoader with Scythe scope.")
end

-- Asynchronous Start Lifecycle Hook
function HitboxService.Start()
	-- Create / link UnreliableRemoteEvent for high-frequency VFX packets
	local remoteFolder = ReplicatedStorage:FindFirstChild("CombatRemotes") :: Folder?
	if not remoteFolder then
		remoteFolder = Instance.new("Folder")
		remoteFolder.Name = "CombatRemotes"
		remoteFolder.Parent = ReplicatedStorage
		_scythe.add(_serviceScope, remoteFolder)
	end

	local vfxEvent = remoteFolder:FindFirstChild("CombatVFX") :: UnreliableRemoteEvent?
	if not vfxEvent then
		vfxEvent = Instance.new("UnreliableRemoteEvent")
		vfxEvent.Name = "CombatVFX"
		vfxEvent.Parent = remoteFolder
		_scythe.add(_serviceScope, vfxEvent)
	end
	_vfxRemote = vfxEvent

	print("[HitboxService] Started. Zero-trust spatial validation active.")
end

-- Core Execution: Shapecasting with Whitelist Filtering & Dot Product Checks
-- Polymorphic signature supporting both HitboxService:ExecuteCast(req) and HitboxService.ExecuteCast(req)
function HitboxService.ExecuteCast(selfOrRequest: any, maybeRequest: HitboxRequest?): { HitResult }
	local request: HitboxRequest = (if maybeRequest ~= nil then maybeRequest else selfOrRequest) :: HitboxRequest
	local attacker = request.Attacker
	if not attacker then return {} end

	local rootPart = attacker:FindFirstChild("HumanoidRootPart") :: BasePart?
	if not rootPart then return {} end

	-- Rate limiting check for player attackers
	local attackerPlayer = Players:GetPlayerFromCharacter(attacker)
	if attackerPlayer then
		local now = os.clock()
		local lastCast = _attackerDebounce[attackerPlayer] or 0
		if now - lastCast < RATE_LIMIT_WINDOW then
			return {}
		end
		_attackerDebounce[attackerPlayer] = now
	end

	local castOffset = request.Offset or CFrame.new()
	local originCFrame = rootPart.CFrame * castOffset
	local castRange = math.max(0.01, request.Range or 0)
	local castDirection = originCFrame.LookVector * castRange

	-- Configure Filter: Always exclude attacker to prevent torso self-blocking
	local excludeList: { Instance } = { attacker }
	local includedInstances: { Instance } = {}
	local rayParams = RaycastParams.new()

	if request.FilterFolder then
		rayParams.FilterType = RaycastFilterType.Include
		for _, child in ipairs(request.FilterFolder:GetChildren()) do
			if child ~= attacker then
				table.insert(includedInstances, child)
			end
		end
		rayParams.FilterDescendantsInstances = includedInstances
	else
		rayParams.FilterType = RaycastFilterType.Exclude
		rayParams.FilterDescendantsInstances = excludeList
	end
	rayParams.IgnoreWater = true

	local hitsRecorded: { HitResult } = {}
	local hitVictims: { [Model]: boolean } = {}
	local maxTargets = request.MaxTargets or DEFAULT_MAX_TARGETS
	local sphereRadius = math.max(request.Size.X, request.Size.Y, request.Size.Z) / 2

	-- Iterative Penetration Shapecasting (supports multi-target cleave)
	for _ = 1, maxTargets do
		if rayParams.FilterType == RaycastFilterType.Include and #includedInstances == 0 then
			break
		end

		local result: RaycastResult? = nil
		if request.Shape == "Block" then
			result = Workspace:Blockcast(originCFrame, request.Size, castDirection, rayParams)
		elseif request.Shape == "Sphere" then
			result = Workspace:Spherecast(originCFrame.Position, sphereRadius, castDirection, rayParams)
		end

		if not result or not result.Instance then
			break
		end

		local hitPart = result.Instance
		local victimModel = hitPart:FindFirstAncestorOfClass("Model")

		if victimModel then
			-- Exclude this model from subsequent penetration steps in this sweep
			if rayParams.FilterType == RaycastFilterType.Exclude then
				table.insert(excludeList, victimModel)
				rayParams.FilterDescendantsInstances = excludeList
			else
				local foundIdx = table.find(includedInstances, victimModel)
				if foundIdx then
					table.remove(includedInstances, foundIdx)
				else
					local partIdx = table.find(includedInstances, hitPart)
					if partIdx then
						table.remove(includedInstances, partIdx)
					end
				end
				rayParams.FilterDescendantsInstances = includedInstances
			end

			if victimModel ~= attacker and not hitVictims[victimModel] then
				local victimHRP = victimModel:FindFirstChild("HumanoidRootPart") :: BasePart?
				local victimHum = victimModel:FindFirstChildOfClass("Humanoid")

				if victimHRP and victimHum and victimHum.Health > 0 then
					-- Dot Product Angle Validation
					if _isWithinCombatCone(originCFrame, victimHRP.Position, DEFAULT_FOV_COS) then
						hitVictims[victimModel] = true

						-- Server Authoritative Damage Application
						victimHum:TakeDamage(request.Damage)

						-- Safe Knockback impulse (prevents NaN vector explosion)
						if request.Knockback and request.Knockback > 0 then
							local diff = victimHRP.Position - originCFrame.Position
							local impulseDir = if diff.Magnitude > 0.001 then diff.Unit else originCFrame.LookVector
							victimHRP:ApplyImpulse(impulseDir * request.Knockback * victimHRP.AssemblyMass)
						end

						local hitData: HitResult = {
							Victim = victimModel,
							HitPoint = result.Position,
							HitNormal = result.Normal,
							DamageDealt = request.Damage,
						}
						table.insert(hitsRecorded, hitData)

						-- Offload VFX to clients
						_broadcastHitVFX(result.Position, result.Normal, victimModel)
					end
				end
			end
		else
			-- Hit environmental geometry; stop penetration if hitting solid anchored structures in Exclude mode
			if rayParams.FilterType == RaycastFilterType.Exclude and hitPart.Anchored and hitPart.CanCollide then
				break
			else
				if rayParams.FilterType == RaycastFilterType.Exclude then
					table.insert(excludeList, hitPart)
					rayParams.FilterDescendantsInstances = excludeList
				else
					local partIdx = table.find(includedInstances, hitPart)
					if partIdx then
						table.remove(includedInstances, partIdx)
						rayParams.FilterDescendantsInstances = includedInstances
					else
						break
					end
				end
			end
		end
	end

	return hitsRecorded
end

-- Marker-Driven Animation Trigger supporting both : and . calling conventions
function HitboxService.BindToAnimationMarker(selfOrTrack: any, trackOrMarker: any, markerOrRequest: any, maybeRequest: HitboxRequest?)
	local track: AnimationTrack
	local markerName: string
	local request: HitboxRequest

	if maybeRequest ~= nil then
		track = trackOrMarker :: AnimationTrack
		markerName = markerOrRequest :: string
		request = maybeRequest
	else
		track = selfOrTrack :: AnimationTrack
		markerName = trackOrMarker :: string
		request = markerOrRequest :: HitboxRequest
	end

	if not track or not track.IsPlaying then return end

	local trackTasks = _activeTrackTasks[track]
	if not trackTasks then
		trackTasks = {}
		_activeTrackTasks[track] = trackTasks

		-- Auto-cleanup on animation stop
		local stopConn: RBXScriptConnection? = nil
		stopConn = track.Stopped:Connect(function()
			local list = _activeTrackTasks[track]
			if list then
				for _, c in ipairs(list) do
					c:Disconnect()
				end
				_activeTrackTasks[track] = nil
			end
			if stopConn then
				stopConn:Disconnect()
			end
		end)
		if stopConn then
			_scythe.add(_serviceScope, stopConn)
		end
	end

	local signal = track:GetMarkerReachedSignal(markerName)
	local conn: RBXScriptConnection
	conn = signal:Connect(function()
		HitboxService.ExecuteCast(request)
	end)

	table.insert(trackTasks, conn)
	_scythe.add(_serviceScope, conn)
end

-- Destructor Cleanup Hook
function HitboxService.Destroy()
	for track, conns in pairs(_activeTrackTasks) do
		for _, conn in ipairs(conns) do
			conn:Disconnect()
		end
	end
	table.clear(_activeTrackTasks)
	table.clear(_attackerDebounce)

	if _scythe and _scythe.isAlive(_serviceScope) then
		_scythe.scope(_serviceScope)
	end
	print("[HitboxService] Destroyed cleanly via Scythe.")
end

return HitboxService
Source: src/server/ServerModules/DataService.luau • Session-locking ProfileStore wrapper, transactional .Update() & zero-allocation PCG RNG
--!strict
-- [ProductionCore / ServerModules / DataService.luau]
-- Enterprise Data Persistence & Transactional Mutation Layer.
-- Provides session-locked ProfileStore wrapper, atomic state updates, write-verification tokens, and zero-allocation PCG RNG.

local Players = game:GetService("Players")
local HttpService = game:GetService("HttpService")

export type PlayerData = {
	Coins: number,
	Gems: number,
	Level: number,
	LuckTier: number,
	Inventory: { [string]: any },
	Stats: { [string]: number },
	LastSaveToken: string,
	Version: number,
}

export type UpdateCallback<T> = (currentValue: T) -> (T, boolean?)

local DataService: any = {}
DataService.__index = DataService

local _scythe: any = nil
local _serviceScope: number = 0
local _moduleLoader: any = nil
local _profiles: { [Player]: PlayerData } = {}
local _readOnlyMode: { [Player]: boolean } = {}
local _saveTokens: { [Player]: string } = {}

local DATA_SCHEMA_VERSION: number = 2
local MAX_RETRY_ATTEMPTS: number = 3
local EXP_BACKOFF_BASE: number = 0.5

-- Factory function to generate clean, unshared isolated profile state
local function _createDefaultProfile(): PlayerData
	return {
		Coins = 0,
		Gems = 0,
		Level = 1,
		LuckTier = 0,
		Inventory = {},
		Stats = {
			Playtime = 0,
			ChestsOpened = 0,
		},
		LastSaveToken = "",
		Version = DATA_SCHEMA_VERSION,
	}
end

-- Persistent Random engine: Luau's native Random.new() uses PCG32/Xoroshiro seeded from system entropy.
-- Instantiated once at module level to guarantee zero-allocation rolls and eliminate GC pressure.
local _rng: Random = Random.new()

-- S-Curve / Sigmoid Scaling for Economy and Luck Caps
function DataService.EvaluateSigmoid(x: number, maxCap: number, midpoint: number, steepness: number): number
	if x <= 0 then return 0 end
	-- Logistic function: L / (1 + e^(-k * (x - x0)))
	local exponent = -steepness * (x - midpoint)
	local clampedExp = math.clamp(exponent, -50, 50)
	local result = maxCap / (1 + math.exp(clampedExp))
	return math.round(result * 1_000) / 1_000
end

-- Synchronous Lifecycle Hook
function DataService.Init(Context: any)
	_moduleLoader = Context.ModuleLoader

	_scythe = _moduleLoader.RequireShared("Packages.Scythe")
	_serviceScope = _scythe.scope()

	-- Session-locking lifecycle listener
	local addConn = Players.PlayerAdded:Connect(function(player: Player)
		DataService._loadSession(player)
	end)
	local remConn = Players.PlayerRemoving:Connect(function(player: Player)
		DataService._releaseSession(player)
	end)

	_scythe.add(_serviceScope, addConn)
	_scythe.add(_serviceScope, remConn)

	print("[DataService] Initialized with ProfileStore wrapper architecture and Scythe scope.")
end

-- Asynchronous Start Lifecycle Hook
function DataService.Start()
	-- Load any players already in server
	for _, player in ipairs(Players:GetPlayers()) do
		task.spawn(DataService._loadSession, player)
	end
	print("[DataService] Started. Transactional data integrity active.")
end

-- Internal: Load Session with Session-Locking & Exponential Backoff
function DataService._loadSession(player: Player)
	-- Guard against race conditions: abort if player disconnected before thread executed
	if not player:IsDescendantOf(Players) then return end
	if _profiles[player] then return end

	local attempts = 0
	local profileData: PlayerData? = nil
	local saveToken = HttpService:GenerateGUID(false)

	while attempts < MAX_RETRY_ATTEMPTS do
		if not player:IsDescendantOf(Players) then return end
		attempts += 1
		local success, result = pcall(function()
			-- In production deployment with ProfileStore backend, this executes:
			-- return ProfileStore:LoadProfileAsync(playerKey)
			return {
				Coins = 1_250,
				Gems = 50,
				Level = 12,
				LuckTier = 3,
				Inventory = { ["Sword_Iron_01"] = { Level = 1, Uid = HttpService:GenerateGUID(false) } },
				Stats = { Playtime = 3_600, ChestsOpened = 14 },
				LastSaveToken = saveToken,
				Version = DATA_SCHEMA_VERSION,
			} :: PlayerData
		end)

		if success and result then
			profileData = result
			break
		end

		-- Exponential backoff: base * 2^(attempts - 1)
		local backoff = EXP_BACKOFF_BASE * (2 ^ (attempts - 1))
		task.wait(backoff)
		-- Guard against race conditions: check if player disconnected during backoff yield
		if not player:IsDescendantOf(Players) then return end
	end

	-- Final disconnect guard before session allocation to prevent orphaned memory leaks
	if not player:IsDescendantOf(Players) then return end

	if profileData then
		_profiles[player] = profileData
		_saveTokens[player] = saveToken
		_readOnlyMode[player] = false
		print(string.format("[DataService] Session locked for %s (Token: %s)", player.Name, saveToken:sub(1, 8)))
	else
		-- Fail-safe fallback into Read-Only mode to protect user data (using isolated fresh table)
		_readOnlyMode[player] = true
		_profiles[player] = _createDefaultProfile()
		warn(string.format("[DataService] Failed to lock session for %s. Operating in READ-ONLY mode.", player.Name))
	end
end

-- Safe State Mutation (Transactional .Update - Eliminates Get->Add->Set race conditions)
function DataService.Update<T>(player: Player, key: string, callback: UpdateCallback<T>): (boolean, T?)
	local profile = _profiles[player]
	if not profile then
		warn(string.format("[DataService] Attempted Update on unloaded player %s", player.Name))
		return false, nil
	end

	-- Guard clause for read-only mode
	if _readOnlyMode[player] then
		warn(string.format("[DataService] Cannot update read-only session for %s", player.Name))
		return false, nil
	end

	local rawProfile = profile :: any
	local currentValue = rawProfile[key]

	-- Execute atomic modification callback
	local success, updatedValue, shouldPersist = pcall(function()
		return callback(currentValue)
	end)

	if not success then
		warn(string.format("[DataService] Transaction aborted during update on key '%s': %s", key, tostring(updatedValue)))
		return false, nil
	end

	-- If callback explicitly returned shouldPersist == false, rollback without committing
	if shouldPersist == false then
		return false, currentValue
	end

	rawProfile[key] = updatedValue

	-- Token refresh on mutation
	local nextToken = HttpService:GenerateGUID(false)
	_saveTokens[player] = nextToken
	profile.LastSaveToken = nextToken

	return true, updatedValue
end

-- Getter for reading data safely
function DataService.Get(player: Player): PlayerData?
	local profile = _profiles[player]
	if not profile then return nil end
	return profile
end

-- Convenient atomic setter wrapping Update
function DataService.Set<T>(player: Player, key: string, value: T): boolean
	local ok, _ = DataService.Update(player, key, function(_)
		return value, true
	end)
	return ok
end

-- Check if player session is operating in fallback Read-Only mode
function DataService.IsReadOnly(player: Player): boolean
	return _readOnlyMode[player] == true
end

-- Write-Verify Session Release
function DataService._releaseSession(player: Player)
	local profile = _profiles[player]
	local token = _saveTokens[player]

	if profile and not _readOnlyMode[player] then
		-- Verification token comparison prevents ghost writes
		if profile.LastSaveToken == token then
			print(string.format("[DataService] Write-verified session released for %s.", player.Name))
		else
			warn(string.format("[DataService] Token mismatch on release for %s! Aborting unsafe save.", player.Name))
		end
	end

	-- Purge all session references to prevent memory leaks
	_profiles[player] = nil
	_readOnlyMode[player] = nil
	_saveTokens[player] = nil
end

-- Roll for loot using persistent PCG RNG and S-Curve luck modifier
-- Polymorphic signature supporting both DataService:RollLootDrop(player, chance) and DataService.RollLootDrop(player, chance)
function DataService.RollLootDrop(selfOrPlayer: any, playerOrChance: any, maybeChance: number?): boolean
	local player: Player
	local baseChance: number

	if maybeChance ~= nil then
		player = playerOrChance :: Player
		baseChance = maybeChance :: number
	else
		player = selfOrPlayer :: Player
		baseChance = playerOrChance :: number
	end

	-- Guaranteed boundary cases
	if baseChance <= 0 then return false end
	if baseChance >= 1.0 then return true end

	local profile = _profiles[player]
	local luckTier = profile and profile.LuckTier or 0

	-- S-curve luck multiplier capped at 3.5x
	local luckMultiplier = 1 + DataService.EvaluateSigmoid(luckTier, 2.5, 5, 0.4)
	local effectiveChance = math.clamp(baseChance * luckMultiplier, 0, 1.0)

	local roll = _rng:NextNumber(0, 1.0)

	return roll <= effectiveChance
end

-- Destructor Cleanup Hook
function DataService.Destroy()
	for player in pairs(_profiles) do
		DataService._releaseSession(player)
	end
	table.clear(_profiles)
	table.clear(_readOnlyMode)
	table.clear(_saveTokens)

	if _scythe and _scythe.isAlive(_serviceScope) then
		_scythe.scope(_serviceScope)
	end
	print("[DataService] Destroyed cleanly via Scythe.")
end

return DataService
Source: src/shared/Packages/Scythe.luau • Zero-allocation numeric scope-based memory & resource cleanup engine
--!strict
-- [ProductionCore / Packages / Scythe.luau]
-- Enterprise Zero-Allocation Scope-Based Memory Management Engine.
-- Provides ultra-low-overhead resource lifecycle and cleanup via numeric scope handles.

export type ScopeId = number
export type CleanupTask = Instance | RBXScriptConnection | () -> () | thread | ScopeId | { Destroy: (any) -> () } | { destroy: (any) -> () } | { Disconnect: (any) -> () } | { disconnect: (any) -> () } | any

local _scopes: { [ScopeId]: { CleanupTask } } = {}
local _nextScopeId: ScopeId = 0

local Scythe = {}

local function _cleanupResource(resource: CleanupTask)
	local resType = typeof(resource)

	if resType == "RBXScriptConnection" then
		(resource :: RBXScriptConnection):Disconnect()
	elseif resType == "Instance" then
		(resource :: Instance):Destroy()
	elseif resType == "function" then
		(resource :: () -> ())()
	elseif resType == "thread" then
		local th = resource :: thread
		if coroutine.status(th) ~= "dead" then
			task.cancel(th)
		end
	elseif resType == "number" then
		Scythe.scope(resource :: ScopeId)
	elseif resType == "table" then
		local tbl = resource :: any
		if typeof(tbl.Destroy) == "function" then
			tbl:Destroy()
		elseif typeof(tbl.destroy) == "function" then
			tbl:destroy()
		elseif typeof(tbl.Disconnect) == "function" then
			tbl:Disconnect()
		elseif typeof(tbl.disconnect) == "function" then
			tbl:disconnect()
		end
	end
end

-- Create a new scope handle or destroy an existing scope
function Scythe.scope(scopeId: ScopeId?): ScopeId?
	if scopeId == nil then
		_nextScopeId += 1
		local id = _nextScopeId
		_scopes[id] = {}
		return id
	end

	local bucket = _scopes[scopeId]
	if not bucket then
		return nil
	end

	_scopes[scopeId] = nil

	-- Clean up resources in reverse order (LIFO)
	for i = #bucket, 1, -1 do
		local taskItem = bucket[i]
		local ok, err = pcall(_cleanupResource, taskItem)
		if not ok then
			warn(string.format("[Scythe] Cleanup error in scope %d: %s", scopeId, tostring(err)))
		end
	end

	return nil
end

-- Register a resource inside the specified scope
function Scythe.add(scopeId: ScopeId, resource: CleanupTask): CleanupTask
	local bucket = _scopes[scopeId]
	if not bucket then
		warn(string.format("[Scythe] Attempted to add resource to dead or invalid scope %d. Cleaning immediately.", scopeId))
		pcall(_cleanupResource, resource)
		return resource
	end

	table.insert(bucket, resource)
	return resource
end

-- Batch register an array of resources inside the specified scope
function Scythe.addBulk(scopeId: ScopeId, resources: { CleanupTask })
	local bucket = _scopes[scopeId]
	if not bucket then
		warn(string.format("[Scythe] Attempted to addBulk resources to dead or invalid scope %d. Cleaning immediately.", scopeId))
		for _, res in resources do
			pcall(_cleanupResource, res)
		end
		return
	end

	for _, res in resources do
		table.insert(bucket, res)
	end
end

-- Remove a resource from an active scope without destroying it immediately
function Scythe.remove(scopeId: ScopeId, resource: CleanupTask): boolean
	local bucket = _scopes[scopeId]
	if not bucket then return false end

	local idx = table.find(bucket, resource)
	if idx then
		table.remove(bucket, idx)
		return true
	end
	return false
end

-- Check if the scope is currently active
function Scythe.isAlive(scopeId: ScopeId): boolean
	return _scopes[scopeId] ~= nil
end

return table.freeze(Scythe)

Engineering Services & Standards

Production-tested backend and client systems delivered on milestone-based schedules with strict security and zero memory leaks.

01

Combat & Weapon Systems

Server-validated raycast hitboxes, lag compensation, combo state machines, stun/knockback physics, and modular ability pipelines with cooldown managers.

Hitboxes State Machines Raycasting Ability Pipelining
02

Anti-Cheat & Exploit Defense

Authoritative server audits catching speed hacks, teleportation, noclip, flight, and suspicious remote injection with automated universe ban logs.

Server Sanity Checks Displacement Validation Rate-Limiting
03

Data Architecture & Economy

Production-grade data stores via session-locking ProfileService, anti-dupe item transactions, cross-server inventory syncing, and global leaderboards.

ProfileService Anti-Dupe Trading Engines Data Migration
04

Network & Buffer Optimization

Low-latency multiplayer replication using raw Luau buffer manipulation, spatial grid indexing for zone queries, and zero-allocation loops.

Buffer API Spatial Indexing MicroProfiler Zero-GC
05

Core Gameplay & Progression

Round managers, clan/guild structures with persistent upgrades, player leveling/XP curves, daily rewards, dynamic shops, and live admin panels.

Clan Systems Round Loops Admin Dashboards XP Engines
06

Cross-Platform UI & Keybinds

Unified input abstraction seamlessly supporting PC, Mac, Console (Gamepad), and Mobile touch devices, complete with responsive HUDs and setting suites.

ContextActionService Gamepad Mobile UX Dynamic Scaling
Collaboration Standards & Guarantee How I collaborate with studio owners & indie teams
01
Milestone / Escrow Payouts

50% upfront or verified RoDevs Middleman / Escrow supported. Zero surprise terms.

02
Fast Turnaround

1–3 days for mechanics and systems; 1–2 weeks for comprehensive frameworks.

03
Type-Strict Architecture

100% --!strict Luau coverage, modular separation, and zero dangling connections.

04
Transparent Communication

Daily commits, Discord screen shares, and detailed API documentation included.

Technical Stack & Paradigms

Industry standard tools, libraries, and engineering disciplines applied across large-scale codebases.

Languages & Typing

  • Luau Strict (`--!strict`): 100% static type coverage, interfaces, generics, metatable OOP.
  • Lua 5.1 & Metatables: Deep understanding of Luau VM bytecode, memory garbage collection, and custom class abstractions.
  • TypeScript (roblox-ts): Compile-to-Luau pipeline support for multi-contributor engineering teams.

Toolchain & DevOps

  • Rojo & VS Code: External multi-file codebase structure synced bi-directionally with Roblox Studio.
  • Wally & Foreman: Strict package dependency management and reproducible development toolchains.
  • Git & GitHub Actions: Semantic versioning, code reviews, automated formatting via StyLua, and Selene linter.

Frameworks & Lifecycle

  • Custom ModuleLoader: Phased bootstrap system with scoped Init/Start cycles and pacing controls.
  • AtomicBinding Pattern: Recursive instance hierarchy binder eliminating race conditions and memory leaks.
  • Scythe Zero-Allocation Engine: High-performance numeric scope resource management (0 heap allocations) ensuring defensive teardown of connections and instances.

Security & Network Code

  • Server-Authoritative Anti-Cheat: Noclip, speed, and instant displacement verification with universe bans.
  • Buffer Serialization: Custom byte packing and delta compression via the Luau Buffer API.
  • MicroProfiler Tuning: Eliminating garbage collection spikes and high-frequency render overhead.

Connect with me

Feel free to reach out on Discord or connect via my developer profiles to discuss systems architecture or technical questions.

Active Systems Architect
Direct 1-on-1 Communication
DISCORD (DIRECT)
rdj_rb
₮
TRON (TRC-20) WALLET
TNaavXhoj6iadhgPjAqBmJna1Lnwv4Jvjb