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,22 @@
using System.Text.Json.Serialization;
namespace AcDream.Launcher.Core.Profiles;
/// <summary>
/// One account under a server, per Campaign LA spec §5. The password is
/// plaintext by explicit user decision
/// (<c>claude-memory/project_launcher_direction.md</c>) — never written
/// anywhere except this file, never logged, never placed in a session
/// config or process argument/environment (see
/// <see cref="AcDream.Launcher.Core.Launching.SessionConfigComposer"/>).
/// </summary>
public sealed class AccountProfile
{
[JsonRequired]
public string Account { get; set; } = string.Empty;
[JsonRequired]
public string Password { get; set; } = string.Empty;
public List<CharacterProfile> Characters { get; set; } = [];
}

View file

@ -0,0 +1,32 @@
using System.Globalization;
namespace AcDream.Launcher.Core.Profiles;
/// <summary>
/// Converts between the wire <c>uint</c> character GUID and the
/// launcher-profile hex-string representation (<c>"0x5000000A"</c>,
/// matching the convention used throughout the project, e.g. the
/// <c>+Acdream</c> test character's <c>0x5000000A</c> in CLAUDE.md).
/// </summary>
public static class CharacterIdFormat
{
public static string ToHexString(uint id) =>
"0x" + id.ToString("X8", CultureInfo.InvariantCulture);
public static bool TryParse(string? text, out uint id)
{
id = 0;
if (string.IsNullOrWhiteSpace(text))
return false;
ReadOnlySpan<char> span = text.AsSpan().Trim();
if (span.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
span = span[2..];
return uint.TryParse(
span,
NumberStyles.HexNumber,
CultureInfo.InvariantCulture,
out id);
}
}

View file

@ -0,0 +1,31 @@
using System.Text.Json.Serialization;
namespace AcDream.Launcher.Core.Profiles;
/// <summary>
/// One character row under an account, per Campaign LA spec §5. The
/// <see cref="Id"/>/<see cref="Name"/> pair is the launcher-maintained
/// cache (fed by status-stream <c>characterList</c> events and roster
/// probes via <see cref="LauncherProfileStore.MergeRoster"/>);
/// <see cref="LaunchMode"/>/<see cref="Plugins"/>/<see cref="LoginCommands"/>
/// are user-owned settings that a roster merge must never clobber.
/// </summary>
public sealed class CharacterProfile
{
[JsonRequired]
public string Name { get; set; } = string.Empty;
/// <summary>
/// Hex-formatted character GUID (e.g. <c>"0x5000000A"</c>), matching
/// the convention used elsewhere in the project. Null only for a
/// hand-authored fixture/profile entry that has never been through a
/// roster merge.
/// </summary>
public string? Id { get; set; }
public LaunchMode LaunchMode { get; set; } = LaunchMode.GuiSelect;
public List<string> Plugins { get; set; } = [];
public List<string> LoginCommands { get; set; } = [];
}

View file

@ -0,0 +1,19 @@
namespace AcDream.Launcher.Core.Profiles;
/// <summary>
/// One roster row as reported by a host's <c>characterList</c> status
/// event or an on-demand probe launch (Campaign LA spec §3/§6). Mirrors
/// the wire shape of <c>AcDream.Core.Net.Messages.CharacterList.Character</c>
/// (<c>uint Id, string Name, uint SecondsGreyedOut</c>) — Launcher.Core
/// does not reference Core.Net, so this is an independent, intentionally
/// identical shape fed by the status-stream parser
/// (<see cref="AcDream.Launcher.Core.Status.CharacterListStatusEvent"/>).
/// <see cref="SecondsGreyedOut"/> is carried for completeness but is
/// NEVER persisted into <see cref="CharacterProfile"/> — ACE reports a
/// constant 1 during the pending-delete grace window (a boolean, not a
/// countdown), and the profile schema (§5) has no field for it.
/// </summary>
public readonly record struct CharacterRosterEntry(
uint Id,
string Name,
uint SecondsGreyedOut);

View file

@ -0,0 +1,35 @@
namespace AcDream.Launcher.Core.Profiles;
/// <summary>
/// Per-character launch behaviour (Campaign LA spec §5). Stored on each
/// <see cref="CharacterProfile"/> and read by
/// <see cref="AcDream.Launcher.Core.Launching.SessionConfigComposer"/> to
/// decide the shape of the composed session-config document.
///
/// <para>
/// Serialized as camelCase text (<c>"gui"</c>/<c>"guiSelect"</c>/
/// <c>"headless"</c>) via the explicit
/// <c>new JsonStringEnumConverter(JsonNamingPolicy.CamelCase, ...)</c>
/// registered in <see cref="LauncherProfileStore"/>'s serializer options
/// — deliberately NOT a per-type <c>[JsonConverter]</c> attribute, which
/// uses exact member-name casing (<c>"Gui"</c>) regardless of the
/// ambient <c>PropertyNamingPolicy</c>.
/// </para>
/// </summary>
public enum LaunchMode
{
/// <summary>Launch the graphical client straight into the world as
/// this character.</summary>
Gui,
/// <summary>Launch the graphical client but stop at the retail
/// character-select screen — no character selector is sent. This is
/// the default for a character that has never had its launch mode set
/// explicitly.</summary>
GuiSelect,
/// <summary>Launch the no-window host running the <c>idle</c> bot
/// policy (enter world, run plugins/login commands, stay until
/// stopped).</summary>
Headless,
}

View file

@ -0,0 +1,16 @@
using System.Text.Json.Serialization;
namespace AcDream.Launcher.Core.Profiles;
/// <summary>
/// Root document for <c>launcher-profiles.json</c> (Campaign LA spec §5)
/// — the launcher's ONLY credential/profile store. Loaded and saved by
/// <see cref="LauncherProfileStore"/>.
/// </summary>
public sealed class LauncherProfileDocument
{
[JsonRequired]
public int Version { get; set; } = LauncherProfileStore.CurrentVersion;
public List<ServerProfile> Servers { get; set; } = [];
}

View file

@ -0,0 +1,17 @@
namespace AcDream.Launcher.Core.Profiles;
/// <summary>Thrown for a malformed <c>launcher-profiles.json</c> document
/// or an invalid CRUD operation against <see cref="LauncherProfileStore"/>
/// (unknown target, duplicate name, etc.).</summary>
public sealed class LauncherProfileException : Exception
{
public LauncherProfileException(string message)
: base(message)
{
}
public LauncherProfileException(string message, Exception innerException)
: base(message, innerException)
{
}
}

View file

@ -0,0 +1,395 @@
using System.Text.Json;
using System.Text.Json.Serialization;
using AcDream.Platform;
namespace AcDream.Launcher.Core.Profiles;
/// <summary>
/// Load/save/CRUD owner for <c>launcher-profiles.json</c> (Campaign LA
/// spec §5) — the launcher's ONLY credential/profile store, and the
/// binding surface the Avalonia UI (slice LA4) mutates directly.
///
/// <para>
/// A store instance holds the current in-memory <see cref="Document"/>
/// after <see cref="Load"/>; every CRUD method mutates that document in
/// place so callers can chain <c>store.AddServer(...); store.Save();</c>
/// without re-threading a returned document through every call.
/// </para>
/// </summary>
public sealed class LauncherProfileStore
{
internal const int CurrentVersion = 1;
private static readonly JsonSerializerOptions SerializerOptions = new()
{
AllowTrailingCommas = false,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = false,
ReadCommentHandling = JsonCommentHandling.Disallow,
UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow,
WriteIndented = true,
Converters =
{
new JsonStringEnumConverter(
JsonNamingPolicy.CamelCase,
allowIntegerValues: false),
},
};
public LauncherProfileStore(string filePath)
{
ArgumentException.ThrowIfNullOrWhiteSpace(filePath);
FilePath = Path.GetFullPath(filePath);
Document = new LauncherProfileDocument();
}
/// <summary>Resolve the store at the canonical location under
/// <see cref="ApplicationPathSet.ConfigDirectory"/>
/// (<c>%APPDATA%\acdream\launcher-profiles.json</c> /
/// <c>~/.config/acdream/launcher-profiles.json</c>).</summary>
public static LauncherProfileStore ForApplicationPaths(ApplicationPathSet paths)
{
ArgumentNullException.ThrowIfNull(paths);
return new LauncherProfileStore(
Path.Combine(paths.ConfigDirectory, "launcher-profiles.json"));
}
public string FilePath { get; }
public LauncherProfileDocument Document { get; private set; }
/// <summary>
/// Loads <see cref="Document"/> from <see cref="FilePath"/>. A
/// missing file is not an error — it resolves to a fresh empty
/// document (version 1, no servers), matching a never-launched
/// installation. Returns true when a file was actually read.
/// </summary>
public bool Load()
{
if (!File.Exists(FilePath))
{
Document = new LauncherProfileDocument();
return false;
}
LauncherProfileDocument? document;
using (FileStream stream = File.OpenRead(FilePath))
{
try
{
document = JsonSerializer.Deserialize<LauncherProfileDocument>(
stream,
SerializerOptions);
}
catch (JsonException ex)
{
throw new LauncherProfileException(
$"'{FilePath}' is not a valid launcher profile document.",
ex);
}
}
if (document is null)
{
throw new LauncherProfileException($"'{FilePath}' is empty.");
}
if (document.Version != CurrentVersion)
{
throw new LauncherProfileException(
$"Unsupported launcher-profiles version {document.Version}; "
+ $"expected {CurrentVersion}.");
}
Document = document;
return true;
}
/// <summary>
/// Persists <see cref="Document"/> to <see cref="FilePath"/> via a
/// write-then-atomic-rename so a crash mid-write never leaves a
/// truncated credentials file. On Linux, restricts the final file to
/// owner read/write (0600) per Campaign LA's plaintext-credential
/// decision (spec §5, decisions log).
/// </summary>
public void Save()
{
string? directory = Path.GetDirectoryName(FilePath);
if (!string.IsNullOrEmpty(directory))
{
Directory.CreateDirectory(directory);
}
string tempPath = FilePath + ".tmp";
using (FileStream stream = File.Create(tempPath))
{
JsonSerializer.Serialize(stream, Document, SerializerOptions);
}
File.Move(tempPath, FilePath, overwrite: true);
if (OperatingSystem.IsLinux())
{
File.SetUnixFileMode(
FilePath,
UnixFileMode.UserRead | UnixFileMode.UserWrite);
}
}
// --- Server CRUD -----------------------------------------------
public ServerProfile AddServer(string name, string host, int port)
{
ArgumentException.ThrowIfNullOrWhiteSpace(name);
ArgumentException.ThrowIfNullOrWhiteSpace(host);
RequireValidPort(port);
if (FindServer(name) is not null)
{
throw new LauncherProfileException(
$"A server named '{name}' already exists.");
}
var server = new ServerProfile { Name = name, Host = host, Port = port };
Document.Servers.Add(server);
return server;
}
public void EditServer(
string name,
string? newName = null,
string? newHost = null,
int? newPort = null)
{
ServerProfile server = FindServerOrThrow(name);
if (newName is not null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(newName);
if (!string.Equals(newName, server.Name, StringComparison.Ordinal)
&& FindServer(newName) is not null)
{
throw new LauncherProfileException(
$"A server named '{newName}' already exists.");
}
server.Name = newName;
}
if (newHost is not null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(newHost);
server.Host = newHost;
}
if (newPort is not null)
{
RequireValidPort(newPort.Value);
server.Port = newPort.Value;
}
}
public void RemoveServer(string name)
{
ServerProfile server = FindServerOrThrow(name);
Document.Servers.Remove(server);
}
// --- Account CRUD ------------------------------------------------
public AccountProfile AddAccount(string serverName, string account, string password)
{
ArgumentException.ThrowIfNullOrWhiteSpace(account);
ArgumentNullException.ThrowIfNull(password);
ServerProfile server = FindServerOrThrow(serverName);
if (FindAccount(server, account) is not null)
{
throw new LauncherProfileException(
$"Account '{account}' already exists on server '{serverName}'.");
}
var profile = new AccountProfile { Account = account, Password = password };
server.Accounts.Add(profile);
return profile;
}
public void EditAccount(
string serverName,
string account,
string? newAccount = null,
string? newPassword = null)
{
ServerProfile server = FindServerOrThrow(serverName);
AccountProfile profile = FindAccountOrThrow(server, account);
if (newAccount is not null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(newAccount);
if (!string.Equals(newAccount, profile.Account, StringComparison.Ordinal)
&& FindAccount(server, newAccount) is not null)
{
throw new LauncherProfileException(
$"Account '{newAccount}' already exists on server '{serverName}'.");
}
profile.Account = newAccount;
}
if (newPassword is not null)
{
profile.Password = newPassword;
}
}
public void RemoveAccount(string serverName, string account)
{
ServerProfile server = FindServerOrThrow(serverName);
AccountProfile profile = FindAccountOrThrow(server, account);
server.Accounts.Remove(profile);
}
// --- Character settings (roster-driven add/remove; user-edited settings) ---
/// <summary>
/// Edits the user-owned settings of an existing character row. There
/// is no manual add/remove for characters — the roster (
/// <see cref="MergeRoster"/>) is the only source of new rows, per
/// spec §5/§6.
/// </summary>
public void EditCharacter(
string serverName,
string account,
string characterName,
LaunchMode? launchMode = null,
IReadOnlyList<string>? plugins = null,
IReadOnlyList<string>? loginCommands = null)
{
ServerProfile server = FindServerOrThrow(serverName);
AccountProfile profile = FindAccountOrThrow(server, account);
CharacterProfile character = FindCharacterOrThrow(profile, characterName);
if (launchMode is not null)
{
character.LaunchMode = launchMode.Value;
}
if (plugins is not null)
{
character.Plugins = [.. plugins];
}
if (loginCommands is not null)
{
character.LoginCommands = [.. loginCommands];
}
}
/// <summary>
/// Folds a reported character roster into an account's
/// <see cref="AccountProfile.Characters"/> (Campaign LA spec §3/§5/
/// §6): every roster entry either updates the name of an existing
/// row (matched by <see cref="CharacterProfile.Id"/>) while
/// PRESERVING that row's user settings (<see cref="LaunchMode"/>,
/// <see cref="CharacterProfile.Plugins"/>,
/// <see cref="CharacterProfile.LoginCommands"/>), or is inserted as a
/// new row with default settings (<see cref="LaunchMode.GuiSelect"/>,
/// no plugins, no login commands). Existing rows absent from the
/// roster are RETAINED unchanged — they may simply be pending-delete
/// (ACE keeps deleted characters queryable during the grace window)
/// or the roster snapshot may be partial; this store never deletes a
/// character row on the caller's behalf.
/// </summary>
public void MergeRoster(
string serverName,
string account,
IReadOnlyList<CharacterRosterEntry> roster)
{
ArgumentNullException.ThrowIfNull(roster);
ServerProfile server = FindServerOrThrow(serverName);
AccountProfile profile = FindAccountOrThrow(server, account);
foreach (CharacterRosterEntry entry in roster)
{
string idText = CharacterIdFormat.ToHexString(entry.Id);
CharacterProfile? existing = profile.Characters.Find(
character => string.Equals(
character.Id,
idText,
StringComparison.OrdinalIgnoreCase));
// Defensive fallback for a hand-edited file where a character
// row was added with a name but no id yet.
existing ??= profile.Characters.Find(
character => character.Id is null
&& string.Equals(
character.Name,
entry.Name,
StringComparison.Ordinal));
if (existing is not null)
{
existing.Id = idText;
existing.Name = entry.Name;
continue;
}
profile.Characters.Add(new CharacterProfile
{
Id = idText,
Name = entry.Name,
LaunchMode = LaunchMode.GuiSelect,
Plugins = [],
LoginCommands = [],
});
}
}
// --- Lookups -------------------------------------------------------
private ServerProfile? FindServer(string name) =>
Document.Servers.Find(
server => string.Equals(server.Name, name, StringComparison.Ordinal));
private ServerProfile FindServerOrThrow(string name)
{
ArgumentException.ThrowIfNullOrWhiteSpace(name);
return FindServer(name)
?? throw new LauncherProfileException($"No server named '{name}'.");
}
private static AccountProfile? FindAccount(ServerProfile server, string account) =>
server.Accounts.Find(
candidate => string.Equals(candidate.Account, account, StringComparison.Ordinal));
private static AccountProfile FindAccountOrThrow(ServerProfile server, string account)
{
ArgumentException.ThrowIfNullOrWhiteSpace(account);
return FindAccount(server, account)
?? throw new LauncherProfileException(
$"No account '{account}' on server '{server.Name}'.");
}
private static CharacterProfile FindCharacterOrThrow(
AccountProfile profile,
string characterName)
{
ArgumentException.ThrowIfNullOrWhiteSpace(characterName);
return profile.Characters.Find(
character => string.Equals(
character.Name,
characterName,
StringComparison.Ordinal))
?? throw new LauncherProfileException(
$"No character '{characterName}' on account '{profile.Account}'.");
}
private static void RequireValidPort(int port)
{
if (port is < 1 or > 65535)
{
throw new LauncherProfileException(
$"Port {port} is outside the valid 1-65535 range.");
}
}
}

View file

@ -0,0 +1,19 @@
using System.Text.Json.Serialization;
namespace AcDream.Launcher.Core.Profiles;
/// <summary>One server entry, per Campaign LA spec §5 (manual add — no
/// published server-list import this campaign).</summary>
public sealed class ServerProfile
{
[JsonRequired]
public string Name { get; set; } = string.Empty;
[JsonRequired]
public string Host { get; set; } = string.Empty;
[JsonRequired]
public int Port { get; set; }
public List<AccountProfile> Accounts { get; set; } = [];
}