feat(launcher): Campaign LA LA3 — AcDream.Launcher.Core profile store, composer, supervisor, status tailer

New AcDream.Launcher.Core (BCL-only, ProjectReference: AcDream.Platform
ONLY) plus tests/AcDream.Launcher.Core.Tests, both registered in
AcDream.slnx. This is the file-contract orchestrator core the Avalonia
launcher (LA4) will bind to — the game solution (Core/Runtime/App/
Headless) stays entirely out of this dependency graph, so the launcher
can never accidentally grow a game-protocol coupling.

- Profiles/: LauncherProfileStore owns launcher-profiles.json (spec §5
  schema: version 1, servers[]/accounts[]/characters[]), strict
  camelCase System.Text.Json (UnmappedMemberHandling.Disallow), typed
  CRUD (add/edit/remove server; add/edit/remove account; edit character
  settings), and MergeRoster (fold a reported roster into an account's
  characters[] while preserving user-owned launchMode/plugins/
  loginCommands, adding new rows with default guiSelect, and retaining
  rows absent from the roster — they may be pending-delete). 0600 on
  Linux via File.SetUnixFileMode after save.
- Launching/: SessionConfigComposer builds the pinned session-config
  contract (Headless K1 shape + plugins/loginCommands/
  loginCommandDelayMs/statusFile) from a profile character + install
  record — character selector omitted entirely for guiSelect, policy
  {id:"idle"} only for headless, credential always standardInput/
  session. Passwords never enter this document (proven by a dedicated
  test). LauncherProcessSupervisor spawns a host, feeds the password to
  stdin then closes it, and exposes Starting/Running/Exited lifecycle;
  Stop calls CloseMainWindow falling back to Kill after a timeout, both
  reachable through an injectable ILauncherChildProcess/factory seam so
  the state machine is unit-testable without real OS process timing.
- Status/: StatusEventParser decodes the v1 status.jsonl vocabulary
  (started/connected/characterList/enteredWorld/pluginLoaded/
  pluginFailed/disconnected/exited); an unrecognized "e" or a malformed
  line degrades to a typed Unknown event rather than throwing.
  StatusFileTailer incrementally reads new lines, tolerating a
  not-yet-existing file and a partial trailing line (only advances its
  read position past confirmed '\n' boundaries; a truncated tail is
  simply re-read next poll, never parsed early).
- Integrity/: streaming SHA-256 + hex verify for later pak/download
  checks (LA9/LA10).

Tests: 71 passed (profile CRUD + roster-merge matrix + strict-schema
rejection; composer golden-shape tests for gui/guiSelect/headless +
password-absence; supervisor tests against both an injected fake child
(state-machine determinism) and a real spawned `dotnet --version`
child (genuine cross-platform stdin/exit-code proof); tailer tests
incl. partial-line and not-yet-existing-file; SHA-256 tests). Verified
green on Windows (Release) and native WSL/Linux (Release) — the Linux
0600 test executes its real assertion body under WSL rather than
early-returning.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Erik 2026-08-14 15:49:13 +02:00
parent cb6502c8a5
commit 37d74e4402
31 changed files with 3131 additions and 0 deletions

View file

