using System.Diagnostics;
using System.Text.Json;
using XFEEDToolBox.Core.Data;
using XFEEDToolBox.Core.Models;
using XFEEDToolBox.Core.Native;
using XFEEDToolBox.Core.Navigation;
using XFEEDToolBox.Core.Session;
internal static class DockingFixtureAcceptance
{
// Explicit one-off native SDK test exception. No CG/trade/SCA/cruise flight.
public static async Task RunAsync(int pid,string report,string? sharedStopFile=null,CancellationToken cancellationToken=default)
{
report=Path.GetFullPath(report);if(File.Exists(report)||File.Exists(report+".jsonl"))throw new IOException("Use a fresh diagnostic report.");
Directory.CreateDirectory(Path.GetDirectoryName(report)!);
using var stop=CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);stop.CancelAfter(TimeSpan.FromMinutes(12));var token=stop.Token;var explicitStop=sharedStopFile??report+".stop";
var settings=ToolboxSettings.Load(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),"XFEstudio","XFEEDToolBox","settings.json"));
await using var journal=new JournalMonitor(settings.JournalDirectory);await journal.StartAsync();var initial=journal.State;
if(!initial.InGame||!initial.Docked||initial.CurrentShipId!=5||initial.CargoCount!=0||initial.CargoCapacity!=192||initial.MarketId is not >0
||NavigationSafety.HasExternalThreat(initial)||NavigationSafety.UnhealthyHull(initial))throw new InvalidOperationException("Healthy empty docked Corsair/5 required.");
var pipe=new NavigationPipeClient(pid);var hello=await pipe.CallAsync(new{op="describe"},token);
if(!hello.GetProperty("nativeDockingInputMapper").GetBoolean()||!hello.GetProperty("nativeDockingFixed075Trial").GetBoolean()
||hello.GetProperty("gameSha256").GetString()!=NativeSystemLocationReader.GameSha256)throw new NotSupportedException("Original mapper diagnostic is not loaded.");
var inventory=await pipe.CallAsync(new{op="commerce.inventory"},token);
if(!inventory.GetProperty("verified").GetBoolean()||inventory.GetProperty("count").GetInt32()!=0||inventory.GetProperty("capacity").GetInt32()!=192)throw new InvalidDataException("Original cargo is not empty.");
using var guardian=await PersistentProtectionProcess.StartOrReuseAsync(pid,Path.GetDirectoryName(report)!,token,allowStart:false);PersistentProtectionProcess.Current=guardian;
await using var protection=await FlightTestProtectionScope.ArmAsync(pid,exitForFailedHandoff:false);
using var source=new NativeCurrentSystemSource(pid,NativeSystemLocationReader.GameSha256,()=>journal.State);
var catalogue=await source.ReadLocationsAsync(token);var row=catalogue.Locations.Single(x=>x.MarketId==initial.MarketId);
var target=new SystemNavigationTarget(catalogue.SystemAddress,row.WorldAddress,row.Name,SystemTargetKind.Station,row.MarketId){NativeKey=row.Key,NativeKind=row.NativeKind,NativeIdentity=row.Identity};
Task BeforeInput(CancellationToken cancellation){cancellation.ThrowIfCancellationRequested();guardian.RequireReady(pid);NativeFlightTestProtection.CheckBeforeInput(pid);return Task.CompletedTask;}
var driver=new NativeSystemFlightControlDriver(pid,NativeSystemLocationReader.GameSha256,()=>journal.State,
new NativeGameInputChannel(pid,NativeSystemLocationReader.GameSha256,Path.Combine(AppContext.BaseDirectory,"PluginPackage")),BeforeInput,useNativeSupercruiseAssist:false);
var trialId=Guid.NewGuid().ToString("N");var start=DateTimeOffset.UtcNow;var launchSeen=false;var launchCompleted=false;var seedArmed=false;var persistent=false;var zero=false;var ai=false;var docked=false;var recovered=false;
string phase="preflight",failure="";JsonElement? proof=null,beforeZeroProof=null;DateTimeOffset? grantAt=null;var stageAt=start;
await using var log=new StreamWriter(new FileStream(report+".jsonl",FileMode.CreateNew,FileAccess.Write,FileShare.Read));
async Task Log(object value){await log.WriteLineAsync(JsonSerializer.Serialize(value,ToolboxSettings.JsonOptions));await log.FlushAsync();}
void SetPhase(string value){if(value==phase)return;phase=value;stageAt=DateTimeOffset.UtcNow;Console.WriteLine(value);}
async Task<SystemFlightFrame> Read()
{
while(true)
{
token.ThrowIfCancellationRequested();if(File.Exists(explicitStop))throw new OperationCanceledException("Diagnostic explicitly stopped.");
var current=journal.State;
if(current.CommanderId!=initial.CommanderId||current.CurrentShipId!=initial.CurrentShipId||current.LoadGameAt!=initial.LoadGameAt||current.CargoCount!=0||NavigationSafety.HasExternalThreat(current)||NavigationSafety.UnhealthyHull(current))throw new InvalidOperationException("Diagnostic session or safety identity changed.");
try{var frame=await driver.ReadSystemFlightAsync(token);if(frame.Mode is LocalFlightMode.Supercruise or LocalFlightMode.OrbitalCruise||frame.HeatPercent is >=80)throw new InvalidOperationException("Normal-space diagnostic safety boundary exceeded.");return frame;}
catch(Exception error)when(NavigationRecovery.CanRetry(error,token)){await Task.Delay(60,token);}
}
}
async Task Apply(SystemFlightFrame frame,Vector3d? direction,double? throttle,SystemNavigationAction actions=SystemNavigationAction.None)
=>await driver.ApplySystemFlightAsync(new(SystemNavigationPhase.NormalApproach,phase,direction,throttle,actions),frame,target,frame.ObservedAt.AddMilliseconds(250),token);
try
{
await driver.SelectAsync(target,token);await driver.RequestLaunchAsync(token);SetPhase("original-launch");
while(true)
{
var frame=await Read();var local=driver.LastTelemetry!.Value;var active=local.GetProperty("docking").GetProperty("nativeLaunchActive").GetBoolean();launchSeen|=active;
await Log(new{at=DateTimeOffset.UtcNow,phase,frame,local});
if(launchSeen&&!active&&!journal.State.Docked&&journal.State.Navigation.UndockedAt>=start.AddSeconds(-1))break;
if(DateTimeOffset.UtcNow-stageAt>TimeSpan.FromMinutes(4))throw new TimeoutException("Original launch did not complete.");await Task.Delay(80,token);
}
driver.ConfirmDockingValidationLaunchCompleted();launchCompleted=true;await driver.PrepareAsync(token);SetPhase("outward-clearance");
while(true)
{
var frame=await Read();var outward=(frame.Position-frame.TargetPosition).Unit();var angle=Vector3d.AngleDegrees(frame.Forward,outward);
var desired=frame.TargetDistance<5800?50d:0;var throttle=angle<=5&&desired>0?Math.Min(.3,desired/Math.Max(1,frame.MaximumNormalSpeed)):0;
await Apply(frame,outward,throttle);await Log(new{at=DateTimeOffset.UtcNow,phase,frame,local=driver.LastTelemetry});
if(frame.TargetDistance is >=4500 and <=7100&&frame.TargetDistance>=5800&&frame.Speed<=5&&angle<=5)break;
if(frame.TargetDistance>7200||DateTimeOffset.UtcNow-stageAt>TimeSpan.FromMinutes(4))throw new InvalidOperationException("Validated outward test volume was not reached.");
await Task.Delay(60,token);
}
SetPhase("original-absolute-075");proof=await driver.BeginDockingValidation075Async(trialId,token);seedArmed=true;await Log(new{at=DateTimeOffset.UtcNow,phase,proof});
while(true)
{
proof=await driver.ReadDockingValidationAsync(trialId,token);await Log(new{at=DateTimeOffset.UtcNow,phase,proof});
var stage=proof.Value.GetProperty("stage").GetUInt32();if(stage==3&&DockingValidationProof.Persistent075(proof.Value)){persistent=true;beforeZeroProof=proof.Value.Clone();break;}if(stage==6||DateTimeOffset.UtcNow-stageAt>TimeSpan.FromSeconds(2))throw new InvalidOperationException("Persistent .75 reproduction not formed: "+proof.Value);
await Task.Delay(20,token);
}
SetPhase("original-atc");var requestFrame=await Read();await Apply(requestFrame,null,null,SystemNavigationAction.RequestDocking|SystemNavigationAction.ReleaseFlightAxes);
while(true)
{
var frame=await Read();await Log(new{at=DateTimeOffset.UtcNow,phase,frame,local=driver.LastTelemetry});
if(frame.Clearance?.Allows(target,DateTimeOffset.UtcNow)==true){grantAt=DateTimeOffset.UtcNow;break;}
if(frame.TargetDistance>7200||DateTimeOffset.UtcNow-stageAt>TimeSpan.FromSeconds(3))throw new TimeoutException("Original ATC did not grant inside the bounded outward diagnostic volume.");await Task.Delay(50,token);
}
SetPhase("original-zero-and-ai");
while(true)
{
var frame=await Read();
if(frame.DockingAssist!=NativeAssistState.Engaged)await Apply(frame,null,null,SystemNavigationAction.EnableDockingAssist|SystemNavigationAction.ReleaseFlightAxes);
proof=await driver.ReadDockingValidationAsync(trialId,token);zero|=beforeZeroProof is {} before&&DockingValidationProof.CompletedZero(before,proof.Value);ai|=frame.DockingAssist==NativeAssistState.Engaged;
await Log(new{at=DateTimeOffset.UtcNow,phase,frame,proof,local=driver.LastTelemetry});
if(zero&&ai)break;if(DateTimeOffset.UtcNow-grantAt>TimeSpan.FromSeconds(2))throw new InvalidOperationException("Actual .75->0/AI handoff not confirmed inside two seconds.");await Task.Delay(35,token);
}
SetPhase("native-docking");
while(true)
{
var frame=await Read();await Log(new{at=DateTimeOffset.UtcNow,phase,frame,local=driver.LastTelemetry});
if(journal.State.Docked&&journal.State.MarketId==target.MarketId){docked=true;break;}
if(DateTimeOffset.UtcNow-stageAt>TimeSpan.FromMinutes(5))throw new TimeoutException("Native AI has not confirmed actual docking.");await Task.Delay(100,token);
}
SetPhase("passed");
}
catch(Exception error)
{
failure=error.ToString();await Log(new{at=DateTimeOffset.UtcNow,phase,failure});Console.WriteLine(error.Message);
try{await driver.ReleaseSystemFlightAsync();}catch(Exception release){await Log(new{releaseFailure=release.ToString()});}
if(!journal.State.Docked&&!cancellationToken.IsCancellationRequested&&!File.Exists(explicitStop))
{
try
{
SetPhase("menu-solo-recovery");var workflow=new NativeRelogWorkflow(new NativeRelogChannel(pid,NativeSystemLocationReader.GameSha256,returnToMenuTrial:true),()=>journal.State){Timeout=TimeSpan.FromMinutes(8)};
using var recoveryStop=CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);recoveryStop.CancelAfter(TimeSpan.FromMinutes(8));
workflow.Progress+=Console.WriteLine;await workflow.RunAsync(recoveryStop.Token);recovered=true;
}
catch(Exception recovery){await Log(new{recoveryFailure=recovery.ToString(),clientTerminated=false});}
}
}
finally
{
if(seedArmed)try{await driver.CancelDockingValidationAsync(trialId,CancellationToken.None);}catch{}
try{await driver.ReleaseSystemFlightAsync();}catch{}
PersistentProtectionProcess.Current=null;
await File.WriteAllTextAsync(report,JsonSerializer.Serialize(new{passed=persistent&&zero&&ai&&docked&&failure.Length==0,pid,start,finishedAt=DateTimeOffset.UtcNow,station=target.Name,marketId=target.MarketId,phase,launchCompleted,persistent075=persistent,zeroVerified=zero,aiEngaged=ai,actualDocked=docked,beforeZeroProof,proof,recoveredViaMainMenu=recovered,clientTerminated=false,supercruiseUsed=false,gameSupercruiseAssistUsed=false,tradeOrdersSent=0,failure},ToolboxSettings.JsonOptions));
}
if(failure.Length!=0)throw new InvalidOperationException("Native docking diagnostic failed; original report preserved.");
}
}
using System.Diagnostics;
using System.Text.Json;
using XFEEDToolBox.Core.Data;
using XFEEDToolBox.Core.Models;
using XFEEDToolBox.Core.Native;
using XFEEDToolBox.Core.Navigation;
using XFEEDToolBox.Core.Session;
internal static class DockingFixtureAcceptance
{
// Explicit one-off native SDK test exception. No CG/trade/SCA/cruise flight.
public static async Task RunAsync(int pid,string report,string? sharedStopFile=null,CancellationToken cancellationToken=default)
{
report=Path.GetFullPath(report);if(File.Exists(report)||File.Exists(report+".jsonl"))throw new IOException("Use a fresh diagnostic report.");
Directory.CreateDirectory(Path.GetDirectoryName(report)!);
using var stop=CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);stop.CancelAfter(TimeSpan.FromMinutes(12));var token=stop.Token;var explicitStop=sharedStopFile??report+".stop";
var settings=ToolboxSettings.Load(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),"XFEstudio","XFEEDToolBox","settings.json"));
await using var journal=new JournalMonitor(settings.JournalDirectory);await journal.StartAsync();var initial=journal.State;
if(!initial.InGame||!initial.Docked||initial.CurrentShipId!=5||initial.CargoCount!=0||initial.CargoCapacity!=192||initial.MarketId is not >0
||NavigationSafety.HasExternalThreat(initial)||NavigationSafety.UnhealthyHull(initial))throw new InvalidOperationException("Healthy empty docked Corsair/5 required.");
var pipe=new NavigationPipeClient(pid);var hello=await pipe.CallAsync(new{op="describe"},token);
if(!hello.GetProperty("nativeDockingInputMapper").GetBoolean()||!hello.GetProperty("nativeDockingFixed075Trial").GetBoolean()
||hello.GetProperty("gameSha256").GetString()!=NativeSystemLocationReader.GameSha256)throw new NotSupportedException("Original mapper diagnostic is not loaded.");
var inventory=await pipe.CallAsync(new{op="commerce.inventory"},token);
if(!inventory.GetProperty("verified").GetBoolean()||inventory.GetProperty("count").GetInt32()!=0||inventory.GetProperty("capacity").GetInt32()!=192)throw new InvalidDataException("Original cargo is not empty.");
using var guardian=await PersistentProtectionProcess.StartOrReuseAsync(pid,Path.GetDirectoryName(report)!,token,allowStart:false);PersistentProtectionProcess.Current=guardian;
await using var protection=await FlightTestProtectionScope.ArmAsync(pid,exitForFailedHandoff:false);
using var source=new NativeCurrentSystemSource(pid,NativeSystemLocationReader.GameSha256,()=>journal.State);
var catalogue=await source.ReadLocationsAsync(token);var row=catalogue.Locations.Single(x=>x.MarketId==initial.MarketId);
var target=new SystemNavigationTarget(catalogue.SystemAddress,row.WorldAddress,row.Name,SystemTargetKind.Station,row.MarketId){NativeKey=row.Key,NativeKind=row.NativeKind,NativeIdentity=row.Identity};
Task BeforeInput(CancellationToken cancellation){cancellation.ThrowIfCancellationRequested();guardian.RequireReady(pid);NativeFlightTestProtection.CheckBeforeInput(pid);return Task.CompletedTask;}
var driver=new NativeSystemFlightControlDriver(pid,NativeSystemLocationReader.GameSha256,()=>journal.State,
new NativeGameInputChannel(pid,NativeSystemLocationReader.GameSha256,Path.Combine(AppContext.BaseDirectory,"PluginPackage")),BeforeInput,useNativeSupercruiseAssist:false);
var trialId=Guid.NewGuid().ToString("N");var start=DateTimeOffset.UtcNow;var launchSeen=false;var launchCompleted=false;var seedArmed=false;var persistent=false;var zero=false;var ai=false;var docked=false;var recovered=false;
string phase="preflight",failure="";JsonElement? proof=null,beforeZeroProof=null;DateTimeOffset? grantAt=null;var stageAt=start;
await using var log=new StreamWriter(new FileStream(report+".jsonl",FileMode.CreateNew,FileAccess.Write,FileShare.Read));
async Task Log(object value){await log.WriteLineAsync(JsonSerializer.Serialize(value,ToolboxSettings.JsonOptions));await log.FlushAsync();}
void SetPhase(string value){if(value==phase)return;phase=value;stageAt=DateTimeOffset.UtcNow;Console.WriteLine(value);}
async Task<SystemFlightFrame> Read()
{
while(true)
{
token.ThrowIfCancellationRequested();if(File.Exists(explicitStop))throw new OperationCanceledException("Diagnostic explicitly stopped.");
var current=journal.State;
if(current.CommanderId!=initial.CommanderId||current.CurrentShipId!=initial.CurrentShipId||current.LoadGameAt!=initial.LoadGameAt||current.CargoCount!=0||NavigationSafety.HasExternalThreat(current)||NavigationSafety.UnhealthyHull(current))throw new InvalidOperationException("Diagnostic session or safety identity changed.");
try{var frame=await driver.ReadSystemFlightAsync(token);if(frame.Mode is LocalFlightMode.Supercruise or LocalFlightMode.OrbitalCruise||frame.HeatPercent is >=80)throw new InvalidOperationException("Normal-space diagnostic safety boundary exceeded.");return frame;}
catch(Exception error)when(NavigationRecovery.CanRetry(error,token)){await Task.Delay(60,token);}
}
}
async Task Apply(SystemFlightFrame frame,Vector3d? direction,double? throttle,SystemNavigationAction actions=SystemNavigationAction.None)
=>await driver.ApplySystemFlightAsync(new(SystemNavigationPhase.NormalApproach,phase,direction,throttle,actions),frame,target,frame.ObservedAt.AddMilliseconds(250),token);
try
{
await driver.SelectAsync(target,token);await driver.RequestLaunchAsync(token);SetPhase("original-launch");
while(true)
{
var frame=await Read();var local=driver.LastTelemetry!.Value;var active=local.GetProperty("docking").GetProperty("nativeLaunchActive").GetBoolean();launchSeen|=active;
await Log(new{at=DateTimeOffset.UtcNow,phase,frame,local});
if(launchSeen&&!active&&!journal.State.Docked&&journal.State.Navigation.UndockedAt>=start.AddSeconds(-1))break;
if(DateTimeOffset.UtcNow-stageAt>TimeSpan.FromMinutes(4))throw new TimeoutException("Original launch did not complete.");await Task.Delay(80,token);
}
driver.ConfirmDockingValidationLaunchCompleted();launchCompleted=true;await driver.PrepareAsync(token);SetPhase("outward-clearance");
while(true)
{
var frame=await Read();var outward=(frame.Position-frame.TargetPosition).Unit();var angle=Vector3d.AngleDegrees(frame.Forward,outward);
var desired=frame.TargetDistance<5800?50d:0;var throttle=angle<=5&&desired>0?Math.Min(.3,desired/Math.Max(1,frame.MaximumNormalSpeed)):0;
await Apply(frame,outward,throttle);await Log(new{at=DateTimeOffset.UtcNow,phase,frame,local=driver.LastTelemetry});
if(frame.TargetDistance is >=4500 and <=7100&&frame.TargetDistance>=5800&&frame.Speed<=5&&angle<=5)break;
if(frame.TargetDistance>7200||DateTimeOffset.UtcNow-stageAt>TimeSpan.FromMinutes(4))throw new InvalidOperationException("Validated outward test volume was not reached.");
await Task.Delay(60,token);
}
SetPhase("original-absolute-075");proof=await driver.BeginDockingValidation075Async(trialId,token);seedArmed=true;await Log(new{at=DateTimeOffset.UtcNow,phase,proof});
while(true)
{
proof=await driver.ReadDockingValidationAsync(trialId,token);await Log(new{at=DateTimeOffset.UtcNow,phase,proof});
var stage=proof.Value.GetProperty("stage").GetUInt32();if(stage==3&&DockingValidationProof.Persistent075(proof.Value)){persistent=true;beforeZeroProof=proof.Value.Clone();break;}if(stage==6||DateTimeOffset.UtcNow-stageAt>TimeSpan.FromSeconds(2))throw new InvalidOperationException("Persistent .75 reproduction not formed: "+proof.Value);
await Task.Delay(20,token);
}
SetPhase("original-atc");var requestFrame=await Read();await Apply(requestFrame,null,null,SystemNavigationAction.RequestDocking|SystemNavigationAction.ReleaseFlightAxes);
while(true)
{
var frame=await Read();await Log(new{at=DateTimeOffset.UtcNow,phase,frame,local=driver.LastTelemetry});
if(frame.Clearance?.Allows(target,DateTimeOffset.UtcNow)==true){grantAt=DateTimeOffset.UtcNow;break;}
if(frame.TargetDistance>7200||DateTimeOffset.UtcNow-stageAt>TimeSpan.FromSeconds(3))throw new TimeoutException("Original ATC did not grant inside the bounded outward diagnostic volume.");await Task.Delay(50,token);
}
SetPhase("original-zero-and-ai");
while(true)
{
var frame=await Read();
if(frame.DockingAssist!=NativeAssistState.Engaged)await Apply(frame,null,null,SystemNavigationAction.EnableDockingAssist|SystemNavigationAction.ReleaseFlightAxes);
proof=await driver.ReadDockingValidationAsync(trialId,token);zero|=beforeZeroProof is {} before&&DockingValidationProof.CompletedZero(before,proof.Value);ai|=frame.DockingAssist==NativeAssistState.Engaged;
await Log(new{at=DateTimeOffset.UtcNow,phase,frame,proof,local=driver.LastTelemetry});
if(zero&&ai)break;if(DateTimeOffset.UtcNow-grantAt>TimeSpan.FromSeconds(2))throw new InvalidOperationException("Actual .75->0/AI handoff not confirmed inside two seconds.");await Task.Delay(35,token);
}
SetPhase("native-docking");
while(true)
{
var frame=await Read();await Log(new{at=DateTimeOffset.UtcNow,phase,frame,local=driver.LastTelemetry});
if(journal.State.Docked&&journal.State.MarketId==target.MarketId){docked=true;break;}
if(DateTimeOffset.UtcNow-stageAt>TimeSpan.FromMinutes(5))throw new TimeoutException("Native AI has not confirmed actual docking.");await Task.Delay(100,token);
}
SetPhase("passed");
}
catch(Exception error)
{
failure=error.ToString();await Log(new{at=DateTimeOffset.UtcNow,phase,failure});Console.WriteLine(error.Message);
try{await driver.ReleaseSystemFlightAsync();}catch(Exception release){await Log(new{releaseFailure=release.ToString()});}
if(!journal.State.Docked&&!cancellationToken.IsCancellationRequested&&!File.Exists(explicitStop))
{
try
{
SetPhase("menu-solo-recovery");var workflow=new NativeRelogWorkflow(new NativeRelogChannel(pid,NativeSystemLocationReader.GameSha256,returnToMenuTrial:true),()=>journal.State){Timeout=TimeSpan.FromMinutes(8)};
using var recoveryStop=CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);recoveryStop.CancelAfter(TimeSpan.FromMinutes(8));
workflow.Progress+=Console.WriteLine;await workflow.RunAsync(recoveryStop.Token);recovered=true;
}
catch(Exception recovery){await Log(new{recoveryFailure=recovery.ToString(),clientTerminated=false});}
}
}
finally
{
if(seedArmed)try{await driver.CancelDockingValidationAsync(trialId,CancellationToken.None);}catch{}
try{await driver.ReleaseSystemFlightAsync();}catch{}
PersistentProtectionProcess.Current=null;
await File.WriteAllTextAsync(report,JsonSerializer.Serialize(new{passed=persistent&&zero&&ai&&docked&&failure.Length==0,pid,start,finishedAt=DateTimeOffset.UtcNow,station=target.Name,marketId=target.MarketId,phase,launchCompleted,persistent075=persistent,zeroVerified=zero,aiEngaged=ai,actualDocked=docked,beforeZeroProof,proof,recoveredViaMainMenu=recovered,clientTerminated=false,supercruiseUsed=false,gameSupercruiseAssistUsed=false,tradeOrdersSent=0,failure},ToolboxSettings.JsonOptions));
}
if(failure.Length!=0)throw new InvalidOperationException("Native docking diagnostic failed; original report preserved.");
}
}