Framework/Scripting/LuaDevReload.cs

Dev-mode hot reload watcher for the Lua scripting layer. Every 2 seconds it hashes the `.lua` and `.json` files that feed the running world (framework root, the active gamemode chain, addons) from `FileSystem.Mounted` and `FileSystem.Data`, and calls `LuaRuntime.Reload` when a change holds stable for two consecutive checks. Only runs when `DevMode` is on, the realm is authority and a server Lua realm exists.

using System;
using System.Collections.Generic;
using System.Linq;
using RoleplayFramework.Diagnostics;

namespace RoleplayFramework.Scripting;

/// <summary>
/// Development hot-reload: with <c>"DevMode": true</c> in framework.json, the server (dedicated or listen host) checks
/// the Lua it runs every <see cref="IntervalSeconds"/> and runs <see cref="LuaRuntime.Reload"/> by itself when a file
/// changed: the running gamemode chain, every addon and the framework core, from the data folder and the game.
/// Clients never watch anything; they get the changed files through the normal reload path.
///
/// A change is applied once it has been stable for one more check (editors may save in several steps). A reload that
/// fails (e.g. a syntax error) leaves the previous scripts running and is not retried until the files change again.
/// </summary>
public static class LuaDevReload
{
	public const double IntervalSeconds = 2.0;

	static double _next;
	static Dictionary<string, ulong> _applied;   // what the running realm was loaded from
	static Dictionary<string, ulong> _pending;   // a change seen once, waiting to be stable
	static LuaRealm _watchedRealm;

	public static bool Active => Bootstrap.FrameworkHost.Config.DevMode && Core.RealmInfo.IsAuthority && LuaRuntime.Server is not null;

	public static void Tick()
	{
		if ( !Active ) { _applied = null; _pending = null; _watchedRealm = null; return; }
		var now = RealTime.Now;
		if ( now < _next ) return;
		_next = now + IntervalSeconds;

		Dictionary<string, ulong> current;
		try { current = Fingerprint(); }
		catch ( Exception e ) { RpLog.Warn( "lua", $"DevMode: could not check Lua files: {e.Message}" ); return; }

		// A new realm (world start or a manual rp_lua_reload): its files are the new baseline.
		if ( _applied is null || _watchedRealm != LuaRuntime.Server )
		{
			_watchedRealm = LuaRuntime.Server;
			_applied = current;
			_pending = null;
			return;
		}

		if ( Same( current, _applied ) ) { _pending = null; return; }
		if ( _pending is null || !Same( current, _pending ) ) { _pending = current; return; } // wait one more check

		var changed = Diff( _applied, current );
		_applied = current;
		_pending = null;
		RpLog.Info( "lua", $"DevMode: {changed.Count} Lua file(s) changed ({string.Join( ", ", changed.Take( 5 ) )}{(changed.Count > 5 ? ", ..." : "")}) - reloading" );
		RpLog.Info( "lua", LuaRuntime.Reload() );
		_watchedRealm = LuaRuntime.Server; // the reloaded realm (or the old one if the reload failed) matches _applied
	}

	static bool Same( Dictionary<string, ulong> a, Dictionary<string, ulong> b ) =>
		a.Count == b.Count && a.All( kv => b.TryGetValue( kv.Key, out var h ) && h == kv.Value );

	static List<string> Diff( Dictionary<string, ulong> before, Dictionary<string, ulong> after )
	{
		var list = new List<string>();
		foreach ( var (k, h) in after ) if ( !before.TryGetValue( k, out var old ) || old != h ) list.Add( k );
		foreach ( var k in before.Keys ) if ( !after.ContainsKey( k ) ) list.Add( k + " (deleted)" );
		return list;
	}

	/// <summary>Path → content hash of every Lua/JSON file that can affect the running world.</summary>
	static Dictionary<string, ulong> Fingerprint()
	{
		var result = new Dictionary<string, ulong>();
		var chain = LuaRuntime.Server.Gamemode is { } gm ? GamemodeRegistry.Current.LoadOrder( gm.Id )?.Select( m => m.Id ).ToList() : null;

		void Scan( BaseFileSystem fs, string dir, string label )
		{
			if ( !fs.DirectoryExists( dir ) ) return;
			foreach ( var rel in fs.FindFile( dir, "*", true ) )
			{
				if ( !rel.EndsWith( ".lua", StringComparison.OrdinalIgnoreCase ) && !rel.EndsWith( ".json", StringComparison.OrdinalIgnoreCase ) ) continue;
				if ( result.Count > 4000 ) return;
				result[$"{label}/{rel}"] = Hash( fs.ReadAllText( $"{dir}/{rel}" ) );
			}
		}

		var mounted = FileSystem.Mounted;
		Scan( mounted, LuaRealm.FrameworkRoot, "framework" );
		foreach ( var id in chain ?? new List<string>() )
		{
			if ( LuaSource.UsesDataFolder && FileSystem.Data.FileExists( $"{LuaSource.DataGamemodes}/{id}/gamemode.json" ) )
				Scan( FileSystem.Data, $"{LuaSource.DataGamemodes}/{id}", $"data:gamemodes/{id}" );
			else
				Scan( mounted, $"{LuaSource.BuiltInGamemodes}/{id}", $"gamemodes/{id}" );
		}
		if ( LuaSource.UsesDataFolder ) Scan( FileSystem.Data, LuaSource.DataAddons, "data:addons" );
		Scan( mounted, LuaSource.BuiltInAddons, "addons" );
		return result;
	}

	/// <summary>FNV-1a 64 over the text: cheap and deterministic.</summary>
	static ulong Hash( string text )
	{
		ulong h = 14695981039346656037UL;
		foreach ( var c in text )
		{
			h ^= c;
			h *= 1099511628211UL;
		}
		return h;
	}
}