@ -0,0 +1,120 @@
using System.Diagnostics;
namespace AcDream.Launcher.Core.Launching;
/// <summary>
/// Thin seam over <see cref="System.Diagnostics.Process"/> so
/// <see cref="LauncherProcessSupervisor"/>'s lifecycle and Stop
/// (CloseMainWindow, falling back to Kill after a timeout) state machine
/// can be unit-tested against an in-memory fake without spawning a real
/// OS process or depending on real window-message timing — both
/// "injectable for tests" per Campaign LA spec §3.
/// </summary>
public interface ILauncherChildProcess : IDisposable
{
bool HasExited { get; }
int ExitCode { get; }
/// <summary>The child's redirected stdin. The supervisor writes the
/// account password here (followed by a newline) and then closes it —
/// never anywhere else.</summary>
TextWriter StandardInput { get; }
/// <summary>Fires exactly once, when the child process terminates
/// (mirrors <see cref="Process.Exited"/> with
/// <c>EnableRaisingEvents</c> on).</summary>
event EventHandler? Exited;
void Start();
/// <summary>Mirrors <see cref="Process.CloseMainWindow"/> — requests
/// a graceful close via WM_CLOSE. Returns false for a console/no-
/// window process (never throws), matching the real API.</summary>
bool CloseMainWindow();
/// <summary>Mirrors <see cref="Process.Kill(bool)"/> with
/// <c>entireProcessTree: true</c>.</summary>
void Kill();
bool WaitForExit(TimeSpan timeout);
}
/// <summary>Creates <see cref="ILauncherChildProcess"/> instances from a
/// <see cref="LauncherProcessSpec"/>.</summary>
public interface ILauncherChildProcessFactory
{
ILauncherChildProcess Create(LauncherProcessSpec spec);
}
/// <summary>Real-process implementation used in production.</summary>
public sealed class SystemChildProcessFactory : ILauncherChildProcessFactory
{
public ILauncherChildProcess Create(LauncherProcessSpec spec) =>
new SystemChildProcess(spec);
}
internal sealed class SystemChildProcess : ILauncherChildProcess
{
private readonly Process _process;
private bool _raisingEnabled;
internal SystemChildProcess(LauncherProcessSpec spec)
{
ArgumentNullException.ThrowIfNull(spec);
var startInfo = new ProcessStartInfo
{
FileName = spec.ExecutablePath,
RedirectStandardInput = true,
UseShellExecute = false,
};
foreach (string argument in spec.Arguments)
{
startInfo.ArgumentList.Add(argument);
}
if (!string.IsNullOrEmpty(spec.WorkingDirectory))
{
startInfo.WorkingDirectory = spec.WorkingDirectory;
}
_process = new Process { StartInfo = startInfo };
}
public bool HasExited => _process.HasExited;
public int ExitCode => _process.ExitCode;
public TextWriter StandardInput => _process.StandardInput;
public event EventHandler? Exited;
public void Start()
{
_process.EnableRaisingEvents = true;
_process.Exited += OnExited;
_raisingEnabled = true;
_process.Start();
}
public bool CloseMainWindow() => _process.CloseMainWindow();
public void Kill() => _process.Kill(entireProcessTree: true);
public bool WaitForExit(TimeSpan timeout) => _process.WaitForExit(timeout);
public void Dispose()
{
if (_raisingEnabled)
{
_process.Exited -= OnExited;
}
_process.Dispose();
}
private void OnExited(object? sender, EventArgs e) =>
Exited?.Invoke(this, EventArgs.Empty);
}

View file

@ -0,0 +1,12 @@
namespace AcDream.Launcher.Core.Launching;
/// <summary>
/// The DAT/pak locations a completed install (LA9) records and every
/// session-config composition consumes for
/// <see cref="SessionContentDescriptor"/>. SHA-256/version bookkeeping
/// for the install record itself is LA9/LA10 scope; this slice only
/// needs the two paths a session config requires.
/// </summary>
public sealed record LauncherInstallRecord(
string DatDirectory,
string PreparedAssetPath);

View file

@ -0,0 +1,15 @@
namespace AcDream.Launcher.Core.Launching;
/// <summary>
/// What to spawn: the host executable path + argument list (both
/// injectable per Campaign LA spec §3, e.g. <c>AcDream.Headless --config
/// &lt;path&gt;</c> or <c>AcDream.App --session-config &lt;path&gt;</c>).
/// Deliberately carries no credential field — the password is a separate
/// transient parameter to <see cref="LauncherProcessSupervisor.Start"/>
/// that flows only to the child's stdin, never into this spec, an
/// argument list, or a process environment.
/// </summary>
public sealed record LauncherProcessSpec(
string ExecutablePath,
IReadOnlyList<string> Arguments,
string? WorkingDirectory = null);

View file

