XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFE.SpaceEngineers.AgentBridge

【SpaceEngineer】AI调试插件

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Xml;
using System.Xml.Linq;

namespace XFE.SeAgent.Cli;

public sealed class OfflineWorldException(string code, string message) : Exception(message)
{ public string Code { get; } = code; }

public sealed record WorldDeployment(int Version, string WorldPath, string ExpectedSectorSha256, ScriptUpdate[] Scripts);
public sealed record ScriptUpdate(string EntityId, string ExpectedSha256, string SourcePath, string SourceSha256);
public sealed record SavedProgram(string EntityId, string Name, string GridId, string GridName, string Sha256, int Characters, string? Enabled, string StorageSha256);
public sealed record FileDigest(string Path, long Bytes, string Sha256);
public sealed record ScriptChange(string EntityId, string Name, string BeforeSha256, string AfterSha256, int Characters);
public sealed record WorldSnapshot(int Version, string WorldPath, DateTimeOffset CreatedUtc, FileDigest[] Files, string? DeployedSectorSha256, ScriptChange[] Changes);
public sealed record DeploymentResult(bool Applied, string WorldPath, string BeforeSectorSha256, string AfterSectorSha256,
    ScriptChange[] Changes, string[] InvalidatedCaches, string? BackupPath, string Compilation);

