#nullable enable
using System.Text;
using System.Text.Json;
using System.Xml;
using System.Xml.Linq;
using XFE.SeAgent.Cli;
namespace XFE.SeAgent.Tests;
internal static partial class Program
{
private sealed class WorldGuard : IWorldUseGuard
{
public IReadOnlyList<GameHostStatus> Hosts = [];
public Action<int>? OnCheck;
public int Checks;
public IReadOnlyList<GameHostStatus> Inspect() => Hosts;
public void AssertUnloaded(string path) { OnCheck?.Invoke(++Checks); HostStatus.CheckUnloaded(path, Hosts); }
}
private static async Task TestOfflineWorldsAsync()
{
string root = Path.Combine(Fixtures, "offline"), world = Path.Combine(root, "存档"), data = Path.Combine(root, "bridge");
Directory.CreateDirectory(world);
File.WriteAllText(Path.Combine(world, "Sandbox.sbc"), "<checkpoint><online>PUBLIC</online></checkpoint>");
File.WriteAllText(Path.Combine(world, "Sandbox_config.sbc"), "<config />");
File.WriteAllBytes(Path.Combine(world, "planet.vx2"), [0, 255, 12, 34, 78]);
File.WriteAllText(Path.Combine(world, OfflineWorldStore.SectorName + "B5"), "binary-cache");
File.WriteAllText(Path.Combine(world, OfflineWorldStore.SectorName + "Banana"), "not-a-cache");
Directory.CreateDirectory(Path.Combine(world, "Backup", "previous"));
File.WriteAllText(Path.Combine(world, "Backup", "previous", "history"), "old-game-backup");
const string source1 = "// 中文 & <>\r\npublic void Main() {}", source2 = "// 第二个\npublic void Main() {}";
XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
XElement Block(string id, string name, string source) => new("MyObjectBuilder_CubeBlock", new XAttribute(xsi + "type", "MyObjectBuilder_MyProgrammableBlock"),
new XElement("EntityId", id), new XElement("CustomName", name), new XElement("Enabled", "false"),
new XElement("Program", source), new XElement("Storage", "持久\r\n数据"), new XElement("CustomData", "[setting]\nvalue=42"));
var document = new XDocument(new XDeclaration("1.0", "utf-8", null), new XElement("MyObjectBuilder_Sector", new XAttribute(XNamespace.Xmlns + "xsi", xsi),
new XElement("SectorObjects", new XElement("MyObjectBuilder_EntityBase", new XElement("EntityId", "99"), new XElement("DisplayName", "测试船"),
new XElement("CubeBlocks", Block("1234567890123456789", "脚本一", source1), Block("-234567890123456789", "脚本二", source2), Block("333", "未选择", "// untouched"),
new XElement("Projector", new XElement("CubeBlocks", Block("444", "投影蓝图", "// blueprint"))))))));
string sector = Path.Combine(world, OfflineWorldStore.SectorName);
using (var writer = XmlWriter.Create(sector, new XmlWriterSettings { Encoding = new UTF8Encoding(true), Indent = true, NewLineChars = "\r\n", NewLineHandling = NewLineHandling.Entitize })) document.Save(writer);
byte[] original = File.ReadAllBytes(sector);
var originalOther = Directory.GetFiles(world).Where(x => x != sector).ToDictionary(x => x, OfflineWorldStore.FileSha);
var guard = new WorldGuard(); var store = new OfflineWorldStore(guard, data);
JsonElement ToJson(object value) => JsonSerializer.SerializeToElement(value, Json);
var inspection = ToJson(store.Inspect(world));
Check(inspection.GetProperty("programs").GetArrayLength() == 3, "offline inspect finds actual PBs and excludes projected blueprint PBs");
Check(ToJson(store.ReadProgram(world, "1234567890123456789")).GetProperty("source").GetString() == source1, "offline read preserves Unicode and CRLF source");
Check(ToJson(store.List(root)).GetProperty("worlds").GetArrayLength() == 1, "offline list locates save folders without endpoints");
string script1 = Path.Combine(root, "one.cs"), script2 = Path.Combine(root, "two.cs");
const string next1 = "// new 中文\r\nvoid Main(){Echo(\"a < b & c\");}", next2 = "// new two\nvoid Main(){}";
File.WriteAllText(script1, next1); File.WriteAllText(script2, next2);
var manifest = new WorldDeployment(1, world, OfflineWorldStore.Sha(original), [
new("1234567890123456789", OfflineWorldStore.Sha(source1), "one.cs", OfflineWorldStore.Sha(next1)),
new("-234567890123456789", OfflineWorldStore.Sha(source2), "two.cs", OfflineWorldStore.Sha(next2))]);
string manifestFile = Path.Combine(root, "deploy.json");
void WriteManifest(WorldDeployment value) => File.WriteAllText(manifestFile, JsonSerializer.Serialize(value, Json));
WriteManifest(manifest);
var preview = store.Deploy(manifestFile);
Check(!preview.Applied && preview.Changes.Length == 2 && File.ReadAllBytes(sector).SequenceEqual(original) && File.Exists(Path.Combine(world, OfflineWorldStore.SectorName + "B5")), "offline deployment defaults to dry run with exact selection and no save writes");
var applied = store.Deploy(manifestFile, true);
Check(applied.Applied && OfflineWorldStore.FileSha(sector) == applied.AfterSectorSha256 && applied.Changes.All(x => x.Characters > 0), "offline batch commits exact source hashes for both signed Int64 IDs");
Check(!File.Exists(Path.Combine(world, OfflineWorldStore.SectorName + "B5")) && File.Exists(Path.Combine(world, OfflineWorldStore.SectorName + "Banana")), "offline deployment invalidates binary sector cache but preserves similarly named unrelated file");
var finalDoc = XDocument.Load(sector, LoadOptions.PreserveWhitespace);
var oldDoc = XDocument.Load(new MemoryStream(original), LoadOptions.PreserveWhitespace);
foreach (var element in finalDoc.Descendants("Program").Zip(oldDoc.Descendants("Program"))) element.First.Value = element.Second.Value;
Check(XNode.DeepEquals(finalDoc, oldDoc) && originalOther.Where(x => !x.Key.EndsWith("sbsB5")).All(x => OfflineWorldStore.FileSha(x.Key) == x.Value), "deployment preserves Storage, configuration, enablement, unselected scripts, hardware, voxels and checkpoint");
Check(File.ReadAllBytes(Path.Combine(applied.BackupPath!, "files", OfflineWorldStore.SectorName)).SequenceEqual(original) && File.Exists(Path.Combine(applied.BackupPath!, "files", "planet.vx2")) && !Directory.Exists(Path.Combine(applied.BackupPath!, "files", "Backup")), "deployment snapshot contains exact original sector, cache and all active files without recursive game history");
Throws<OfflineWorldException>(() => store.Deploy(manifestFile, true), "stale expected sector hash prevents repeated deployment");
File.AppendAllText(Path.Combine(world, "Sandbox_config.sbc"), "<!-- user edit -->");
Throws<OfflineWorldException>(() => store.Restore(applied.BackupPath!), "rollback refuses to overwrite subsequent game or user progress");
File.Copy(Path.Combine(applied.BackupPath!, "files", "Sandbox_config.sbc"), Path.Combine(world, "Sandbox_config.sbc"), true);
store.Restore(applied.BackupPath!);
Check(File.ReadAllBytes(sector).SequenceEqual(original) && originalOther.All(x => OfflineWorldStore.FileSha(x.Key) == x.Value), "rollback restores original XML and binary cache byte for byte");
WriteManifest(manifest with { Scripts = [manifest.Scripts[0] with { ExpectedSha256 = new string('a', 64) }] });
Throws<OfflineWorldException>(() => store.Deploy(manifestFile, true), "offline batch rejects stale per-block source hash");
WriteManifest(manifest with { Scripts = [manifest.Scripts[0] with { SourceSha256 = new string('b', 64) }] });
Throws<OfflineWorldException>(() => store.Deploy(manifestFile, true), "offline batch rejects changed input source before mutation");
WriteManifest(manifest with { Scripts = [manifest.Scripts[0], manifest.Scripts[0]] });
Throws<OfflineWorldException>(() => store.Deploy(manifestFile, true), "offline batch rejects duplicate block IDs");
WriteManifest(manifest with { Scripts = [manifest.Scripts[0] with { EntityId = "444" }] });
Throws<OfflineWorldException>(() => store.Deploy(manifestFile, true), "offline deploy cannot target projected blueprint blocks");
WriteManifest(manifest);
var host = new GameHostStatus(123, "C:\\game\\SpaceEngineers.exe", DateTimeOffset.UtcNow, false, "loaded_or_loading", world, null, "fixture");
guard.Hosts = [host];
Throws<OfflineWorldException>(() => store.Deploy(manifestFile, true), "loaded target world is rejected without needing a plugin endpoint");
guard.Hosts = [host with { State = "unknown", WorldPath = null }];
Throws<OfflineWorldException>(() => store.Backup(world), "unknown game state blocks offline mutation and inconsistent snapshots");
guard.Hosts = [host with { WorldPath = world + "-other" }];
Check(!store.Deploy(manifestFile).Applied, "another identified loaded world permits independent offline deployment preview");
guard.Hosts = [];
guard.Checks = 0;
FileStream? held = null;
guard.OnCheck = n => { if (n == 4) held = new FileStream(sector, FileMode.Open, FileAccess.Read, FileShare.Read); };
try
{
try { store.Deploy(manifestFile, true); throw new Exception("Expected atomic replace failure"); }
catch (OfflineWorldException ex) { Check(ex.Code == "deployment_rolled_back", "failed atomic replacement recovers cache automatically and reports rollback"); }
}
finally { held?.Dispose(); guard.OnCheck = null; }
Check(File.ReadAllBytes(sector).SequenceEqual(original) && originalOther.All(x => OfflineWorldStore.FileSha(x.Key) == x.Value), "failed deployment leaves all active files byte identical");
guard.Checks = 0;
guard.OnCheck = n => { if (n == 4) guard.Hosts = [host]; };
Throws<OfflineWorldException>(() => store.Deploy(manifestFile, true), "world loaded during backup is detected again before commit");
guard.OnCheck = null; guard.Hosts = [];
Check(File.ReadAllBytes(sector).SequenceEqual(original), "late world-use conflict leaves source unchanged");
Throws<OfflineWorldException>(() => store.Backup(world, Path.Combine(world, "nested-backup")), "backup destination cannot recurse into target save");
var snapshot = ToJson(store.Backup(world));
Check(snapshot.GetProperty("snapshot").GetProperty("files").GetArrayLength() == 6, "standalone offline backup covers all active files");
var parsed = HostStatus.ParseLog(new StringReader($"Environment.CommandLine: \"{host.ExecutablePath}\"\nLoading session: {world}\n"), host with { State = "unknown", WorldPath = null }, "fixture.log");
Check(parsed.State == "loaded_or_loading" && parsed.WorldPath == world, "host log identifies the current save only after executable identity matches");
parsed = HostStatus.ParseLog(new StringReader($"Environment.CommandLine: \"{host.ExecutablePath}\"\nLoading session: {world}\nMySession::Unload START\n"), host with { State = "unknown", WorldPath = null }, "fixture.log");
Check(parsed.WorldPath == world, "host protects the previous world until unload completes");
parsed = HostStatus.ParseLog(new StringReader($"Environment.CommandLine: \"{host.ExecutablePath}\"\nLoading session: {world}\nMySession::Unload END\n"), host with { State = "unknown", WorldPath = null }, "fixture.log");
Check(parsed.State == "unloaded" && parsed.WorldPath == null, "host recognizes completed unload without UI access");
parsed = HostStatus.ParseLog(new StringReader($"Environment.CommandLine: \"C:\\other.exe\"\nLoading session: {world}\n"), host with { State = "unknown", WorldPath = null }, "fixture.log");
Check(parsed.State == "unknown", "host rejects logs belonging to a different executable");
var cli = new CliApplication(worlds: store, host: guard);
using var stdout = new StringWriter(); using var stderr = new StringWriter();
int exit = await cli.RunAsync(["world", "deploy", "--manifest", manifestFile], stdout, stderr);
using var cliResult = JsonDocument.Parse(stdout.ToString());
Check(exit == 0 && !cliResult.RootElement.GetProperty("applied").GetBoolean() && stderr.ToString().Length == 0, "offline CLI returns structured dry run without resolving an Agent pipe");
}
}
#nullable enable
using System.Text;
using System.Text.Json;
using System.Xml;
using System.Xml.Linq;
using XFE.SeAgent.Cli;
namespace XFE.SeAgent.Tests;
internal static partial class Program
{
private sealed class WorldGuard : IWorldUseGuard
{
public IReadOnlyList<GameHostStatus> Hosts = [];
public Action<int>? OnCheck;
public int Checks;
public IReadOnlyList<GameHostStatus> Inspect() => Hosts;
public void AssertUnloaded(string path) { OnCheck?.Invoke(++Checks); HostStatus.CheckUnloaded(path, Hosts); }
}
private static async Task TestOfflineWorldsAsync()
{
string root = Path.Combine(Fixtures, "offline"), world = Path.Combine(root, "存档"), data = Path.Combine(root, "bridge");
Directory.CreateDirectory(world);
File.WriteAllText(Path.Combine(world, "Sandbox.sbc"), "<checkpoint><online>PUBLIC</online></checkpoint>");
File.WriteAllText(Path.Combine(world, "Sandbox_config.sbc"), "<config />");
File.WriteAllBytes(Path.Combine(world, "planet.vx2"), [0, 255, 12, 34, 78]);
File.WriteAllText(Path.Combine(world, OfflineWorldStore.SectorName + "B5"), "binary-cache");
File.WriteAllText(Path.Combine(world, OfflineWorldStore.SectorName + "Banana"), "not-a-cache");
Directory.CreateDirectory(Path.Combine(world, "Backup", "previous"));
File.WriteAllText(Path.Combine(world, "Backup", "previous", "history"), "old-game-backup");
const string source1 = "// 中文 & <>\r\npublic void Main() {}", source2 = "// 第二个\npublic void Main() {}";
XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
XElement Block(string id, string name, string source) => new("MyObjectBuilder_CubeBlock", new XAttribute(xsi + "type", "MyObjectBuilder_MyProgrammableBlock"),
new XElement("EntityId", id), new XElement("CustomName", name), new XElement("Enabled", "false"),
new XElement("Program", source), new XElement("Storage", "持久\r\n数据"), new XElement("CustomData", "[setting]\nvalue=42"));
var document = new XDocument(new XDeclaration("1.0", "utf-8", null), new XElement("MyObjectBuilder_Sector", new XAttribute(XNamespace.Xmlns + "xsi", xsi),
new XElement("SectorObjects", new XElement("MyObjectBuilder_EntityBase", new XElement("EntityId", "99"), new XElement("DisplayName", "测试船"),
new XElement("CubeBlocks", Block("1234567890123456789", "脚本一", source1), Block("-234567890123456789", "脚本二", source2), Block("333", "未选择", "// untouched"),
new XElement("Projector", new XElement("CubeBlocks", Block("444", "投影蓝图", "// blueprint"))))))));
string sector = Path.Combine(world, OfflineWorldStore.SectorName);
using (var writer = XmlWriter.Create(sector, new XmlWriterSettings { Encoding = new UTF8Encoding(true), Indent = true, NewLineChars = "\r\n", NewLineHandling = NewLineHandling.Entitize })) document.Save(writer);
byte[] original = File.ReadAllBytes(sector);
var originalOther = Directory.GetFiles(world).Where(x => x != sector).ToDictionary(x => x, OfflineWorldStore.FileSha);
var guard = new WorldGuard(); var store = new OfflineWorldStore(guard, data);
JsonElement ToJson(object value) => JsonSerializer.SerializeToElement(value, Json);
var inspection = ToJson(store.Inspect(world));
Check(inspection.GetProperty("programs").GetArrayLength() == 3, "offline inspect finds actual PBs and excludes projected blueprint PBs");
Check(ToJson(store.ReadProgram(world, "1234567890123456789")).GetProperty("source").GetString() == source1, "offline read preserves Unicode and CRLF source");
Check(ToJson(store.List(root)).GetProperty("worlds").GetArrayLength() == 1, "offline list locates save folders without endpoints");
string script1 = Path.Combine(root, "one.cs"), script2 = Path.Combine(root, "two.cs");
const string next1 = "// new 中文\r\nvoid Main(){Echo(\"a < b & c\");}", next2 = "// new two\nvoid Main(){}";
File.WriteAllText(script1, next1); File.WriteAllText(script2, next2);
var manifest = new WorldDeployment(1, world, OfflineWorldStore.Sha(original), [
new("1234567890123456789", OfflineWorldStore.Sha(source1), "one.cs", OfflineWorldStore.Sha(next1)),
new("-234567890123456789", OfflineWorldStore.Sha(source2), "two.cs", OfflineWorldStore.Sha(next2))]);
string manifestFile = Path.Combine(root, "deploy.json");
void WriteManifest(WorldDeployment value) => File.WriteAllText(manifestFile, JsonSerializer.Serialize(value, Json));
WriteManifest(manifest);
var preview = store.Deploy(manifestFile);
Check(!preview.Applied && preview.Changes.Length == 2 && File.ReadAllBytes(sector).SequenceEqual(original) && File.Exists(Path.Combine(world, OfflineWorldStore.SectorName + "B5")), "offline deployment defaults to dry run with exact selection and no save writes");
var applied = store.Deploy(manifestFile, true);
Check(applied.Applied && OfflineWorldStore.FileSha(sector) == applied.AfterSectorSha256 && applied.Changes.All(x => x.Characters > 0), "offline batch commits exact source hashes for both signed Int64 IDs");
Check(!File.Exists(Path.Combine(world, OfflineWorldStore.SectorName + "B5")) && File.Exists(Path.Combine(world, OfflineWorldStore.SectorName + "Banana")), "offline deployment invalidates binary sector cache but preserves similarly named unrelated file");
var finalDoc = XDocument.Load(sector, LoadOptions.PreserveWhitespace);
var oldDoc = XDocument.Load(new MemoryStream(original), LoadOptions.PreserveWhitespace);
foreach (var element in finalDoc.Descendants("Program").Zip(oldDoc.Descendants("Program"))) element.First.Value = element.Second.Value;
Check(XNode.DeepEquals(finalDoc, oldDoc) && originalOther.Where(x => !x.Key.EndsWith("sbsB5")).All(x => OfflineWorldStore.FileSha(x.Key) == x.Value), "deployment preserves Storage, configuration, enablement, unselected scripts, hardware, voxels and checkpoint");
Check(File.ReadAllBytes(Path.Combine(applied.BackupPath!, "files", OfflineWorldStore.SectorName)).SequenceEqual(original) && File.Exists(Path.Combine(applied.BackupPath!, "files", "planet.vx2")) && !Directory.Exists(Path.Combine(applied.BackupPath!, "files", "Backup")), "deployment snapshot contains exact original sector, cache and all active files without recursive game history");
Throws<OfflineWorldException>(() => store.Deploy(manifestFile, true), "stale expected sector hash prevents repeated deployment");
File.AppendAllText(Path.Combine(world, "Sandbox_config.sbc"), "<!-- user edit -->");
Throws<OfflineWorldException>(() => store.Restore(applied.BackupPath!), "rollback refuses to overwrite subsequent game or user progress");
File.Copy(Path.Combine(applied.BackupPath!, "files", "Sandbox_config.sbc"), Path.Combine(world, "Sandbox_config.sbc"), true);
store.Restore(applied.BackupPath!);
Check(File.ReadAllBytes(sector).SequenceEqual(original) && originalOther.All(x => OfflineWorldStore.FileSha(x.Key) == x.Value), "rollback restores original XML and binary cache byte for byte");
WriteManifest(manifest with { Scripts = [manifest.Scripts[0] with { ExpectedSha256 = new string('a', 64) }] });
Throws<OfflineWorldException>(() => store.Deploy(manifestFile, true), "offline batch rejects stale per-block source hash");
WriteManifest(manifest with { Scripts = [manifest.Scripts[0] with { SourceSha256 = new string('b', 64) }] });
Throws<OfflineWorldException>(() => store.Deploy(manifestFile, true), "offline batch rejects changed input source before mutation");
WriteManifest(manifest with { Scripts = [manifest.Scripts[0], manifest.Scripts[0]] });
Throws<OfflineWorldException>(() => store.Deploy(manifestFile, true), "offline batch rejects duplicate block IDs");
WriteManifest(manifest with { Scripts = [manifest.Scripts[0] with { EntityId = "444" }] });
Throws<OfflineWorldException>(() => store.Deploy(manifestFile, true), "offline deploy cannot target projected blueprint blocks");
WriteManifest(manifest);
var host = new GameHostStatus(123, "C:\\game\\SpaceEngineers.exe", DateTimeOffset.UtcNow, false, "loaded_or_loading", world, null, "fixture");
guard.Hosts = [host];
Throws<OfflineWorldException>(() => store.Deploy(manifestFile, true), "loaded target world is rejected without needing a plugin endpoint");
guard.Hosts = [host with { State = "unknown", WorldPath = null }];
Throws<OfflineWorldException>(() => store.Backup(world), "unknown game state blocks offline mutation and inconsistent snapshots");
guard.Hosts = [host with { WorldPath = world + "-other" }];
Check(!store.Deploy(manifestFile).Applied, "another identified loaded world permits independent offline deployment preview");
guard.Hosts = [];
guard.Checks = 0;
FileStream? held = null;
guard.OnCheck = n => { if (n == 4) held = new FileStream(sector, FileMode.Open, FileAccess.Read, FileShare.Read); };
try
{
try { store.Deploy(manifestFile, true); throw new Exception("Expected atomic replace failure"); }
catch (OfflineWorldException ex) { Check(ex.Code == "deployment_rolled_back", "failed atomic replacement recovers cache automatically and reports rollback"); }
}
finally { held?.Dispose(); guard.OnCheck = null; }
Check(File.ReadAllBytes(sector).SequenceEqual(original) && originalOther.All(x => OfflineWorldStore.FileSha(x.Key) == x.Value), "failed deployment leaves all active files byte identical");
guard.Checks = 0;
guard.OnCheck = n => { if (n == 4) guard.Hosts = [host]; };
Throws<OfflineWorldException>(() => store.Deploy(manifestFile, true), "world loaded during backup is detected again before commit");
guard.OnCheck = null; guard.Hosts = [];
Check(File.ReadAllBytes(sector).SequenceEqual(original), "late world-use conflict leaves source unchanged");
Throws<OfflineWorldException>(() => store.Backup(world, Path.Combine(world, "nested-backup")), "backup destination cannot recurse into target save");
var snapshot = ToJson(store.Backup(world));
Check(snapshot.GetProperty("snapshot").GetProperty("files").GetArrayLength() == 6, "standalone offline backup covers all active files");
var parsed = HostStatus.ParseLog(new StringReader($"Environment.CommandLine: \"{host.ExecutablePath}\"\nLoading session: {world}\n"), host with { State = "unknown", WorldPath = null }, "fixture.log");
Check(parsed.State == "loaded_or_loading" && parsed.WorldPath == world, "host log identifies the current save only after executable identity matches");
parsed = HostStatus.ParseLog(new StringReader($"Environment.CommandLine: \"{host.ExecutablePath}\"\nLoading session: {world}\nMySession::Unload START\n"), host with { State = "unknown", WorldPath = null }, "fixture.log");
Check(parsed.WorldPath == world, "host protects the previous world until unload completes");
parsed = HostStatus.ParseLog(new StringReader($"Environment.CommandLine: \"{host.ExecutablePath}\"\nLoading session: {world}\nMySession::Unload END\n"), host with { State = "unknown", WorldPath = null }, "fixture.log");
Check(parsed.State == "unloaded" && parsed.WorldPath == null, "host recognizes completed unload without UI access");
parsed = HostStatus.ParseLog(new StringReader($"Environment.CommandLine: \"C:\\other.exe\"\nLoading session: {world}\n"), host with { State = "unknown", WorldPath = null }, "fixture.log");
Check(parsed.State == "unknown", "host rejects logs belonging to a different executable");
var cli = new CliApplication(worlds: store, host: guard);
using var stdout = new StringWriter(); using var stderr = new StringWriter();
int exit = await cli.RunAsync(["world", "deploy", "--manifest", manifestFile], stdout, stderr);
using var cliResult = JsonDocument.Parse(stdout.ToString());
Check(exit == 0 && !cliResult.RootElement.GetProperty("applied").GetBoolean() && stderr.ToString().Length == 0, "offline CLI returns structured dry run without resolving an Agent pipe");
}
}