@ -0,0 +1,146 @@
namespace AcDream.Launcher.Core.Launching;
/// <summary>
/// Spawns a host process (App/Headless), feeds the account password to
/// its stdin then closes it, and supervises its lifetime (Campaign LA
/// spec §3/§6). One supervisor instance owns exactly one child process
/// for its lifetime — start a new supervisor per launched session.
/// </summary>
public sealed class LauncherProcessSupervisor : IDisposable
{
private readonly ILauncherChildProcessFactory _factory;
private readonly object _gate = new();
private ILauncherChildProcess? _process;
public LauncherProcessSupervisor(ILauncherChildProcessFactory? factory = null)
{
_factory = factory ?? new SystemChildProcessFactory();
}
public LauncherSessionState State { get; private set; } = LauncherSessionState.Starting;
/// <summary>Set once <see cref="State"/> reaches
/// <see cref="LauncherSessionState.Exited"/>; null before then.
/// </summary>
public int? ExitCode { get; private set; }
/// <summary>Fires on every <see cref="LauncherSessionState"/>
/// transition, in order.</summary>
public event EventHandler<LauncherSessionState>? StateChanged;
/// <summary>
/// Spawns the child described by <paramref name="spec"/>, writes
/// <paramref name="password"/> (if any) followed by a newline to its
/// stdin, then closes stdin. The password is never written anywhere
/// else — not into <paramref name="spec"/>, not into an environment
/// variable, not logged.
/// </summary>
public void Start(LauncherProcessSpec spec, string? password)
{
ArgumentNullException.ThrowIfNull(spec);
ILauncherChildProcess process;
lock (_gate)
{
if (_process is not null)
{
throw new InvalidOperationException(
"This supervisor already owns a process; start a new "
+ "supervisor per launched session.");
}
process = _factory.Create(spec);
process.Exited += OnProcessExited;
_process = process;
}
SetState(LauncherSessionState.Starting);
try
{
process.Start();
if (password is not null)
{
process.StandardInput.Write(password);
process.StandardInput.Write('\n');
process.StandardInput.Flush();
}
process.StandardInput.Close();
}
catch
{
lock (_gate)
{
process.Exited -= OnProcessExited;
_process = null;
}
throw;
}
SetState(LauncherSessionState.Running);
}
/// <summary>
/// Requests a graceful stop (CloseMainWindow), falling back to Kill
/// if the process has not exited within <paramref name="timeout"/>.
/// A no-op if <see cref="Start"/> was never called or the process has
/// already exited.
/// </summary>
public void Stop(TimeSpan timeout)
{
ILauncherChildProcess? process;
lock (_gate)
{
process = _process;
}
if (process is null || process.HasExited)
{
return;
}
process.CloseMainWindow();
if (!process.WaitForExit(timeout) && !process.HasExited)
{
process.Kill();
}
}
private void OnProcessExited(object? sender, EventArgs e)
{
ILauncherChildProcess? process;
lock (_gate)
{
process = _process;
}
ExitCode = process is { HasExited: true } ? process.ExitCode : null;
SetState(LauncherSessionState.Exited);
}
private void SetState(LauncherSessionState state)
{
lock (_gate)
{
State = state;
}
StateChanged?.Invoke(this, state);
}
public void Dispose()
{
lock (_gate)
{
if (_process is not null)
{
_process.Exited -= OnProcessExited;
_process.Dispose();
_process = null;
}
}
}
}

View file

@ -0,0 +1,21 @@
namespace AcDream.Launcher.Core.Launching;
/// <summary>Lifecycle of a launched host process, per Campaign LA spec §3
/// ("supervise lifetime ... surface typed session state").</summary>
public enum LauncherSessionState
{
/// <summary>The child process has been created and the credential
/// handed off, but has not yet reached <see cref="Running"/>.</summary>
Starting,
/// <summary>The child process is spawned and its stdin has been
/// closed. Says nothing about game-level connection state — that
/// comes from the status stream (see
/// <c>AcDream.Launcher.Core.Status</c>).</summary>
Running,
/// <summary>The child process has exited. See
/// <see cref="LauncherProcessSupervisor.ExitCode"/> for the exit
/// code.</summary>
Exited,
}

View file