/// <summary>Generic, local save management. Never runs game code or edits configuration/Storage.</summary>
public sealed class OfflineWorldStore(IWorldUseGuard? guard = null, string? dataDirectory = null)
{
    public const string SectorName = "SANDBOX_0_0_0_.sbs";
    private readonly IWorldUseGuard guard = guard ?? new HostStatus();
    private readonly string dataDirectory = dataDirectory ?? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "XFE", "SpaceEngineersAgent");
    private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web) { WriteIndented = true, UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow };
    private static readonly XNamespace Xsi = "http://www.w3.org/2001/XMLSchema-instance";

    public object List(string? root = null)
    {
        root = Path.GetFullPath(root ?? Path.Combine(HostStatus.GameDataDirectory, "Saves"));
        var worlds = new List<object>();
        if (Directory.Exists(root))
        {
            var candidates = new List<string> { root };
            foreach (string directory in SafeDirectories(root))
            { candidates.Add(directory); candidates.AddRange(SafeDirectories(directory)); }
            foreach (string path in candidates.Distinct(StringComparer.OrdinalIgnoreCase))
                if (File.Exists(Path.Combine(path, "Sandbox.sbc")))
                    worlds.Add(new { path, name = Path.GetFileName(path), modifiedUtc = File.GetLastWriteTimeUtc(Path.Combine(path, "Sandbox.sbc")), hasXmlSector = File.Exists(Path.Combine(path, SectorName)) });
        }
        return new { root, worlds };
    }

    public object Inspect(string worldPath)
    {
        string world = WorldPath(worldPath);
        var sector = ReadSector(world);
        return new { worldPath = world, sectorSha256 = Sha(sector.Bytes), programs = Programs(sector.Document).Select(Describe).ToArray(),
            caches = CacheFiles(world).Select(path => new { name = Path.GetFileName(path), bytes = new FileInfo(path).Length }).ToArray(),
            hosts = guard.Inspect(), note = "磁盘内容;已加载世界的内存状态应通过实时 pb.read 检查。" };
    }

    public object ReadProgram(string worldPath, string entityId)
    {
        string id = Id(entityId);
        var block = Programs(ReadSector(WorldPath(worldPath)).Document).SingleOrDefault(x => Value(x.Block, "EntityId") == id)
            ?? throw new OfflineWorldException("block_missing", "未找到编程块:" + id);
        return new { program = Describe(block), source = Value(block.Block, "Program"), storage = Value(block.Block, "Storage") };
    }

    public object Backup(string worldPath, string? destination = null)
    {
        string world = WorldPath(worldPath);
        using var operation = Lock(world);
        guard.AssertUnloaded(world);
        string backup = CreateSnapshot(world, destination, null, []);
        return new { worldPath = world, backupPath = backup, snapshot = ReadJson<WorldSnapshot>(Path.Combine(backup, "backup.json")), note = "完整离线快照(不含游戏历史 Backup 目录);原存档未修改。" };
    }

    public DeploymentResult Deploy(string manifestPath, bool apply = false)
    {
        manifestPath = Path.GetFullPath(manifestPath);
        var manifest = ReadJson<WorldDeployment>(manifestPath);
        if (manifest.Version != 1 || manifest.Scripts == null || manifest.Scripts.Length is < 1 or > 1024)
            throw new OfflineWorldException("invalid_manifest", "version 必须为 1,scripts 必须包含 1 至 1024 个条目。");
        string world = WorldPath(manifest.WorldPath);
        using var operation = Lock(world);
        guard.AssertUnloaded(world);
        var sector = ReadSector(world);
        string before = Sha(sector.Bytes);
        Match(before, manifest.ExpectedSectorSha256, "存档 sector 已变化,请重新 inspect。");
        var edited = new XDocument(sector.Document);
        var programs = Programs(edited).ToDictionary(x => Id(Value(x.Block, "EntityId")), StringComparer.Ordinal);
        var changes = new List<ScriptChange>();
        var seen = new HashSet<string>(StringComparer.Ordinal);
        foreach (var update in manifest.Scripts)
        {
            if (update == null) throw new OfflineWorldException("invalid_manifest", "scripts 不得包含 null。");
            string id = Id(update.EntityId);
            if (!seen.Add(id)) throw new OfflineWorldException("invalid_manifest", "编程块 ID 重复:" + id);
            if (!programs.TryGetValue(id, out var program)) throw new OfflineWorldException("block_missing", "未找到编程块:" + id);
            string oldHash = Sha(Value(program.Block, "Program"));
            Match(oldHash, update.ExpectedSha256, "编程块旧源码不匹配:" + id);
            if (string.IsNullOrWhiteSpace(update.SourcePath)) throw new OfflineWorldException("invalid_manifest", "sourcePath 不能为空。");
            string sourcePath = Path.GetFullPath(update.SourcePath, Path.GetDirectoryName(manifestPath)!);
            if (new FileInfo(sourcePath).Length > 1024 * 1024) throw new OfflineWorldException("source_too_large", "源码文件超过 1 MiB。");
            string source = File.ReadAllText(sourcePath, new UTF8Encoding(false, true));
            if (source.Length > 100000) throw new OfflineWorldException("source_too_large", "编程块源码超过游戏的 100000 字符上限。");
            string newHash = Sha(source);
            Match(newHash, update.SourceSha256, "部署文件内容已变化:" + sourcePath);
            var element = Child(program.Block, "Program");
            if (element == null) { element = new XElement(program.Block.Name.Namespace + "Program"); program.Block.Add(element); }
            element.Value = source;
            changes.Add(new(id, Value(program.Block, "CustomName"), oldHash, newHash, source.Length));
        }
        byte[] replacement = Serialize(edited, sector.Bytes);
        VerifyOnlyProgramsChanged(sector.Document, Parse(replacement), seen);
        string after = Sha(replacement);
        string[] caches = CacheFiles(world).Select(Path.GetFileName).Cast<string>().ToArray();
        if (!apply) return new(false, world, before, after, changes.ToArray(), caches, null, "未编译;离线写入后游戏下次加载时编译。");
        string backup = CreateSnapshot(world, null, after, changes.ToArray());
        var snapshot = ReadJson<WorldSnapshot>(Path.Combine(backup, "backup.json"));
        Match(snapshot.Files.Single(f => f.Path == SectorName).Sha256, before, "备份前存档已变化。");
        string temporary = Path.Combine(world, ".xfe-se-" + Guid.NewGuid().ToString("N") + ".tmp");
        bool mutationStarted = false;
        try
        {
            WriteDurable(temporary, replacement);
            guard.AssertUnloaded(world);
            VerifyFiles(world, snapshot.Files, temporary);
            // Removing the cache first makes even an interrupted deployment fall back to valid XML.
            mutationStarted = true;
            foreach (string name in caches) File.Delete(Under(world, name));
            File.Replace(temporary, Path.Combine(world, SectorName), null);
            Match(FileSha(Path.Combine(world, SectorName)), after, "写入后校验失败。");
            VerifyFiles(world, ExpectedDeployedFiles(snapshot));
        }
        catch (Exception failure)
        {
            if (!mutationStarted) throw;
            // Recovery is conservative: never overwrite an unexpected edit or an active save.
            try { RestoreCore(backup, snapshot, allowPartial: true, ignoredPath: temporary); }
            catch (Exception recovery) { throw new OfflineWorldException("recovery_required", $"部署未完成:{failure.Message};自动恢复失败:{recovery.Message}。备份:{backup}"); }
            throw new OfflineWorldException("deployment_rolled_back", $"部署失败,已恢复原文件:{failure.Message}。备份:{backup}");
        }
        finally { if (File.Exists(temporary)) File.Delete(temporary); }
        return new(true, world, before, after, changes.ToArray(), caches, backup, "未执行游戏内编译;下次加载此存档时生效。");
    }

    public object Restore(string backupPath)
    {
        string backup = Path.GetFullPath(backupPath);
        var snapshot = ReadJson<WorldSnapshot>(Path.Combine(backup, "backup.json"));
        string world = WorldPath(snapshot.WorldPath);
        using var operation = Lock(world);
        RestoreCore(backup, snapshot, false);
        return new { restored = true, worldPath = world, backupPath = backup, note = "源码和二进制缓存已恢复;其他存档文件保持一致。" };
    }

    private void RestoreCore(string backup, WorldSnapshot snapshot, bool allowPartial, string? ignoredPath = null)
    {
        if (snapshot.Version != 1 || snapshot.DeployedSectorSha256 == null || snapshot.Files == null || snapshot.Files.Length == 0)
            throw new OfflineWorldException("invalid_backup", "restore 需要由 world deploy 创建的事务备份;普通快照可复制为另一个存档。");
        string world = WorldPath(snapshot.WorldPath);
        guard.AssertUnloaded(world);
        foreach (var file in snapshot.Files) Match(FileSha(Under(Path.Combine(backup, "files"), file.Path)), file.Sha256, "备份文件已变化:" + file.Path);
        var expected = ExpectedDeployedFiles(snapshot).ToList();
        if (allowPartial)
        {
            string current = FileSha(Path.Combine(world, SectorName));
            var original = snapshot.Files.Single(x => x.Path == SectorName);
            if (current == original.Sha256) expected[expected.FindIndex(x => x.Path == SectorName)] = original;
            foreach (var file in snapshot.Files.Where(x => IsCache(x.Path)))
                if (File.Exists(Under(world, file.Path))) expected.Add(file);
        }
        VerifyFiles(world, expected.ToArray(), ignoredPath);
        guard.AssertUnloaded(world);
        foreach (var file in snapshot.Files.Where(x => x.Path == SectorName || IsCache(x.Path)))
        {
            string target = Under(world, file.Path);
            if (File.Exists(target) && FileSha(target) == file.Sha256) continue;
            string temp = target + ".xfe-restore-" + Guid.NewGuid().ToString("N");
            try
            {
                File.Copy(Under(Path.Combine(backup, "files"), file.Path), temp, false);
                if (File.Exists(target)) File.Replace(temp, target, null); else File.Move(temp, target);
            }
            finally { if (File.Exists(temp)) File.Delete(temp); }
        }
        VerifyFiles(world, snapshot.Files, ignoredPath);
    }

    private string CreateSnapshot(string world, string? destination, string? deployedHash, ScriptChange[] changes)
    {
        guard.AssertUnloaded(world);
        string backup = Path.GetFullPath(destination ?? Path.Combine(dataDirectory, "backups", DateTime.UtcNow.ToString("yyyyMMddTHHmmssfff", CultureInfo.InvariantCulture) + "-" + Guid.NewGuid().ToString("N")));
        if (SamePath(backup, world) || backup.StartsWith(world + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) || Directory.Exists(backup) || File.Exists(backup))
            throw new OfflineWorldException("invalid_backup_path", "备份目录必须是存档以外的新目录。");
        EnsureNoLinks(backup);
        var files = ActiveFiles(world);
        Directory.CreateDirectory(Path.Combine(backup, "files"));
        var digests = new List<FileDigest>();
        foreach (string relative in files)
        {
            string source = Under(world, relative), target = Under(Path.Combine(backup, "files"), relative);
            Directory.CreateDirectory(Path.GetDirectoryName(target)!);
            using (var input = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.Read))
            using (var output = new FileStream(target, FileMode.CreateNew, FileAccess.Write, FileShare.None))
            { input.CopyTo(output); output.Flush(true); }
            digests.Add(new(relative, new FileInfo(target).Length, FileSha(target)));
        }
        guard.AssertUnloaded(world);
        VerifyFiles(world, digests.ToArray());
        var snapshot = new WorldSnapshot(1, world, DateTimeOffset.UtcNow, digests.ToArray(), deployedHash, changes);
        WriteDurable(Path.Combine(backup, "backup.json"), Encoding.UTF8.GetBytes(JsonSerializer.Serialize(snapshot, Json)));
        return backup;
    }

    private static FileDigest[] ExpectedDeployedFiles(WorldSnapshot snapshot) => snapshot.Files.Where(x => !IsCache(x.Path)).Select(x =>
        x.Path == SectorName ? x with { Sha256 = snapshot.DeployedSectorSha256!, Bytes = -1 } : x).ToArray();

    private static void VerifyFiles(string world, FileDigest[] files, string? ignoredPath = null)
    {
        string[] actual = ActiveFiles(world).Where(p => ignoredPath == null || !SamePath(Under(world, p), ignoredPath)).ToArray();
        if (!actual.Order(StringComparer.OrdinalIgnoreCase).SequenceEqual(files.Select(x => x.Path).Order(StringComparer.OrdinalIgnoreCase), StringComparer.OrdinalIgnoreCase))
            throw new OfflineWorldException("concurrent_change", "存档文件列表已变化,拒绝覆盖。");
        foreach (var file in files) Match(FileSha(Under(world, file.Path)), file.Sha256, "存档文件已变化:" + file.Path);
    }

    private FileStream Lock(string world)
    {
        string directory = Path.Combine(dataDirectory, "offline-locks"); Directory.CreateDirectory(directory);
        return new FileStream(Path.Combine(directory, Sha(world.ToUpperInvariant()) + ".lock"), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
    }
    public static bool SamePath(string a, string b) => string.Equals(Path.TrimEndingDirectorySeparator(Path.GetFullPath(a)), Path.TrimEndingDirectorySeparator(Path.GetFullPath(b)), StringComparison.OrdinalIgnoreCase);
    public static string Sha(string text) => Sha(Encoding.UTF8.GetBytes(text));
    public static string Sha(byte[] bytes) => Convert.ToHexStringLower(SHA256.HashData(bytes));
    public static string FileSha(string path) { using var input = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); return Convert.ToHexStringLower(SHA256.HashData(input)); }
    private static void Match(string actual, string? expected, string detail)
    {
        if (expected == null || expected.Length != 64 || !expected.All(Uri.IsHexDigit)) throw new OfflineWorldException("invalid_hash", "需要完整 SHA-256:" + detail);
        if (!actual.Equals(expected, StringComparison.OrdinalIgnoreCase)) throw new OfflineWorldException("hash_mismatch", detail);
    }
    private static string Id(string? value) => long.TryParse(value, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out long id) && id != 0 ? id.ToString(CultureInfo.InvariantCulture) : throw new OfflineWorldException("invalid_id", "需要非零 Int64 字符串 ID。");
    private static T ReadJson<T>(string path)
    {
        if (new FileInfo(path).Length > 8 * 1024 * 1024) throw new OfflineWorldException("invalid_manifest", "JSON 文件超过 8 MiB。");
        return JsonSerializer.Deserialize<T>(File.ReadAllText(path), Json) ?? throw new OfflineWorldException("invalid_manifest", "JSON 不能为空。");
    }
    private static string WorldPath(string path)
    {
        if (string.IsNullOrWhiteSpace(path) || !Path.IsPathFullyQualified(path)) throw new OfflineWorldException("invalid_world", "存档路径必须是绝对路径。");
        path = Path.TrimEndingDirectorySeparator(Path.GetFullPath(path)); EnsureNoLinks(path);
        if (!File.Exists(Path.Combine(path, "Sandbox.sbc"))) throw new OfflineWorldException("invalid_world", "目录中没有 Sandbox.sbc。");
        return path;
    }
    private static string Under(string root, string relative)
    {
        string path = Path.GetFullPath(Path.Combine(root, relative));
        if (Path.IsPathRooted(relative) || !path.StartsWith(Path.TrimEndingDirectorySeparator(Path.GetFullPath(root)) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
            throw new OfflineWorldException("invalid_path", "文件路径超出目标目录。");
        EnsureNoLinks(path); return path;
    }
    private static void EnsureNoLinks(string path)
    {
        for (string? current = Path.GetFullPath(path); current != null; current = Path.GetDirectoryName(current))
            if ((Directory.Exists(current) || File.Exists(current)) && (File.GetAttributes(current) & FileAttributes.ReparsePoint) != 0)
                throw new OfflineWorldException("linked_path", "离线存档操作不跟随链接或目录联接:" + current);
    }
    private static IEnumerable<string> SafeDirectories(string root) => Directory.EnumerateDirectories(root).Where(p => (File.GetAttributes(p) & FileAttributes.ReparsePoint) == 0).Take(10000);
    private static string[] ActiveFiles(string world)
    {
        var files = new List<string>();
        void Walk(string directory)
        {
            foreach (string path in Directory.EnumerateFileSystemEntries(directory))
            {
                if (SamePath(directory, world) && Path.GetFileName(path).Equals("Backup", StringComparison.OrdinalIgnoreCase)) continue;
                EnsureNoLinks(path);
                if (Directory.Exists(path)) Walk(path); else files.Add(Path.GetRelativePath(world, path));
                if (files.Count > 200000) throw new OfflineWorldException("world_too_large", "存档文件超过 200000 个。");
            }
        }
        Walk(world); return files.Order(StringComparer.OrdinalIgnoreCase).ToArray();
    }
    private static bool IsCache(string relative) => Path.GetFileName(relative).Equals(relative, StringComparison.Ordinal) && relative.StartsWith(SectorName + "B", StringComparison.OrdinalIgnoreCase)
        && relative.Length > SectorName.Length + 1 && relative[(SectorName.Length + 1)..].All(char.IsAsciiDigit);
    private static string[] CacheFiles(string world) => Directory.EnumerateFiles(world).Where(p => IsCache(Path.GetFileName(p))).ToArray();
    private static (byte[] Bytes, XDocument Document) ReadSector(string world)
    {
        string path = Under(world, SectorName);
        if (!File.Exists(path)) throw new OfflineWorldException("xml_sector_missing", "缺少 XML sector;请先在游戏中生成 XML 存档,不能直接修改二进制缓存。");
        if (new FileInfo(path).Length > 512L * 1024 * 1024) throw new OfflineWorldException("world_too_large", "XML sector 超过 512 MiB。");
        byte[] bytes = File.ReadAllBytes(path); return (bytes, Parse(bytes));
    }
    private static XDocument Parse(byte[] bytes)
    {
        using var stream = new MemoryStream(bytes);
        using var reader = XmlReader.Create(stream, new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null, MaxCharactersInDocument = 512L * 1024 * 1024 });
        return XDocument.Load(reader, LoadOptions.PreserveWhitespace);
    }
    private sealed record ProgramNode(XElement Block, XElement Grid);
    private static XElement? Child(XElement element, string name) => element.Elements().FirstOrDefault(x => x.Name.LocalName == name);
    private static string Value(XElement element, string name) => Child(element, name)?.Value ?? "";
    private static IEnumerable<ProgramNode> Programs(XDocument document)
    {
        var objects = document.Root == null ? null : Child(document.Root, "SectorObjects");
        if (objects == null) throw new OfflineWorldException("invalid_sector", "未找到 SectorObjects。");
        foreach (var grid in objects.Elements())
            foreach (var block in Child(grid, "CubeBlocks")?.Elements() ?? [])
                if (((string?)block.Attribute(Xsi + "type") ?? block.Name.LocalName) is "MyObjectBuilder_MyProgrammableBlock" or "MyObjectBuilder_ProgrammableBlock")
                    yield return new(block, grid);
    }
    private static SavedProgram Describe(ProgramNode node) => new(Value(node.Block, "EntityId"), Value(node.Block, "CustomName"), Value(node.Grid, "EntityId"), Value(node.Grid, "DisplayName"),
        Sha(Value(node.Block, "Program")), Value(node.Block, "Program").Length, Child(node.Block, "Enabled")?.Value, Sha(Value(node.Block, "Storage")));
    private static byte[] Serialize(XDocument document, byte[] original)
    {
        using var output = new MemoryStream();
        using (var writer = XmlWriter.Create(output, new XmlWriterSettings { Encoding = new UTF8Encoding(original.AsSpan().StartsWith(new byte[] { 239, 187, 191 })), Indent = false, NewLineHandling = NewLineHandling.Entitize, OmitXmlDeclaration = document.Declaration == null })) document.Save(writer);
        return output.ToArray();
    }
    private static void VerifyOnlyProgramsChanged(XDocument before, XDocument after, HashSet<string> ids)
    {
        var old = Programs(before).ToDictionary(x => Value(x.Block, "EntityId"));
        foreach (var program in Programs(after).Where(x => ids.Contains(Value(x.Block, "EntityId"))))
        {
            var prior = Child(old[Value(program.Block, "EntityId")].Block, "Program");
            var element = Child(program.Block, "Program")!;
            if (prior == null) element.Remove(); else element.ReplaceWith(new XElement(prior));
        }
        if (!XNode.DeepEquals(before, after)) throw new OfflineWorldException("preservation_failed", "XML 往返校验发现源码以外的内容变化,拒绝写入。");
    }
    private static void WriteDurable(string path, byte[] bytes)
    { using var file = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None); file.Write(bytes); file.Flush(true); }
}