@ -0,0 +1,167 @@
using System.Text.Json;
using System.Text.Json.Serialization;
using AcDream.Launcher.Core.Profiles;
using AcDream.Platform;
namespace AcDream.Launcher.Core.Launching;
/// <summary>The composed session-config document plus the two per-launch
/// paths derived from the session id, per Campaign LA spec §6.</summary>
public sealed record ComposedSessionConfig(
string SessionId,
string ConfigFilePath,
string StatusFilePath,
SessionConfigDocument Document);
/// <summary>
/// Builds the per-launch <see cref="SessionConfigDocument"/> from a
/// profile character + install record (Campaign LA spec §6). Passwords
/// NEVER appear in the composed document — the credential is always the
/// <c>standardInput</c> provider; the launcher feeds the password to the
/// child process's stdin separately (<see cref="LauncherProcessSupervisor"/>).
/// </summary>
public static class SessionConfigComposer
{
internal static readonly JsonSerializerOptions SerializerOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
WriteIndented = true,
};
/// <summary>
/// Builds the document and the paths it would be written to under
/// <c>&lt;CacheDirectory&gt;/launcher/sessions/&lt;sessionId&gt;/</c>,
/// without touching disk. <paramref name="sessionId"/> is caller-
/// supplied so composition stays a pure function of its inputs
/// (golden-file tests pass a fixed id).
/// </summary>
public static ComposedSessionConfig Compose(
ServerProfile server,
AccountProfile account,
CharacterProfile character,
LauncherInstallRecord install,
ApplicationPathSet paths,
string sessionId,
int? loginCommandDelayMs = null)
{
ArgumentNullException.ThrowIfNull(server);
ArgumentNullException.ThrowIfNull(account);
ArgumentNullException.ThrowIfNull(character);
ArgumentNullException.ThrowIfNull(install);
ArgumentNullException.ThrowIfNull(paths);
ArgumentException.ThrowIfNullOrWhiteSpace(sessionId);
string sessionDirectory = Path.Combine(
paths.CacheDirectory,
"launcher",
"sessions",
sessionId);
string configFilePath = Path.Combine(sessionDirectory, "session.json");
string statusFilePath = Path.Combine(sessionDirectory, "status.jsonl");
SessionCharacterSelector? selector = character.LaunchMode == LaunchMode.GuiSelect
? null
: BuildSelector(character);
SessionPolicyDescriptor? policy = character.LaunchMode == LaunchMode.Headless
? new SessionPolicyDescriptor()
: null;
var descriptor = new SessionDescriptor
{
Id = sessionId,
Endpoint = new SessionEndpointDescriptor
{
Host = server.Host,
Port = server.Port,
},
Account = account.Account,
Character = selector,
Policy = policy,
Credential = new SessionCredentialDescriptor(),
Plugins = character.Plugins.Count > 0 ? [.. character.Plugins] : null,
LoginCommands = character.LoginCommands.Count > 0
? [.. character.LoginCommands]
: null,
LoginCommandDelayMs = loginCommandDelayMs,
StatusFile = statusFilePath,
};
var document = new SessionConfigDocument
{
Process = new SessionProcessSettings
{
Paths = new SessionPathOverrides(),
Content = new SessionContentDescriptor
{
DatDirectory = install.DatDirectory,
PreparedAssetPath = install.PreparedAssetPath,
},
},
Sessions = [descriptor],
};
return new ComposedSessionConfig(
sessionId,
configFilePath,
statusFilePath,
document);
}
/// <summary>Composes and writes <c>session.json</c> to
/// <see cref="ComposedSessionConfig.ConfigFilePath"/>, creating the
/// per-session directory. The status file itself is created by the
/// launched host, not the launcher.</summary>
public static ComposedSessionConfig ComposeAndWrite(
ServerProfile server,
AccountProfile account,
CharacterProfile character,
LauncherInstallRecord install,
ApplicationPathSet paths,
string sessionId,
int? loginCommandDelayMs = null)
{
ComposedSessionConfig composed = Compose(
server,
account,
character,
install,
paths,
sessionId,
loginCommandDelayMs);
string? directory = Path.GetDirectoryName(composed.ConfigFilePath);
if (!string.IsNullOrEmpty(directory))
{
Directory.CreateDirectory(directory);
}
using FileStream stream = File.Create(composed.ConfigFilePath);
JsonSerializer.Serialize(stream, composed.Document, SerializerOptions);
return composed;
}
/// <summary>Serializes the composed document exactly as
/// <see cref="ComposeAndWrite"/> would write it — used by golden-file
/// tests that assert on the JSON text without touching disk.</summary>
public static string Serialize(SessionConfigDocument document) =>
JsonSerializer.Serialize(document, SerializerOptions);
private static SessionCharacterSelector BuildSelector(CharacterProfile character)
{
if (CharacterIdFormat.TryParse(character.Id, out uint id))
{
return new SessionCharacterSelector { Id = id };
}
if (!string.IsNullOrWhiteSpace(character.Name))
{
return new SessionCharacterSelector { Name = character.Name };
}
throw new InvalidOperationException(
"Character has neither a usable id nor a name to select by.");
}
}

View file

@ -0,0 +1,134 @@
namespace AcDream.Launcher.Core.Launching;
/// <summary>
/// The per-launch session-config document written to
/// <c>&lt;CacheDirectory&gt;/launcher/sessions/&lt;sessionId&gt;/session.json</c>
/// and consumed by <c>AcDream.Headless --config</c> / (LA1)
/// <c>AcDream.App --session-config</c>.
///
/// <para>
/// PINNED CONTRACT (Campaign LA plan §LA3): this is the Slice K1
/// <c>HeadlessConfiguration</c> version-1 shape extended with optional
/// launcher fields (<c>plugins</c>, <c>loginCommands</c>,
/// <c>loginCommandDelayMs</c>, <c>statusFile</c>). Launcher.Core defines
/// its own DTOs rather than referencing <c>AcDream.Headless</c> — the
/// project reference set for this assembly is <c>AcDream.Platform</c>
/// ONLY (no game-solution dependency; see LA3 acceptance).
/// Serialized camelCase via <see cref="SessionConfigComposer"/>, with
/// null optional members omitted from the written JSON.
/// </para>
/// </summary>
public sealed class SessionConfigDocument
{
public int Version { get; init; } = 1;
public SessionProcessSettings Process { get; init; } = new();
public List<SessionDescriptor> Sessions { get; init; } = [];
}
public sealed class SessionProcessSettings
{
public SessionPathOverrides Paths { get; init; } = new();
public SessionContentDescriptor Content { get; init; } = new();
}
/// <summary>All three members are optional overrides; a host resolves
/// its own default <c>ApplicationPathSet</c> when a member is
/// omitted.</summary>
public sealed class SessionPathOverrides
{
public string? ConfigDirectory { get; init; }
public string? DataDirectory { get; init; }
public string? CacheDirectory { get; init; }
}
// NOTE: these DTOs are write-only (Launcher.Core composes and serializes
// them; it never deserializes a session-config document back). Members
// that the pinned contract calls "always present" therefore use plain
// non-nullable defaults rather than C#'s `required` modifier — a
// `required` member cannot be given a `= new()` default on a containing
// type without a [SetsRequiredMembers] constructor, and correctness here
// is enforced by SessionConfigComposer's tests, not the compiler.
public sealed class SessionContentDescriptor
{
public string DatDirectory { get; init; } = string.Empty;
public string PreparedAssetPath { get; init; } = string.Empty;
}
public sealed class SessionDescriptor
{
public string Id { get; init; } = string.Empty;
public SessionEndpointDescriptor Endpoint { get; init; } = new();
public string Account { get; init; } = string.Empty;
/// <summary>Exactly one of index/id/name when present. OMITTED
/// entirely for a <c>guiSelect</c> launch (retail character-select
/// screen instead of auto-enter).</summary>
public SessionCharacterSelector? Character { get; init; }
/// <summary>Present only for a <c>headless</c> launch (the <c>idle</c>
/// bot policy). Omitted for <c>gui</c>/<c>guiSelect</c>.</summary>
public SessionPolicyDescriptor? Policy { get; init; }
public SessionCredentialDescriptor Credential { get; init; } = new();
/// <summary>Omitted (never an empty array) when the character has no
/// configured plugin set.</summary>
public List<string>? Plugins { get; init; }
/// <summary>Omitted (never an empty array) when the character has no
/// configured login commands.</summary>
public List<string>? LoginCommands { get; init; }
/// <summary>Overrides the host's default 500&#160;ms inter-command
/// delay when set; omitted otherwise.</summary>
public int? LoginCommandDelayMs { get; init; }
public string StatusFile { get; init; } = string.Empty;
}
public sealed class SessionEndpointDescriptor
{
public string Host { get; init; } = string.Empty;
public int Port { get; init; }
}
/// <summary>Exactly one of <see cref="Index"/>/<see cref="Id"/>/
/// <see cref="Name"/> is set by <see cref="SessionConfigComposer"/>.
/// </summary>
public sealed class SessionCharacterSelector
{
public int? Index { get; init; }
public uint? Id { get; init; }
public string? Name { get; init; }
}
/// <summary>Campaign LA composes exactly the <c>idle</c> bot policy (LA2)
/// for headless launches — the launcher never asks for any other
/// policy id.</summary>
public sealed class SessionPolicyDescriptor
{
public string Id { get; init; } = "idle";
}
/// <summary>Always the <c>standardInput</c> provider — the launcher pipes
/// the account password to the child's stdin and never places it in the
/// session-config document, process arguments, or environment (see
/// <see cref="LauncherProcessSupervisor"/>).</summary>
public sealed class SessionCredentialDescriptor
{
public string Provider { get; init; } = "standardInput";
public string Reference { get; init; } = "session";
}