From 787beddecd75b020e900af33622ddb08c007024f Mon Sep 17 00:00:00 2001 From: Gordon Breuer Date: Mon, 26 Oct 2026 13:01:16 +0000 Subject: [PATCH 1/2] Use generated JSON contracts for storage, IPC, bridge and CLI output --- .github/workflows/json-compatibility.yml | 52 +++++++ .../0004-generated-json-contracts.md | 61 ++++++++ scripts/deployment_experiments.py | 6 +- scripts/json_compatibility.py | 67 +++++++++ src/SidePulse.Cli/About.cs | 10 +- src/SidePulse.Cli/Agents.cs | 2 +- src/SidePulse.Cli/Animations.cs | 10 +- src/SidePulse.Cli/Commands.cs | 8 +- src/SidePulse.Cli/Hooks.cs | 8 +- src/SidePulse.Cli/HostManagement.cs | 6 +- src/SidePulse.Cli/Installation.cs | 37 +++-- src/SidePulse.Cli/JsonContracts.cs | 100 +++++++++++++ src/SidePulse.Cli/Settings.cs | 2 +- src/SidePulse.Cli/SidePulse.Cli.csproj | 1 + src/SidePulse.Cli/TerminalMode.cs | 2 +- src/SidePulse.Cli/Updates.cs | 10 +- src/SidePulse.Core/AnimationLibrary.cs | 4 +- src/SidePulse.Core/CoreJson.cs | 40 ++++++ src/SidePulse.Core/HookConfiguration.cs | 2 +- src/SidePulse.Core/HookInstallation.cs | 9 +- src/SidePulse.Core/LinkStore.cs | 11 +- src/SidePulse.Core/OpenCodePlugin.cs | 2 +- src/SidePulse.Core/PhoneBridge.cs | 9 +- src/SidePulse.Core/Preferences.cs | 4 +- src/SidePulse.Core/UpdatePackage.cs | 2 +- src/SidePulse.Core/UpdateTransaction.cs | 6 +- src/SidePulse.Core/UserInstallation.cs | 6 +- tests/SidePulse.Tests/CoreTests.cs | 2 + tests/SidePulse.Tests/JsonContractTests.cs | 133 ++++++++++++++++++ 29 files changed, 530 insertions(+), 82 deletions(-) create mode 100644 .github/workflows/json-compatibility.yml create mode 100644 docs/decisions/0004-generated-json-contracts.md create mode 100644 scripts/json_compatibility.py create mode 100644 src/SidePulse.Cli/JsonContracts.cs create mode 100644 src/SidePulse.Core/CoreJson.cs create mode 100644 tests/SidePulse.Tests/JsonContractTests.cs diff --git a/.github/workflows/json-compatibility.yml b/.github/workflows/json-compatibility.yml new file mode 100644 index 0000000..058e471 --- /dev/null +++ b/.github/workflows/json-compatibility.yml @@ -0,0 +1,52 @@ +name: JSON compatibility +on: + pull_request: + paths: + - 'src/**' + - 'scripts/json_compatibility.py' + - '.github/workflows/json-compatibility.yml' + workflow_dispatch: + inputs: + baseline_ref: + description: Baseline commit or tag to publish with the same SDK + required: true + default: 763ab97ae34175f3ef69331f42bb3740581b0d4f +permissions: + contents: read +concurrency: + group: json-compatibility-${{ github.ref }} + cancel-in-progress: true +jobs: + compare: + strategy: + fail-fast: false + matrix: + os: [windows-latest, ubuntu-latest, macos-latest] + runs-on: ${{ matrix.os }} + timeout-minutes: 15 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + path: candidate + persist-credentials: false + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + path: baseline + ref: ${{ inputs.baseline_ref || github.event.pull_request.base.sha }} + persist-credentials: false + - uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6 + with: + dotnet-version: 10.0.x + - name: Compare public JSON contracts with the baseline + shell: pwsh + run: | + $prefix = if ($IsWindows) { 'win' } elseif ($IsMacOS) { 'osx' } else { 'linux' } + $rid = "$prefix-$([System.Runtime.InteropServices.RuntimeInformation]::ProcessArchitecture.ToString().ToLowerInvariant())" + $binary = if ($IsWindows) { 'spn.exe' } else { 'spn' } + dotnet --info > sdk-info.txt + foreach ($source in @('baseline', 'candidate')) { + dotnet publish "$source/src/SidePulse.Cli" -c Release -r $rid --self-contained true -p:NuGetLockFilePath=obj/packages.publish.lock.json -o "$source/published" + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + } + python candidate/scripts/json_compatibility.py "baseline/published/$binary" "candidate/published/$binary" + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } diff --git a/docs/decisions/0004-generated-json-contracts.md b/docs/decisions/0004-generated-json-contracts.md new file mode 100644 index 0000000..f356714 --- /dev/null +++ b/docs/decisions/0004-generated-json-contracts.md @@ -0,0 +1,61 @@ +# Generated JSON contracts + +Date: 2026-10-26. Delivery: #60; CLI dependency follow-up: #61. + +## Decision + +Use explicit records and System.Text.Json generated metadata for application files, +transport envelopes, IPC and CLI JSON. The executable disables reflection-based +JSON serialization by default. Unknown contracts fail explicitly; they do not fall +back to runtime reflection. Core services remain independent of terminal output +and receive their existing caller-owned HTTP clients/credential protectors. + +`CoreJsonContext` registers persisted core records and the phone bridge envelope. +`CliJsonContext` registers public output and helper-plan records. The separate +`IpcJsonContext` keeps the host's numeric wire enums. Runtime option converters use +the generic enum converter, not the dynamic converter factory. + +## Compatibility + +- Keep existing property names/order, casing, null fields, enum representations + and constructor defaults. Lowercase CLI reply properties are deliberate wire + names; existing public model properties retain their PascalCase names. +- Preferences, profiles, encrypted link plaintext and ownership records retain + their current schema. Link/ownership record implementation types are internal; + encryption/protection and credential identities are unchanged. +- Package/install/update records retain case-insensitive reads, indentation and + format-1/format-2 handling. Startup/helper/rollback checks remain active. +- Host messages retain numeric enums and ProtocolVersion 1. CLI output retains + named enums. Old unversioned event defaults and numeric host responses still read. +- The bridge retains `aps.content-available`, `leds` and `data.sidepulse_event_id`; + no alert field or push token is added to JSON output. Token-bearing PhoneLink + objects are not registered as public CLI output contracts. +- Serializer contexts receive copies of caller options: a context encapsulates + its options, so sharing an options instance between Core and CLI contexts would + break uninstall/helper serialization. Copies also preserve caller mutability + without retaining a stale cached snapshot. + +## Evidence and remaining work + +JsonContractTests compares generated output bytes with the prior anonymous/file +shapes and fixed legacy fixtures; it covers defaults, enum differences, protected +link payload shape, caller-owned options and unknown/secret output rejection. +The normal CLI and lifecycle smoke run with reflection JSON disabled. + +```bash +python3 scripts/json_compatibility.py /path/to/baseline/spn /path/to/candidate/spn +``` + +This compares 22 read-only public JSON/error responses. Only executable-directory +and derived receipt-key differences are normalized. The isolated application config +must remain absent. Run against a stopped host; a live externally changing session +is not deterministic compatibility evidence. JSON compatibility CI publishes both +revisions with the same SDK on native Windows/Linux/macOS and runs this comparison. + +Application JSON IL2026 diagnostics are removed, including the generic +`JsonArray.Add` overload (use the concrete JsonNode overload instead). +Local strict partial-trim/ReadyToRun now reaches the third-party +Spectre.Console.Cli IL2104 warning; AOT reports that dependency's IL3050 rather than +our JSON APIs. #61 owns the remaining CLI metadata/dynamic-code compatibility. +Publishing experiments no longer re-enable reflection JSON for smaller variants. +Default release trimming/AOT flags stay unchanged until their full acceptance. diff --git a/scripts/deployment_experiments.py b/scripts/deployment_experiments.py index 0b0c2f4..72104a0 100644 --- a/scripts/deployment_experiments.py +++ b/scripts/deployment_experiments.py @@ -18,9 +18,9 @@ MODES = { 'full': [], 'raw-trim': ['PublishTrimmed=true'], - 'partial-strict': ['PublishTrimmed=true', 'TrimMode=partial', 'JsonSerializerIsReflectionEnabledByDefault=true'], - 'partial': ['PublishTrimmed=true', 'TrimMode=partial', 'JsonSerializerIsReflectionEnabledByDefault=true'], - 'partial-r2r': ['PublishTrimmed=true', 'TrimMode=partial', 'JsonSerializerIsReflectionEnabledByDefault=true', 'PublishReadyToRun=true'], + 'partial-strict': ['PublishTrimmed=true', 'TrimMode=partial'], + 'partial': ['PublishTrimmed=true', 'TrimMode=partial'], + 'partial-r2r': ['PublishTrimmed=true', 'TrimMode=partial', 'PublishReadyToRun=true'], 'aot': ['PublishAot=true', 'PublishSingleFile=false', 'DebugType=None', 'StripSymbols=true'], } diff --git a/scripts/json_compatibility.py b/scripts/json_compatibility.py new file mode 100644 index 0000000..2e9f2f4 --- /dev/null +++ b/scripts/json_compatibility.py @@ -0,0 +1,67 @@ +"""Compare public read-only JSON responses with a published baseline executable.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import subprocess +import tempfile + +COMMANDS = [ + ['state', 'working', '--dry-run', '--json'], + ['state', 'waiting', '--brightness', '42', '--dry-run', '--json'], + ['settings', 'show', '--json'], ['install', '--status', '--json'], + ['uninstall', '--dry-run', '--json'], ['update', 'status', '--json'], + ['host', 'status', '--json'], ['devices', '--json'], ['dashboard', '--json'], + ['doctor', '--json'], ['link', 'list', '--json'], ['agents', 'list', '--json'], + ['animations', 'list', '--json'], + ['animations', 'validate', 'solid-green', '--model', 'dot', '--json'], + ['animations', 'preview', 'solid-green', '--model', 'dot', '--at', '100', '--json'], + ['animations', 'export', 'solid-green', '--model', 'dot', '--json'], + ['docs', '--offline', '--json'], ['about', 'info', '--json'], + ['about', 'github', '--json'], ['about', 'credits', '--json'], + ['about', 'licenses', '--full', '--json'], + ['state', 'not-a-state', '--json'], +] + + +def normalize(value, executable): + if isinstance(value, dict): + return {key: normalize(item, executable) for key, item in value.items()} + if isinstance(value, list): + return [normalize(item, executable) for item in value] + if isinstance(value, str): + target = str(executable.parent).rstrip('/\\') + if os.name == 'nt': + target = target.upper() + key = hashlib.sha256(target.encode('utf-8')).hexdigest().upper()[:24] + return value.replace(str(executable.parent), '').replace(key, '') + return value + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('baseline', type=Path) + parser.add_argument('candidate', type=Path) + args = parser.parse_args() + baseline, candidate = args.baseline.resolve(), args.candidate.resolve() + with tempfile.TemporaryDirectory(prefix='spn JSON compatibility ') as temporary: + environment = dict(os.environ, SIDEPULSE_NET_HOME=str(Path(temporary) / 'config')) + for command in COMMANDS: + results = [] + for executable in (baseline, candidate): + response = subprocess.run([str(executable), *command], env=environment, + capture_output=True, text=True, timeout=15) + channel = response.stdout if response.returncode == 0 else response.stderr + try: + value = normalize(json.loads(channel), executable) + except ValueError as error: + raise AssertionError(f'Invalid JSON for {command}, exit {response.returncode}') from error + results.append((response.returncode, value)) + assert results[0] == results[1], (command, results) + assert not (Path(temporary) / 'config').exists(), 'Read-only compatibility probes created configuration' + print(f'{len(COMMANDS)} public JSON command/error responses match baseline.') + + +if __name__ == '__main__': + main() diff --git a/src/SidePulse.Cli/About.cs b/src/SidePulse.Cli/About.cs index 6f61e31..1caed86 100644 --- a/src/SidePulse.Cli/About.cs +++ b/src/SidePulse.Cli/About.cs @@ -29,7 +29,7 @@ public static IReadOnlyList Dependencies get { using var stream = Assembly.GetManifestResourceStream("SidePulse.Cli.Dependencies.json") ?? throw new IOException("Dependency credits are missing."); - return JsonSerializer.Deserialize(stream, new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!; + return JsonSerializer.Deserialize(stream, CliJson.Info(new JsonSerializerOptions { PropertyNameCaseInsensitive = true }))!; } } public static IReadOnlyList LicenseResources => Assembly.GetManifestResourceNames().Where(n => n.Contains(".Licenses.", StringComparison.Ordinal)).Order(StringComparer.Ordinal).ToArray(); @@ -46,7 +46,7 @@ public static int Link(string url, AboutSettings settings) try { Process.Start(new ProcessStartInfo(url) { UseShellExecute = true }); } catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException) { throw new IOException("Could not open the browser. Open this URL manually: " + url); } } - if (settings.Json) Output.Print(new { url, opened = settings.Open }); else Console.WriteLine(url); + if (settings.Json) Output.Print(new LinkReply(url, settings.Open)); else Console.WriteLine(url); return 0; } } @@ -54,7 +54,7 @@ public sealed class AboutCommand : Command { public override int Execute(CommandContext context, AboutSettings settings, CancellationToken cancellationToken) { - if (settings.Json) Output.Print(new { name = "SidePulse.NET", version = ProjectInfo.Version, license = "MIT", unofficial = true, website = ProjectInfo.Website, github = ProjectInfo.Github, upstream = ProjectInfo.Upstream }); + if (settings.Json) Output.Print(new AboutReply("SidePulse.NET", ProjectInfo.Version, "MIT", true, ProjectInfo.Website, ProjectInfo.Github, ProjectInfo.Upstream)); else Console.WriteLine($"SidePulse.NET {ProjectInfo.Version}\nUnofficial .NET companion · MIT\nOriginal SidePulse by Peter Kuhar / InteliWEAR\n{ProjectInfo.Github}"); return 0; } @@ -85,7 +85,7 @@ public sealed class CreditsCommand : Command { public override int Execute(CommandContext context, AboutSettings settings, CancellationToken cancellationToken) { - if (settings.Json) Output.Print(new { project = "Gordon Breuer / Anheledir", upstream = "Peter Kuhar / InteliWEAR", dependencies = ProjectInfo.Dependencies }); + if (settings.Json) Output.Print(new CreditsReply("Gordon Breuer / Anheledir", "Peter Kuhar / InteliWEAR", ProjectInfo.Dependencies)); else { Console.WriteLine("SidePulse.NET: Gordon Breuer / Anheledir\nSidePulse hardware, protocol and original animations: Peter Kuhar / InteliWEAR\n" + ProjectInfo.Upstream); @@ -102,7 +102,7 @@ public override int Execute(CommandContext context, AboutSettings settings, Canc var resources = ProjectInfo.LicenseResources; var runtimeDirectory = Path.Combine(AppContext.BaseDirectory, "third-party", "dotnet"); var runtime = Directory.Exists(runtimeDirectory) ? Directory.GetFiles(runtimeDirectory).Order(StringComparer.Ordinal).ToArray() : []; - if (settings.Json) Output.Print(new { project = "MIT", dependencies = ProjectInfo.Dependencies, notices = resources.Select(r => new { name = r, text = settings.Full ? ProjectInfo.LicenseText(r) : null }), runtimeNotices = runtime.Select(r => new { name = Path.GetFileName(r), text = settings.Full ? File.ReadAllText(r) : null }) }); + if (settings.Json) Output.Print(new LicensesReply("MIT", ProjectInfo.Dependencies, resources.Select(r => new LicenseNotice(r, settings.Full ? ProjectInfo.LicenseText(r) : null)).ToArray(), runtime.Select(r => new LicenseNotice(Path.GetFileName(r), settings.Full ? File.ReadAllText(r) : null)).ToArray())); else { Console.WriteLine("SidePulse.NET · MIT"); diff --git a/src/SidePulse.Cli/Agents.cs b/src/SidePulse.Cli/Agents.cs index 83ec447..1159ce6 100644 --- a/src/SidePulse.Cli/Agents.cs +++ b/src/SidePulse.Cli/Agents.cs @@ -59,7 +59,7 @@ public override int Execute(CommandContext context, AgentSettings settings, Canc { var generated = HookConfiguration.Generate(settings.Agent, HookConfiguration.Executable(settings.Executable), OperatingSystem.IsWindows()); var status = settings.Installation.Install(settings.Target, settings.Agent, generated, settings.DryRun); - if (settings.Json) Output.Print(new { status, managedHooks = settings.DryRun ? generated : null }); + if (settings.Json) Output.Print(new AgentInstallReply(status, settings.DryRun ? generated : null)); else { AnsiConsole.WriteLine($"{status.State}: {status.Target}"); diff --git a/src/SidePulse.Cli/Animations.cs b/src/SidePulse.Cli/Animations.cs index 2b1bf14..f2f1c55 100644 --- a/src/SidePulse.Cli/Animations.cs +++ b/src/SidePulse.Cli/Animations.cs @@ -45,7 +45,7 @@ public override int Execute(CommandContext context, PatternSettings settings, Ca var program = settings.File is null && settings.Name is { } name && System.IO.File.Exists(name) ? AnimationLibrary.WithBrightness(new(System.IO.File.ReadAllText(name)), settings.Brightness) : settings.Read(); var animation = Animation.Parse(program, settings.Model); - if (settings.Json) Output.Print(new { valid = true, model = settings.Model, bytes = program.ByteCount, lines = program.LineCount, instructions = animation.Instructions.Count }); + if (settings.Json) Output.Print(new ValidationReply(true, settings.Model, program.ByteCount, program.LineCount, animation.Instructions.Count)); else Console.WriteLine($"Valid ({program.ByteCount} bytes, {program.LineCount} lines, {settings.Model})."); return 0; } @@ -122,7 +122,7 @@ public override async Task ExecuteAsync(CommandContext context, PreviewSett if (settings.Json) { var models = settings.Both ? Enum.GetValues() : [settings.Model]; - Output.Print(models.Select(m => { var selected = settings.File is null ? AnimationLibrary.WithBrightness(AnimationLibrary.Default.Get(settings.Name!, m), settings.Brightness) : program; var player = new AnimationPlayer(Animation.Parse(selected, m)); player.Advance(settings.At); return new { model = m, at = settings.At, colors = player.Frame.Select(c => c.ToString()).ToArray() }; }).ToArray()); + Output.Print(models.Select(m => { var selected = settings.File is null ? AnimationLibrary.WithBrightness(AnimationLibrary.Default.Get(settings.Name!, m), settings.Brightness) : program; var player = new AnimationPlayer(Animation.Parse(selected, m)); player.Advance(settings.At); return new FrameReply(m, settings.At, player.Frame.Select(c => c.ToString()).ToArray()); }).ToArray()); } else { @@ -177,7 +177,7 @@ public sealed class PatternImportCommand : Command public override int Execute(CommandContext context, PatternImportSettings settings, CancellationToken cancellationToken) { var path = AnimationLibrary.Default.Save(settings.Name, settings.Model, new(System.IO.File.ReadAllText(settings.File)), settings.Force); - if (settings.Json) Output.Print(new { saved = path }); else Console.WriteLine(path); + if (settings.Json) Output.Print(new SavedReply(path)); else Console.WriteLine(path); return 0; } } @@ -192,7 +192,7 @@ public override int Execute(CommandContext context, PatternExportSettings settin { var program = settings.Read(); Animation.Parse(program, settings.Model); if (settings.Destination is { } path) AnimationLibrary.WriteFile(path, program.Text + "\n", settings.Force); - if (settings.Json) Output.Print(new { program = program.Text, output = settings.Destination }); + if (settings.Json) Output.Print(new ExportReply(program.Text, settings.Destination)); else if (settings.Destination is null) Console.WriteLine(program.Text); else Console.WriteLine(Path.GetFullPath(settings.Destination)); return 0; @@ -219,7 +219,7 @@ public override int Execute(CommandContext context, ProfileSettings settings, Ca profile.States[settings.State.Value] = settings.Pattern; profile = profile with { Brightness = settings.Brightness ?? profile.Brightness }; var path = AnimationLibrary.Default.SaveProfile(settings.Name, profile, true); - if (settings.Json) Output.Print(new { path, profile }); else Console.WriteLine(path); + if (settings.Json) Output.Print(new ProfileReply(path, profile)); else Console.WriteLine(path); return 0; } } diff --git a/src/SidePulse.Cli/Commands.cs b/src/SidePulse.Cli/Commands.cs index bfb742b..c9b9f09 100644 --- a/src/SidePulse.Cli/Commands.cs +++ b/src/SidePulse.Cli/Commands.cs @@ -9,8 +9,8 @@ namespace SidePulse.Cli; public static class Output { - public static readonly JsonSerializerOptions Json = new() { WriteIndented = true, Converters = { new JsonStringEnumConverter() } }; - public static void Print(object value) => Console.WriteLine(JsonSerializer.Serialize(value, Json)); + public static readonly JsonSerializerOptions Json = new() { WriteIndented = true, Converters = { new JsonStringEnumConverter(), new JsonStringEnumConverter(), new JsonStringEnumConverter() } }; + public static void Print(T value) => Console.WriteLine(CliJson.Serialize(value, Json)); public static string Color(AgentState state) => state switch { AgentState.Working => "cyan", AgentState.Waiting => "orange1", AgentState.Done => "green", @@ -87,7 +87,7 @@ public static async Task Send(TargetSettings settings, LedProgram program, Cance } public static void Receipt(TargetSettings settings, LedProgram program) { - if (settings.Json) Output.Print(new { dryRun = settings.DryRun, bytes = program.ByteCount, lines = program.LineCount, program = program.Text }); + if (settings.Json) Output.Print(new DeliveryReply(settings.DryRun, program.ByteCount, program.LineCount, program.Text)); else if (settings.DryRun) AnsiConsole.Write(new Panel(new Text(program.Text)).Header("LED preview").Border(BoxBorder.Rounded)); else AnsiConsole.MarkupLine("[green]Sent.[/]"); } @@ -153,7 +153,7 @@ public sealed class DashboardCommand : Command { public override int Execute(CommandContext context, DevicesSettings settings, CancellationToken cancellationToken) { - if (settings.Json) { Output.Print(new { devices = DeviceTransport.Discover(), profiles = Enum.GetNames() }); return 0; } + if (settings.Json) { Output.Print(new DashboardReply(DeviceTransport.Discover(), Enum.GetNames())); return 0; } AnsiConsole.Write(new Rule("[cyan]SidePulse[/][white].NET[/]").LeftJustified()); AnsiConsole.MarkupLine("[grey]Small signals. Clear status.[/]\n"); new DevicesCommand().Execute(context, settings, cancellationToken); diff --git a/src/SidePulse.Cli/Hooks.cs b/src/SidePulse.Cli/Hooks.cs index ba0e9b7..c6fdff4 100644 --- a/src/SidePulse.Cli/Hooks.cs +++ b/src/SidePulse.Cli/Hooks.cs @@ -82,7 +82,7 @@ public override async Task ExecuteAsync(CommandContext context, HookSetting if (length > LocalPipe.MaximumMessageBytes) return 0; var item = AgentEvents.Parse(settings.Source, settings.Event, new string(buffer, 0, length)); if (item is null) return 0; - var bytes = JsonSerializer.SerializeToUtf8Bytes(item); + var bytes = CoreJson.Bytes(item); if (bytes.Length > LocalPipe.MaximumMessageBytes) return 0; using var pipe = new NamedPipeClientStream(".", LocalPipe.Name, PipeDirection.Out, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly); @@ -184,7 +184,7 @@ public override async Task ExecuteAsync(CommandContext context, HostSetting queued = AgentState.Unknown; outputs.Writer.TryWrite(patterns[AgentState.Unknown]); } - var response = JsonSerializer.SerializeToUtf8Bytes(new HostSnapshot(true, Environment.ProcessId, sessions.State, sessions.Snapshot)); + var response = IpcJson.Snapshot(new HostSnapshot(true, Environment.ProcessId, sessions.State, sessions.Snapshot)); await pipe.WriteAsync(response.Concat(new byte[] { 10 }).ToArray(), deadline.Token); await pipe.FlushAsync(deadline.Token); // Windows disconnect discards unread reply bytes. Wait for a bounded receipt @@ -194,10 +194,10 @@ public override async Task ExecuteAsync(CommandContext context, HostSetting } continue; } - var item = JsonSerializer.Deserialize(message.ToArray()); + var item = CoreJson.Read(message.ToArray()); if (item is null || !Enum.IsDefined(item.State) || !sessions.Apply(item)) continue; var state = sessions.State; - if (settings.Json) Output.Print(new { state, sessions = sessions.Snapshot }); + if (settings.Json) Output.Print(new HostActivityReply(state, sessions.Snapshot)); else if (settings.Plain || Console.IsOutputRedirected) Console.WriteLine($"{DateTimeOffset.Now:HH:mm:ss} {state} ({sessions.Snapshot.Count} sessions)"); else { diff --git a/src/SidePulse.Cli/HostManagement.cs b/src/SidePulse.Cli/HostManagement.cs index e40e26a..004a25e 100644 --- a/src/SidePulse.Cli/HostManagement.cs +++ b/src/SidePulse.Cli/HostManagement.cs @@ -20,13 +20,13 @@ public static async Task Request(string command, CancellationToken try { await pipe.ConnectAsync(waitForConnection ? Timeout.Infinite : 0, deadline.Token); } catch (TimeoutException) when (!waitForConnection) { return new(false, null, AgentState.Unknown, []); } catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) { return new(false, null, AgentState.Unknown, []); } - await pipe.WriteAsync(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new { Command = command, ProtocolVersion = 1 }) + "\n"), deadline.Token); + await pipe.WriteAsync(Encoding.UTF8.GetBytes(IpcJson.Request(new HostRequest(command)) + "\n"), deadline.Token); await pipe.FlushAsync(deadline.Token); using var reader = new StreamReader(pipe, Encoding.UTF8); var response = await reader.ReadLineAsync(deadline.Token) ?? throw new IOException("The host closed without a response."); await pipe.WriteAsync(new byte[] { 10 }, deadline.Token); await pipe.FlushAsync(deadline.Token); - var snapshot = JsonSerializer.Deserialize(response, Output.Json) ?? throw new IOException("Invalid host response."); + var snapshot = JsonSerializer.Deserialize(response, CliJson.Info(Output.Json)) ?? throw new IOException("Invalid host response."); if (snapshot.ProtocolVersion != 1) throw new IOException("Host protocol mismatch. Stop the old host and use matching CLI/host versions."); return snapshot; } @@ -60,7 +60,7 @@ public override async Task ExecuteAsync(CommandContext context, HostActionS if (attempt == 24) throw new IOException("The host acknowledged stop but has not exited. No process was forcibly killed."); } } - if (settings.Json) Output.Print(new { stopped = state.Running }); + if (settings.Json) Output.Print(new StopReply(state.Running)); else AnsiConsole.WriteLine(state.Running ? "Host stopped." : "Host was not running."); return 0; } diff --git a/src/SidePulse.Cli/Installation.cs b/src/SidePulse.Cli/Installation.cs index 9c7ec94..c1492e8 100644 --- a/src/SidePulse.Cli/Installation.cs +++ b/src/SidePulse.Cli/Installation.cs @@ -31,17 +31,17 @@ public static string PreferredExecutable return path; } } - public static object Status() + public static InstallStatusReply Status() { var record = UserInstallation.ReadRecord(); var current = Environment.ProcessPath ?? ""; var resolved = UserPath.ResolveCommand(Environment.GetEnvironmentVariable("PATH") ?? ""); var installed = record is null ? null : Path.Combine(record.Directory, ApplicationIdentity.CurrentExecutable); - return new { mode = record is null ? "portable" : "installed", executable = current, - directory = record?.Directory, installedExecutable = installed, installedExecutableExists = installed is not null && File.Exists(installed), - bundled = ProjectInfo.IsBundled(), pathRegistered = record?.PathEntries.Count > 0, - resolvedCommand = resolved, pathEffective = installed is not null && resolved is not null && (resolved.Equals(installed, OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) || UserPath.IsOurLink(resolved, installed)), - record = UserInstallation.RecordPath, profileBackups = record?.PathEntries.Where(entry => entry.Kind == "profile" && entry.Backup is not null).Select(entry => entry.Backup).ToArray() ?? [] }; + return new InstallStatusReply(record is null ? "portable" : "installed", current, + record?.Directory, installed, installed is not null && File.Exists(installed), + ProjectInfo.IsBundled(), record?.PathEntries.Count > 0, resolved, + installed is not null && resolved is not null && (resolved.Equals(installed, OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) || UserPath.IsOurLink(resolved, installed)), + UserInstallation.RecordPath, record?.PathEntries.Where(entry => entry.Kind == "profile" && entry.Backup is not null).Select(entry => entry.Backup).ToArray() ?? []); } public static InstallationManifest SourceManifest() { @@ -68,14 +68,14 @@ public static void RequireNoManagedHooks() if (Directory.Exists(directory) && Directory.EnumerateFiles(directory, "*.json").Any()) throw new IOException("Remove managed agent integrations with agents uninstall (including any --config overrides) before uninstalling the application. Provider settings and unrelated hooks are not removed automatically."); } - public static void Print(bool json, object value, string text) { if (json) Output.Print(value); else Console.WriteLine(text); } + public static void Print(bool json, T value, string text) { if (json) Output.Print(value); else Console.WriteLine(text); } } public sealed class InstallCommand : AsyncCommand { public override async Task ExecuteAsync(CommandContext context, InstallSettings settings, CancellationToken token) { - if (settings.Status) { var status = Installation.Status(); Installation.Print(settings.Json, status, JsonSerializer.Serialize(status, Output.Json)); return 0; } + if (settings.Status) { var status = Installation.Status(); Installation.Print(settings.Json, status, CliJson.Serialize(status, Output.Json)); return 0; } var manifest = Installation.SourceManifest(); var directory = Path.GetFullPath(settings.Directory ?? UserInstallation.DefaultDirectory); var plan = UserInstallation.Plan(Path.GetDirectoryName(Environment.ProcessPath!)!, directory, manifest); @@ -90,8 +90,7 @@ public override async Task ExecuteAsync(CommandContext context, InstallSett if (entries.Count > 0) { UserPath.ValidateRemoval(entries); UserPath.CheckConflict(directory); } else pathPlan = UserPath.Plan(directory, settings.Shell); } - var preview = new { state = settings.DryRun ? "planned" : "installed", plan, path = pathPlan, existingPathEntries = entries, - restartTerminal = settings.AddToPath, preservesUserSettings = true }; + var preview = new InstallPreviewReply(settings.DryRun ? "planned" : "installed", plan, pathPlan, entries, settings.AddToPath, true); if (settings.DryRun) { Installation.Print(settings.Json, preview, $"Install {plan.Version} into {directory}\nExecutable: {plan.Executable}\n" + (pathPlan?.Profile is { } profile ? $"PATH profile: {profile}\n{pathPlan.Block}" : settings.AddToPath ? "Register user PATH/launcher. Reopen terminals afterward." : "No PATH or shell-profile changes.")); @@ -109,7 +108,7 @@ public override async Task ExecuteAsync(CommandContext context, InstallSett catch { UserPath.Remove(entries); throw; } } else if (settings.AddToPath && entries.Count > 0) UserPath.Repair(entries); - Installation.Print(settings.Json, new { state = plan.AlreadyInstalled ? "already-installed" : "installed", executable = plan.Executable, directory, pathRegistered = entries.Count > 0, restartTerminal = settings.AddToPath }, + Installation.Print(settings.Json, new InstallReply(plan.AlreadyInstalled ? "already-installed" : "installed", plan.Executable, directory, entries.Count > 0, settings.AddToPath), $"Installed: {plan.Executable}\n" + (settings.AddToPath ? "User PATH/launcher configured. Reopen terminals; use the absolute executable immediately." : "PATH was not changed.") + "\nPhone links and settings are preserved. Install integrations from this permanent executable path."); return 0; } @@ -126,12 +125,12 @@ public sealed class UninstallCommand : AsyncCommand public override async Task ExecuteAsync(CommandContext context, UninstallSettings settings, CancellationToken token) { var record = UserInstallation.ReadRecord(); - if (record is null) { Installation.Print(settings.Json, new { state = "not-installed" }, "No managed installation is registered."); return 0; } + if (record is null) { Installation.Print(settings.Json, new StateReply("not-installed"), "No managed installation is registered."); return 0; } UserInstallation.ValidateRemoval(record); Installation.RequireNoManagedHooks(); if (settings.DryRun) { - Installation.Print(settings.Json, new { state = "planned", directory = record.Directory, removePathEntries = record.PathEntries, preservesUserSettings = true }, + Installation.Print(settings.Json, new UninstallPreviewReply("planned", record.Directory, record.PathEntries, true), $"Remove owned application files from {record.Directory} and its managed PATH/launcher entries. Settings, phone links, user-added files and profile backups remain."); return 0; } @@ -140,7 +139,7 @@ public override async Task ExecuteAsync(CommandContext context, UninstallSe if (!string.Equals(currentDirectory, record.Directory, OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) { UserInstallation.Remove(record); - Installation.Print(settings.Json, new { state = "removed" }, "Application and owned PATH entries removed. Settings and phone links retained."); return 0; + Installation.Print(settings.Json, new StateReply("removed"), "Application and owned PATH entries removed. Settings and phone links retained."); return 0; } var job = Path.Combine(Path.GetDirectoryName(UserInstallation.RecordPath)!, "uninstall-" + Guid.NewGuid().ToString("N")); Directory.CreateDirectory(job); @@ -156,13 +155,13 @@ public override async Task ExecuteAsync(CommandContext context, UninstallSe using var parent = Process.GetCurrentProcess(); var plan = new UninstallPlan(UserInstallation.RecordPath, InstallationManifest.Hash(UserInstallation.RecordPath), record, parent.Id, parent.StartTime.ToUniversalTime().Ticks); var planPath = Path.Combine(job, "uninstall.json"); - UserInstallation.AtomicWrite(planPath, JsonSerializer.SerializeToUtf8Bytes(plan, InstallationManifest.Json)); + UserInstallation.AtomicWrite(planPath, CliJson.Bytes(plan, InstallationManifest.Json)); var start = new ProcessStartInfo(Path.Combine(job, ApplicationIdentity.CurrentExecutable)) { UseShellExecute = OperatingSystem.IsWindows(), CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden, RedirectStandardInput = !OperatingSystem.IsWindows(), RedirectStandardOutput = !OperatingSystem.IsWindows(), RedirectStandardError = !OperatingSystem.IsWindows(), WorkingDirectory = job }; foreach (var argument in new[] { "internal-uninstall", "--plan", planPath }) start.ArgumentList.Add(argument); using var helper = Process.Start(start) ?? throw new IOException("Could not start uninstall helper. The installation was preserved."); if (!OperatingSystem.IsWindows()) helper.StandardInput.Close(); - Installation.Print(settings.Json, new { state = "scheduled", workspace = job }, "Uninstall scheduled after this process exits. Settings and phone links are retained; the helper workspace remains for recovery."); + Installation.Print(settings.Json, new ScheduledUninstallReply("scheduled", job), "Uninstall scheduled after this process exits. Settings and phone links are retained; the helper workspace remains for recovery."); return 0; } } @@ -175,7 +174,7 @@ public sealed class InternalUninstallCommand : AsyncCommand ExecuteAsync(CommandContext context, InternalUninstallSettings settings, CancellationToken token) { if (!OperatingSystem.IsWindows()) HostLogs.Detach(); - var plan = JsonSerializer.Deserialize(await File.ReadAllTextAsync(settings.Plan, token), InstallationManifest.Json) ?? throw new IOException("Invalid uninstall plan."); + var plan = JsonSerializer.Deserialize(await File.ReadAllTextAsync(settings.Plan, token), CliJson.Info(InstallationManifest.Json)) ?? throw new IOException("Invalid uninstall plan."); var job = Path.GetDirectoryName(Environment.ProcessPath!)!; if (Path.GetFullPath(settings.Plan) != Path.Combine(job, "uninstall.json") || Path.GetDirectoryName(job) != Path.GetDirectoryName(UserInstallation.RecordPath) || !Path.GetFileName(job).StartsWith("uninstall-", StringComparison.Ordinal) || plan.RecordPath != UserInstallation.RecordPath || job == plan.Record.Directory) throw new IOException("Uninstall helpers must run from their private prepared workspace."); @@ -190,12 +189,12 @@ public override async Task ExecuteAsync(CommandContext context, InternalUni try { UserInstallation.Remove(UserInstallation.ReadRecord() ?? throw new IOException("Installation record is missing.")); - UserInstallation.AtomicWrite(Path.Combine(job, "result.json"), JsonSerializer.SerializeToUtf8Bytes(new { state = "removed" })); + UserInstallation.AtomicWrite(Path.Combine(job, "result.json"), CliJson.Bytes(new StateReply("removed"))); return 0; } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { - UserInstallation.AtomicWrite(Path.Combine(job, "result.json"), JsonSerializer.SerializeToUtf8Bytes(new { state = "failed", error = ex.Message, recoveryPackage = job })); + UserInstallation.AtomicWrite(Path.Combine(job, "result.json"), CliJson.Bytes(new FailedUninstallReply("failed", ex.Message, job))); return 1; } } diff --git a/src/SidePulse.Cli/JsonContracts.cs b/src/SidePulse.Cli/JsonContracts.cs new file mode 100644 index 0000000..9fea715 --- /dev/null +++ b/src/SidePulse.Cli/JsonContracts.cs @@ -0,0 +1,100 @@ +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Text.Json.Serialization; +using System.Text.Json.Serialization.Metadata; +using SidePulse.Core; + +namespace SidePulse.Cli; + +public sealed record ErrorReply(string error); +public sealed record StateReply(string state); +public sealed record ScheduledUninstallReply(string state, string workspace); +public sealed record FailedUninstallReply(string state, string error, string recoveryPackage); +public sealed record SettingsReply(string path, bool dryRun, Preferences preferences); +public sealed record StopReply(bool stopped); +public sealed record HostRequest(string Command, int ProtocolVersion = 1); +public sealed record HostActivityReply(AgentState state, IReadOnlyList sessions); +public sealed record DeliveryReply(bool dryRun, int bytes, int lines, string program); +public sealed record DashboardReply(IReadOnlyList devices, string[] profiles); +public sealed record ValidationReply(bool valid, DeviceModel model, int bytes, int lines, int instructions); +public sealed record FrameReply(DeviceModel model, int at, string[] colors); +public sealed record SavedReply(string saved); +public sealed record ExportReply(string program, string? output); +public sealed record ProfileReply(string path, AnimationProfile profile); +public sealed record AgentInstallReply(InstallationStatus status, JsonObject? managedHooks); +public sealed record LinkReply(string url, bool opened); +public sealed record AboutReply(string name, string version, string license, bool unofficial, string website, string github, string upstream); +public sealed record CreditsReply(string project, string upstream, IReadOnlyList dependencies); +public sealed record LicenseNotice(string name, string? text); +public sealed record LicensesReply(string project, IReadOnlyList dependencies, LicenseNotice[] notices, LicenseNotice[] runtimeNotices); +public sealed record InstallStatusReply(string mode, string executable, string? directory, string? installedExecutable, bool installedExecutableExists, bool bundled, bool pathRegistered, string? resolvedCommand, bool pathEffective, string record, string?[] profileBackups); +public sealed record InstallPreviewReply(string state, InstallPlan plan, UserPathPlan? path, IReadOnlyList existingPathEntries, bool restartTerminal, bool preservesUserSettings); +public sealed record InstallReply(string state, string executable, string directory, bool pathRegistered, bool restartTerminal); +public sealed record UninstallPreviewReply(string state, string directory, IReadOnlyList removePathEntries, bool preservesUserSettings); +public sealed record UpdatePreviewReply(string state, UpdateCheck check); +public sealed record UpdateScheduledReply(string state, string version, string receipt, string backup); +public sealed record UpdateStatusReply(string state, string? version, string target, string? backup, string? workspace, string? error, string receipt); + +public static class CliJson +{ + public static JsonTypeInfo Info(JsonSerializerOptions? options = null) + { + var context = options is null ? CliJsonContext.Default : new CliJsonContext(new JsonSerializerOptions(options)); + return (JsonTypeInfo)(context.GetTypeInfo(typeof(T)) ?? throw new NotSupportedException("Unregistered CLI JSON contract: " + typeof(T).Name)); + } + public static string Serialize(T value, JsonSerializerOptions? options = null) => JsonSerializer.Serialize(value, Info(options)); + public static byte[] Bytes(T value, JsonSerializerOptions? options = null) => JsonSerializer.SerializeToUtf8Bytes(value, Info(options)); +} + +[JsonSourceGenerationOptions(GenerationMode = JsonSourceGenerationMode.Metadata, UseStringEnumConverter = true)] +[JsonSerializable(typeof(ErrorReply))] +[JsonSerializable(typeof(StateReply))] +[JsonSerializable(typeof(ScheduledUninstallReply))] +[JsonSerializable(typeof(FailedUninstallReply))] +[JsonSerializable(typeof(SettingsReply))] +[JsonSerializable(typeof(StopReply))] +[JsonSerializable(typeof(HostSnapshot))] +[JsonSerializable(typeof(HostActivityReply))] +[JsonSerializable(typeof(DeliveryReply))] +[JsonSerializable(typeof(DashboardReply))] +[JsonSerializable(typeof(ValidationReply))] +[JsonSerializable(typeof(FrameReply[]))] +[JsonSerializable(typeof(SavedReply))] +[JsonSerializable(typeof(ExportReply))] +[JsonSerializable(typeof(ProfileReply))] +[JsonSerializable(typeof(AgentInstallReply))] +[JsonSerializable(typeof(InstallationStatus))] +[JsonSerializable(typeof(LinkReply))] +[JsonSerializable(typeof(AboutReply))] +[JsonSerializable(typeof(CreditsReply))] +[JsonSerializable(typeof(LicensesReply))] +[JsonSerializable(typeof(InstallStatusReply))] +[JsonSerializable(typeof(InstallPreviewReply))] +[JsonSerializable(typeof(InstallReply))] +[JsonSerializable(typeof(UninstallPreviewReply))] +[JsonSerializable(typeof(UninstallPlan))] +[JsonSerializable(typeof(UpdateCheck))] +[JsonSerializable(typeof(UpdatePreviewReply))] +[JsonSerializable(typeof(UpdateScheduledReply))] +[JsonSerializable(typeof(UpdateStatusReply))] +[JsonSerializable(typeof(IReadOnlyList))] +[JsonSerializable(typeof(IReadOnlyList))] +[JsonSerializable(typeof(IReadOnlyList))] +[JsonSerializable(typeof(IReadOnlyList))] +[JsonSerializable(typeof(IReadOnlyList))] +[JsonSerializable(typeof(List))] +[JsonSerializable(typeof(AnimationProfile))] +[JsonSerializable(typeof(DependencyCredit[]))] +internal partial class CliJsonContext : JsonSerializerContext; + +public static class IpcJson +{ + public static string Request(HostRequest value) => JsonSerializer.Serialize(value, IpcJsonContext.Default.HostRequest); + public static byte[] Snapshot(HostSnapshot value) => JsonSerializer.SerializeToUtf8Bytes(value, IpcJsonContext.Default.HostSnapshot); +} + +// IPC deliberately retains numeric enums; CLI output deliberately uses names. +[JsonSourceGenerationOptions(GenerationMode = JsonSourceGenerationMode.Metadata)] +[JsonSerializable(typeof(HostRequest))] +[JsonSerializable(typeof(HostSnapshot))] +internal partial class IpcJsonContext : JsonSerializerContext; diff --git a/src/SidePulse.Cli/Settings.cs b/src/SidePulse.Cli/Settings.cs index 8f7ee23..e30104e 100644 --- a/src/SidePulse.Cli/Settings.cs +++ b/src/SidePulse.Cli/Settings.cs @@ -42,7 +42,7 @@ public override int Execute(CommandContext context, PreferenceSettings settings, if (value.Profile is not null) _ = AnimationLibrary.ResolveProfile(value.Profile, value.Model, value.Device); } if (settings.Action != "show" && !settings.DryRun) store.Save(value); - if (settings.Json) Output.Print(new { path = PreferenceStore.DefaultPath, dryRun = settings.DryRun, preferences = value }); + if (settings.Json) Output.Print(new SettingsReply(PreferenceStore.DefaultPath, settings.DryRun, value)); else Console.WriteLine($"{value.OutputDescription}\nBrightness: {value.Brightness}% · Profile: {value.Profile ?? "built-in"} · Model: {value.Model?.ToString() ?? "auto"}\nExport shell: {value.Shell ?? (OperatingSystem.IsWindows() ? "powershell" : "bash")}\nSettings: {PreferenceStore.DefaultPath}" + (settings.DryRun ? "\nPreview only; settings unchanged." : "")); return 0; } diff --git a/src/SidePulse.Cli/SidePulse.Cli.csproj b/src/SidePulse.Cli/SidePulse.Cli.csproj index b1b6bcf..bacbc4b 100644 --- a/src/SidePulse.Cli/SidePulse.Cli.csproj +++ b/src/SidePulse.Cli/SidePulse.Cli.csproj @@ -6,6 +6,7 @@ true true embedded + false Unofficial SidePulse companion MIT diff --git a/src/SidePulse.Cli/TerminalMode.cs b/src/SidePulse.Cli/TerminalMode.cs index d619941..ac3821e 100644 --- a/src/SidePulse.Cli/TerminalMode.cs +++ b/src/SidePulse.Cli/TerminalMode.cs @@ -39,7 +39,7 @@ public static string[] Configure(string[] args) } public static int Error(Exception exception) { - if (Json) Console.Error.WriteLine(System.Text.Json.JsonSerializer.Serialize(new { error = exception.Message })); + if (Json) Console.Error.WriteLine(CliJson.Serialize(new ErrorReply(exception.Message))); else Console.Error.WriteLine("Error: " + exception.Message); return 1; } diff --git a/src/SidePulse.Cli/Updates.cs b/src/SidePulse.Cli/Updates.cs index 710f78c..2d02921 100644 --- a/src/SidePulse.Cli/Updates.cs +++ b/src/SidePulse.Cli/Updates.cs @@ -22,7 +22,7 @@ public static string Target return root.TrimEnd(Path.DirectorySeparatorChar); } } - public static void Print(UpdateSettings settings, object data, string text) { if (settings.Json) Output.Print(data); else Console.WriteLine(text); } + public static void Print(UpdateSettings settings, T data, string text) { if (settings.Json) Output.Print(data); else Console.WriteLine(text); } public static async Task<(AvailableRelease? Release, UpdateCheck Check)> Check(UpdateSettings settings, CancellationToken cancellationToken) { using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(30) }; @@ -69,7 +69,7 @@ public override async Task ExecuteAsync(CommandContext context, UpdateSetti if (release is null || new ReleaseVersion(release.Version).CompareTo(new(ProjectInfo.Version)) <= 0) { Updater.Print(settings, check, release is null ? "No published release in the selected channel." : "Already up to date."); return 0; } if (!check.Available) throw new IOException("The release is missing a package or SHA256SUMS; update refused."); - if (settings.DryRun) { Updater.Print(settings, new { state = "planned", check }, $"Would download, verify and install {check.Asset} ({check.Latest}) into {Updater.Target}."); return 0; } + if (settings.DryRun) { Updater.Print(settings, new UpdatePreviewReply("planned", check), $"Would download, verify and install {check.Asset} ({check.Latest}) into {Updater.Target}."); return 0; } var installed = InstallationManifest.Read(Updater.Target); if (installed.Version != ProjectInfo.Version || installed.Runtime != check.Runtime || Path.GetFileName(Environment.ProcessPath) != (ApplicationIdentity.CurrentExecutable)) throw new IOException("Self-update requires an unmodified self-contained release installation."); using var gate = UpdateTransaction.Lock(Updater.Target); @@ -98,7 +98,7 @@ public override async Task ExecuteAsync(CommandContext context, UpdateSetti UpdateTransaction.Receipt(plan, "scheduled"); using var process = Process.Start(start) ?? throw new IOException("Could not launch the update helper."); if (!OperatingSystem.IsWindows()) process.StandardInput.Close(); - Updater.Print(settings, new { state = "scheduled", version = plan.Version, receipt = plan.Receipt, backup = plan.Backup }, "Verified update scheduled. It will apply after this command exits. Run 'spn update status' to confirm before restarting the host."); + Updater.Print(settings, new UpdateScheduledReply("scheduled", plan.Version, plan.Receipt, plan.Backup), "Verified update scheduled. It will apply after this command exits. Run 'spn update status' to confirm before restarting the host."); return 0; } catch @@ -114,7 +114,7 @@ public sealed class UpdateStatusCommand : Command public override int Execute(CommandContext context, UpdateSettings settings, CancellationToken cancellationToken) { var status = UpdateTransaction.Status(Updater.Target); - Updater.Print(settings, new { state = status?.State ?? "none", version = status?.Version, target = Updater.Target, backup = status?.Backup, workspace = status?.Job, error = status?.Error, receipt = UpdateTransaction.ReceiptPath(Updater.Target) }, status is null ? "No recorded update for this installation." : $"{status.State}: {status.Version}\nBackup: {status.Backup}\nWorkspace: {status.Job}" + (status.Error is null ? "" : "\n" + status.Error)); + Updater.Print(settings, new UpdateStatusReply(status?.State ?? "none", status?.Version, Updater.Target, status?.Backup, status?.Job, status?.Error, UpdateTransaction.ReceiptPath(Updater.Target)), status is null ? "No recorded update for this installation." : $"{status.State}: {status.Version}\nBackup: {status.Backup}\nWorkspace: {status.Job}" + (status.Error is null ? "" : "\n" + status.Error)); return status?.State is "failed" or "recovery-required" ? 1 : 0; } } @@ -130,7 +130,7 @@ public override async Task ExecuteAsync(CommandContext context, ApplyUpdate try { if (!OperatingSystem.IsWindows()) HostLogs.Detach(); - plan = JsonSerializer.Deserialize(await File.ReadAllTextAsync(settings.Plan, cancellationToken), InstallationManifest.Json) ?? throw new IOException("Missing update plan."); + plan = CoreJson.Read(await File.ReadAllTextAsync(settings.Plan, cancellationToken), InstallationManifest.Json) ?? throw new IOException("Missing update plan."); UpdateTransaction.Validate(plan); var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; if (!Path.GetFullPath(settings.Plan).Equals(Path.Combine(plan.Job, "plan.json"), comparison) || !Updater.Target.Equals(Path.Combine(plan.Job, "helper"), comparison)) throw new IOException("Update helpers must run from their prepared workspace."); diff --git a/src/SidePulse.Core/AnimationLibrary.cs b/src/SidePulse.Core/AnimationLibrary.cs index 69ebbba..ac2c8ec 100644 --- a/src/SidePulse.Core/AnimationLibrary.cs +++ b/src/SidePulse.Core/AnimationLibrary.cs @@ -64,13 +64,13 @@ public string SaveProfile(string name, AnimationProfile profile, bool overwrite foreach (var pattern in profile.States.Values) Name(pattern); Directory.CreateDirectory(DirectoryPath); var path = Path.Combine(DirectoryPath, name + ".profile.json"); - WriteFile(path, JsonSerializer.Serialize(profile, new JsonSerializerOptions { WriteIndented = true }) + "\n", overwrite); + WriteFile(path, CoreJson.Serialize(profile, CoreJson.Pretty) + "\n", overwrite); return path; } public AnimationProfile LoadProfile(string name) { var path = Path.Combine(DirectoryPath, Name(name) + ".profile.json"); - var profile = JsonSerializer.Deserialize(File.ReadAllText(path)) ?? throw new ArgumentException("Invalid animation profile."); + var profile = CoreJson.Read(File.ReadAllText(path)) ?? throw new ArgumentException("Invalid animation profile."); if (profile.States is null || profile.Brightness is < 0 or > 100 || profile.States.Any(s => !Enum.IsDefined(s.Key))) throw new ArgumentException("Invalid animation profile."); foreach (var pattern in profile.States.Values) Name(pattern); return profile; diff --git a/src/SidePulse.Core/CoreJson.cs b/src/SidePulse.Core/CoreJson.cs new file mode 100644 index 0000000..4a759a7 --- /dev/null +++ b/src/SidePulse.Core/CoreJson.cs @@ -0,0 +1,40 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Text.Json.Serialization.Metadata; + +namespace SidePulse.Core; + +internal sealed record LinkStoreDocument(int Version, string? DefaultAlias, List Links); +internal sealed record HookOwnershipManifest(string Target, string BeforeHash, string InstalledHash, string? Backup); +internal sealed record BridgeAps([property: JsonPropertyName("content-available")] int ContentAvailable); +internal sealed record BridgeEvent(string sidepulse_event_id); +internal sealed record BridgePayload(BridgeAps aps, string leds, BridgeEvent data); + +/// Generated metadata for the application's explicitly registered wire/file contracts. No reflection fallback. +public static class CoreJson +{ + public static readonly JsonSerializerOptions Pretty = new() { WriteIndented = true }; + public static JsonTypeInfo Info(JsonSerializerOptions? options = null) + { + var context = options is null ? CoreJsonContext.Default : new CoreJsonContext(new JsonSerializerOptions(options)); + return (JsonTypeInfo)(context.GetTypeInfo(typeof(T)) ?? throw new NotSupportedException("Unregistered Core JSON contract: " + typeof(T).Name)); + } + public static string Serialize(T value, JsonSerializerOptions? options = null) => JsonSerializer.Serialize(value, Info(options)); + public static byte[] Bytes(T value, JsonSerializerOptions? options = null) => JsonSerializer.SerializeToUtf8Bytes(value, Info(options)); + public static T? Read(string json, JsonSerializerOptions? options = null) => JsonSerializer.Deserialize(json, Info(options)); + public static T? Read(ReadOnlySpan json, JsonSerializerOptions? options = null) => JsonSerializer.Deserialize(json, Info(options)); +} + +[JsonSourceGenerationOptions(GenerationMode = JsonSourceGenerationMode.Metadata)] +[JsonSerializable(typeof(string))] +[JsonSerializable(typeof(Preferences))] +[JsonSerializable(typeof(AnimationProfile))] +[JsonSerializable(typeof(InstallationManifest))] +[JsonSerializable(typeof(UserInstallRecord))] +[JsonSerializable(typeof(UpdateReceipt))] +[JsonSerializable(typeof(UpdatePlan))] +[JsonSerializable(typeof(LinkStoreDocument))] +[JsonSerializable(typeof(HookOwnershipManifest))] +[JsonSerializable(typeof(BridgePayload))] +[JsonSerializable(typeof(SessionEvent))] +internal partial class CoreJsonContext : JsonSerializerContext; diff --git a/src/SidePulse.Core/HookConfiguration.cs b/src/SidePulse.Core/HookConfiguration.cs index 9b9c76a..c402d8f 100644 --- a/src/SidePulse.Core/HookConfiguration.cs +++ b/src/SidePulse.Core/HookConfiguration.cs @@ -42,7 +42,7 @@ public static JsonObject Generate(AgentProvider provider, string exe, bool windo } else if (provider == AgentProvider.Kiro) { - kiro.Add(new JsonObject { ["name"] = "SidePulse.NET " + name, ["trigger"] = name, ["timeout"] = 2, + kiro.Add((JsonNode)new JsonObject { ["name"] = "SidePulse.NET " + name, ["trigger"] = name, ["timeout"] = 2, ["action"] = new JsonObject { ["type"] = "command", ["command"] = portable } }); } else diff --git a/src/SidePulse.Core/HookInstallation.cs b/src/SidePulse.Core/HookInstallation.cs index a4becb7..c92ed95 100644 --- a/src/SidePulse.Core/HookInstallation.cs +++ b/src/SidePulse.Core/HookInstallation.cs @@ -7,16 +7,15 @@ namespace SidePulse.Core; public sealed record InstallationStatus(string State, string Target, string? Backup); public sealed class HookInstallation(string manifestDirectory) { - private sealed record Manifest(string Target, string BeforeHash, string InstalledHash, string? Backup); private static string Hash(byte[]? bytes) => bytes is null ? "absent" : Convert.ToHexString(SHA256.HashData(bytes)); private string ManifestPath(string target) => Path.Combine(manifestDirectory, Hash(System.Text.Encoding.UTF8.GetBytes(target)) + ".json"); private static byte[]? Read(string target) => File.Exists(target) ? File.ReadAllBytes(target) : null; private static string Target(string path) => Path.GetFullPath(path); - private Manifest? Load(string target) + private HookOwnershipManifest? Load(string target) { var path = ManifestPath(target); if (!File.Exists(path)) return null; - var record = JsonSerializer.Deserialize(File.ReadAllBytes(path)) ?? throw new IOException("Installation manifest is unreadable."); + var record = CoreJson.Read(File.ReadAllBytes(path)) ?? throw new IOException("Installation manifest is unreadable."); if (record.Target != target || record.Backup is not null && !record.Backup.StartsWith(target + ".sidepulse-net-", StringComparison.Ordinal)) throw new IOException("Installation manifest paths do not match this target."); return record; @@ -65,9 +64,9 @@ public InstallationStatus Install(string path, AgentProvider provider, JsonObjec if (Hash(Read(target)) != Hash(before) || Load(target) is not null) throw new IOException("Configuration changed while preparing installation. Retry after reviewing it."); var backup = before is null ? null : target + ".sidepulse-net-" + DateTimeOffset.UtcNow.ToString("yyyyMMddHHmmss") + "-" + Guid.NewGuid().ToString("N") + ".bak"; if (backup is not null) { using var file = PrivateFile(backup, FileMode.CreateNew); file.Write(before!); file.Flush(true); } - var record = new Manifest(target, Hash(before), Hash(after), backup); + var record = new HookOwnershipManifest(target, Hash(before), Hash(after), backup); // A manifest written before the target makes an interrupted installation detectable and recoverable. - AtomicWrite(ManifestPath(target), JsonSerializer.SerializeToUtf8Bytes(record)); + AtomicWrite(ManifestPath(target), CoreJson.Bytes(record)); try { if (Hash(Read(target)) != Hash(before)) throw new IOException("Configuration changed during installation. No provider configuration was replaced."); diff --git a/src/SidePulse.Core/LinkStore.cs b/src/SidePulse.Core/LinkStore.cs index def0127..6abafb0 100644 --- a/src/SidePulse.Core/LinkStore.cs +++ b/src/SidePulse.Core/LinkStore.cs @@ -43,7 +43,6 @@ public static string DefaultPath } } private const int MaximumBytes = 262144; - private sealed record Document(int Version, string? DefaultAlias, List Links); private readonly string fullPath = Path.GetFullPath(path); private FileStream Lock() @@ -59,7 +58,7 @@ private static FileStream PrivateFile(string path, FileMode mode, FileOptions op if (!OperatingSystem.IsWindows()) settings.UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite; return new FileStream(path, settings); } - private Document Read() + private LinkStoreDocument Read() { if (!File.Exists(fullPath)) return new(1, null, []); byte[]? plaintext = null; @@ -68,7 +67,7 @@ private Document Read() if (new FileInfo(fullPath).Length > MaximumBytes) throw new InvalidDataException(); plaintext = protector.Unprotect(File.ReadAllBytes(fullPath)); if (plaintext.Length > MaximumBytes) throw new InvalidDataException(); - var document = JsonSerializer.Deserialize(plaintext); + var document = CoreJson.Read(plaintext); if (document is null || document.Version != 1 || document.Links is null || document.Links.Count > 128) throw new InvalidDataException(); var aliases = new HashSet(StringComparer.OrdinalIgnoreCase); @@ -87,9 +86,9 @@ private Document Read() } finally { if (plaintext is not null) CryptographicOperations.ZeroMemory(plaintext); } } - private void Save(Document document) + private void Save(LinkStoreDocument document) { - var plaintext = JsonSerializer.SerializeToUtf8Bytes(document); + var plaintext = CoreJson.Bytes(document); byte[] encrypted; try { @@ -151,7 +150,7 @@ public void Remove(string alias) => Change(alias, (document, link) => document.Links.Remove(link); return document with { DefaultAlias = document.DefaultAlias == link.Alias ? null : document.DefaultAlias }; }); - private void Change(string alias, Func update) + private void Change(string alias, Func update) { alias = PhoneTokens.Alias(alias); using var gate = Lock(); diff --git a/src/SidePulse.Core/OpenCodePlugin.cs b/src/SidePulse.Core/OpenCodePlugin.cs index 389d48f..360aeb8 100644 --- a/src/SidePulse.Core/OpenCodePlugin.cs +++ b/src/SidePulse.Core/OpenCodePlugin.cs @@ -8,7 +8,7 @@ public static string Generate(string executable) => """ // Managed by SidePulse.NET. Uninstall before editing or moving the executable. import { spawn } from "node:child_process"; const executable = - """ + JsonSerializer.Serialize(executable) + ";\n" + """ + """ + CoreJson.Serialize(executable) + ";\n" + """ export const SidePulsePlugin = async () => { const pending = new Map(); const failed = new Set(); diff --git a/src/SidePulse.Core/PhoneBridge.cs b/src/SidePulse.Core/PhoneBridge.cs index ee8291c..8ab2440 100644 --- a/src/SidePulse.Core/PhoneBridge.cs +++ b/src/SidePulse.Core/PhoneBridge.cs @@ -7,16 +7,11 @@ public sealed class PhoneBridge(HttpClient client) public async Task SendAsync(string token, LedProgram program, CancellationToken cancellationToken = default) { token = PhoneTokens.Normalize(token); - var payload = new Dictionary - { - ["aps"] = new Dictionary { ["content-available"] = 1 }, - ["leds"] = program.Text, - ["data"] = new Dictionary { ["sidepulse_event_id"] = Guid.NewGuid().ToString() } - }; + var payload = new BridgePayload(new(1), program.Text, new(Guid.NewGuid().ToString())); try { using var response = await client.PostAsJsonAsync( - "https://bridge.sidepulse.io/api/leds/" + Uri.EscapeDataString("apns_" + token), payload, cancellationToken); + "https://bridge.sidepulse.io/api/leds/" + Uri.EscapeDataString("apns_" + token), payload, CoreJson.Info(), cancellationToken); if (!response.IsSuccessStatusCode) throw new IOException($"Phone bridge returned HTTP {(int)response.StatusCode}."); } diff --git a/src/SidePulse.Core/Preferences.cs b/src/SidePulse.Core/Preferences.cs index 540b3df..cc937eb 100644 --- a/src/SidePulse.Core/Preferences.cs +++ b/src/SidePulse.Core/Preferences.cs @@ -41,7 +41,7 @@ public Preferences Read() try { if (new FileInfo(path).Length > 16384) throw new ArgumentException("Settings file is too large."); - var preferences = JsonSerializer.Deserialize(File.ReadAllBytes(path)) ?? throw new ArgumentException("Empty settings."); + var preferences = CoreJson.Read(File.ReadAllBytes(path)) ?? throw new ArgumentException("Empty settings."); preferences.Validate(); return preferences; } @@ -56,6 +56,6 @@ public void Save(Preferences preferences) var directory = Path.GetDirectoryName(Path.GetFullPath(path))!; if (OperatingSystem.IsWindows()) Directory.CreateDirectory(directory); else Directory.CreateDirectory(directory, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); - UserInstallation.AtomicWrite(path, JsonSerializer.SerializeToUtf8Bytes(preferences, new JsonSerializerOptions { WriteIndented = true })); + UserInstallation.AtomicWrite(path, CoreJson.Bytes(preferences, CoreJson.Pretty)); } } diff --git a/src/SidePulse.Core/UpdatePackage.cs b/src/SidePulse.Core/UpdatePackage.cs index 50966f4..1c04e0a 100644 --- a/src/SidePulse.Core/UpdatePackage.cs +++ b/src/SidePulse.Core/UpdatePackage.cs @@ -22,7 +22,7 @@ public static InstallationManifest Read(string directory) { var path = System.IO.Path.Combine(directory, Filename); if (!File.Exists(path) || new FileInfo(path).Length > 4 * 1024 * 1024) throw new IOException("This installation has no supported update manifest. Install a current self-contained preview/release manually first."); - var manifest = JsonSerializer.Deserialize(File.ReadAllText(path), Json) ?? throw new IOException("Invalid installation manifest."); + var manifest = CoreJson.Read(File.ReadAllText(path), Json) ?? throw new IOException("Invalid installation manifest."); _ = new ReleaseVersion(manifest.Version); if (manifest.Format is not (1 or 2) || manifest.Runtime is not ("win-x64" or "win-arm64" or "osx-x64" or "osx-arm64" or "linux-x64" or "linux-arm64") || manifest.Files is null || manifest.Files.Count is < 1 or > 10000) throw new IOException("Invalid installation manifest."); var names = new HashSet(StringComparer.OrdinalIgnoreCase); diff --git a/src/SidePulse.Core/UpdateTransaction.cs b/src/SidePulse.Core/UpdateTransaction.cs index aea6e64..2e7b368 100644 --- a/src/SidePulse.Core/UpdateTransaction.cs +++ b/src/SidePulse.Core/UpdateTransaction.cs @@ -19,12 +19,12 @@ public static string TargetKey(string target) { var path = ReceiptPath(target); if (!File.Exists(path)) return null; - return JsonSerializer.Deserialize(File.ReadAllText(path), InstallationManifest.Json) ?? throw new IOException("Invalid update receipt."); + return CoreJson.Read(File.ReadAllText(path), InstallationManifest.Json) ?? throw new IOException("Invalid update receipt."); } public static void Receipt(UpdatePlan plan, string state, string? error = null) { Directory.CreateDirectory(Path.GetDirectoryName(plan.Receipt)!); - AnimationLibrary.WriteFile(plan.Receipt, JsonSerializer.Serialize(new UpdateReceipt(state, plan.Version, plan.Target, plan.Backup, plan.Job, error), InstallationManifest.Json) + "\n", true); + AnimationLibrary.WriteFile(plan.Receipt, CoreJson.Serialize(new UpdateReceipt(state, plan.Version, plan.Target, plan.Backup, plan.Job, error), InstallationManifest.Json) + "\n", true); } public static FileStream Lock(string target) { @@ -68,7 +68,7 @@ public static UpdatePlan Prepare(string target, string stage, string job, string } File.Copy(Path.Combine(target, InstallationManifest.Filename), Path.Combine(helper, InstallationManifest.Filename)); current.Verify(helper, true); - AnimationLibrary.WriteFile(Path.Combine(job, "plan.json"), JsonSerializer.Serialize(plan, InstallationManifest.Json) + "\n", false); + AnimationLibrary.WriteFile(Path.Combine(job, "plan.json"), CoreJson.Serialize(plan, InstallationManifest.Json) + "\n", false); Receipt(plan, "prepared"); return plan; } diff --git a/src/SidePulse.Core/UserInstallation.cs b/src/SidePulse.Core/UserInstallation.cs index 76d7245..95c0381 100644 --- a/src/SidePulse.Core/UserInstallation.cs +++ b/src/SidePulse.Core/UserInstallation.cs @@ -18,7 +18,7 @@ public static class UserInstallation path ??= RecordPath; if (!File.Exists(path)) return null; if (new FileInfo(path).Length > 65536) throw new IOException("Installation record is too large. Existing files were preserved."); - var record = JsonSerializer.Deserialize(File.ReadAllText(path), InstallationManifest.Json); + var record = CoreJson.Read(File.ReadAllText(path), InstallationManifest.Json); if (record is null || record.Format != 1 || !Path.IsPathFullyQualified(record.Directory) || record.PathEntries is null || record.PathEntries.Count > 3) throw new IOException("Installation record is invalid. Existing files were preserved."); _ = Target(record.Directory); @@ -30,7 +30,7 @@ public static void SaveRecord(UserInstallRecord record, string? path = null) path ??= RecordPath; if (OperatingSystem.IsWindows()) Directory.CreateDirectory(Path.GetDirectoryName(path)!); else Directory.CreateDirectory(Path.GetDirectoryName(path)!, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); - AtomicWrite(path, System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(record, InstallationManifest.Json)); + AtomicWrite(path, CoreJson.Bytes(record, InstallationManifest.Json)); } public static void AtomicWrite(string path, byte[] bytes) { @@ -98,7 +98,7 @@ public static async Task Install(InstallPlan plan, InstallationManifest manifest File.Copy(InstallationManifest.Resolve(plan.Source, file.Path), target); if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(target, (UnixFileMode)file.Mode); } - AtomicWrite(Path.Combine(stage, InstallationManifest.Filename), JsonSerializer.SerializeToUtf8Bytes(manifest, InstallationManifest.Json)); + AtomicWrite(Path.Combine(stage, InstallationManifest.Filename), CoreJson.Bytes(manifest, InstallationManifest.Json)); _ = InstallationManifest.Read(stage); manifest.Verify(stage, true); if (Directory.Exists(plan.Destination)) diff --git a/tests/SidePulse.Tests/CoreTests.cs b/tests/SidePulse.Tests/CoreTests.cs index d9468fe..767fd2c 100644 --- a/tests/SidePulse.Tests/CoreTests.cs +++ b/tests/SidePulse.Tests/CoreTests.cs @@ -107,6 +107,8 @@ public async Task BridgeSendsSilentApnsEnvelopeAndRedactsNetworkFailures() Assert.Equal(1, body.RootElement.GetProperty("aps").GetProperty("content-available").GetInt32()); Assert.Equal("off", body.RootElement.GetProperty("leds").GetString()); Assert.False(body.RootElement.GetProperty("aps").TryGetProperty("alert", out _)); + Assert.Equal(3, body.RootElement.EnumerateObject().Count()); + Assert.True(Guid.TryParse(body.RootElement.GetProperty("data").GetProperty("sidepulse_event_id").GetString(), out _)); handler.Throw = true; var error = await Assert.ThrowsAsync(() => new PhoneBridge(client).SendAsync(new string('a', 64), new LedProgram("off"))); Assert.DoesNotContain(new string('a', 64), error.Message); diff --git a/tests/SidePulse.Tests/JsonContractTests.cs b/tests/SidePulse.Tests/JsonContractTests.cs new file mode 100644 index 0000000..5561173 --- /dev/null +++ b/tests/SidePulse.Tests/JsonContractTests.cs @@ -0,0 +1,133 @@ +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; +using SidePulse.Cli; +using SidePulse.Core; +using Xunit; + +namespace SidePulse.Tests; + +public sealed class JsonContractTests +{ + private static JsonSerializerOptions LegacyOutput => new() { WriteIndented = true, Converters = { new JsonStringEnumConverter() } }; + private static void SameCli(T actual, object legacy) => Assert.Equal(JsonSerializer.Serialize(legacy, LegacyOutput), CliJson.Serialize(actual, Output.Json)); + + [Fact] + public void NamedCliContractsPreserveAnonymousOutputBytes() + { + var preferences = new Preferences(Phone: "iphone", Brightness: 42, Model: DeviceModel.Dot); + SameCli(new SettingsReply("/config/settings.json", true, preferences), new { path = "/config/settings.json", dryRun = true, preferences }); + SameCli(new DeliveryReply(true, 4, 1, "off"), new { dryRun = true, bytes = 4, lines = 1, program = "off" }); + SameCli(new ValidationReply(true, DeviceModel.Pro, 4, 1, 1), new { valid = true, model = DeviceModel.Pro, bytes = 4, lines = 1, instructions = 1 }); + SameCli(new UpdateStatusReply("none", null, "/app", null, null, null, "/receipt"), new { state = "none", version = (string?)null, target = "/app", backup = (string?)null, workspace = (string?)null, error = (string?)null, receipt = "/receipt" }); + var status = new InstallationStatus("preview", "/hooks.json", null); + SameCli(new AgentInstallReply(status, new() { ["hooks"] = new System.Text.Json.Nodes.JsonArray() }), new { status, managedHooks = new System.Text.Json.Nodes.JsonObject { ["hooks"] = new System.Text.Json.Nodes.JsonArray() } }); + SameCli(new FrameReply[] { new(DeviceModel.Dot, 100, ["#00FF66"]) }, new[] { new { model = DeviceModel.Dot, at = 100, colors = new[] { "#00FF66" } } }); + } + + [Fact] + public void FileContractsPreserveFormattingNumericEnumsAndNulls() + { + var options = new JsonSerializerOptions { WriteIndented = true, PropertyNameCaseInsensitive = true }; + var preferences = new Preferences(Model: DeviceModel.Pro, Brightness: 17); + Assert.Equal(JsonSerializer.Serialize(preferences, options), CoreJson.Serialize(preferences, CoreJson.Pretty)); + var plan = new UpdatePlan("/app", "/stage", "/backup", "/job", "/receipt", "ABC", "0.1.0-beta.2", "linux-x64", 123, 456); + Assert.Equal(JsonSerializer.Serialize(plan, options), CoreJson.Serialize(plan, InstallationManifest.Json)); + var profile = new AnimationProfile(new() { [AgentState.Working] = "solid-green" }, 42); + Assert.Equal(JsonSerializer.Serialize(profile, options), CoreJson.Serialize(profile, CoreJson.Pretty)); + Assert.Equal(42, CoreJson.Read(CoreJson.Serialize(profile))!.Brightness); + Assert.Equal("solid-green", CoreJson.Read("{\"States\":{\"Working\":\"solid-green\"},\"Brightness\":42}")!.States[AgentState.Working]); + } + + [Fact] + public void LegacyMissingFieldsAndCaseInsensitivePackageRecordsRemainReadable() + { + var value = CoreJson.Read("{\"Phone\":\"iphone\"}")!; + Assert.Equal(1, value.Version); + Assert.Equal(100, value.Brightness); + Assert.Null(value.Model); + // Preferences historically use case-sensitive names; package records do not. + Assert.Equal(100, CoreJson.Read("{\"brightness\":42}")!.Brightness); + var manifest = CoreJson.Read("{\"format\":2,\"version\":\"0.1.0-beta.2\",\"runtime\":\"linux-x64\",\"files\":[{\"path\":\"spn\",\"sha256\":\"ABC\",\"mode\":493}]}", InstallationManifest.Json)!; + Assert.Equal(2, manifest.Format); + Assert.Equal("spn", Assert.Single(manifest.Files).Path); + var record = CoreJson.Read("{\"format\":1,\"directory\":\"/app\",\"pathEntries\":[]}", InstallationManifest.Json)!; + Assert.Equal("/app", record.Directory); + } + + [Fact] + public void NumericIpcAndNamedCliEnumsStayDistinct() + { + var message = new SessionEvent("test", AgentState.Waiting, 123, AgentProvider.Codex); + Assert.Equal("{\"SessionId\":\"test\",\"State\":3,\"Timestamp\":123,\"Provider\":1,\"ProtocolVersion\":1}", CoreJson.Serialize(message)); + var legacy = CoreJson.Read("{\"SessionId\":\"legacy\",\"State\":2,\"Timestamp\":42}")!; + Assert.Equal(AgentProvider.Copilot, legacy.Provider); + Assert.Equal(1, legacy.ProtocolVersion); + var snapshot = new HostSnapshot(true, 123, AgentState.Waiting, [new("test", AgentState.Waiting, 123, AgentProvider.Codex)]); + using var wire = JsonDocument.Parse(IpcJson.Snapshot(snapshot)); + Assert.Equal(3, wire.RootElement.GetProperty("State").GetInt32()); + Assert.Equal(1, wire.RootElement.GetProperty("Sessions")[0].GetProperty("Provider").GetInt32()); + using var output = JsonDocument.Parse(CliJson.Serialize(snapshot, Output.Json)); + Assert.Equal("Waiting", output.RootElement.GetProperty("State").GetString()); + Assert.Equal("Codex", output.RootElement.GetProperty("Sessions")[0].GetProperty("Provider").GetString()); + Assert.Equal("{\"Command\":\"status\",\"ProtocolVersion\":1}", IpcJson.Request(new("status"))); + Assert.Equal(snapshot.State, JsonSerializer.Deserialize(IpcJson.Snapshot(snapshot), CliJson.Info(Output.Json))!.State); + } + + [Fact] + public void ExistingProtectedLinkDocumentKeepsItsWireShape() + { + var directory = Path.Combine(Path.GetTempPath(), "spn JSON fixture " + Guid.NewGuid()); + Directory.CreateDirectory(directory); + var path = Path.Combine(directory, "links.fixture"); + var fixture = "{\"Version\":1,\"DefaultAlias\":\"iphone\",\"Links\":[{\"Alias\":\"iphone\",\"Name\":\"Fixture\",\"Token\":\"" + new string('a', 64) + "\",\"LinkedAt\":\"2026-01-01T00:00:00+00:00\"}]}"; + try + { + File.WriteAllText(path, fixture); + var store = new LinkStore(path, new IdentityFixtureProtector()); + Assert.Equal("Fixture", store.Get("default").Name); + store.SetDefault("iphone"); + Assert.Equal(fixture, File.ReadAllText(path)); + } + finally { Directory.Delete(directory, true); } + } + + [Fact] + public void UnregisteredContractsFailWithoutReflectionFallback() + { + Assert.Throws(() => CoreJson.Serialize(new UnknownContract("fixture"))); + Assert.Throws(() => CliJson.Serialize(new UnknownContract("fixture"))); + Assert.Equal("{\"error\":\"fixture\"}", CliJson.Serialize(new ErrorReply("fixture"))); + Assert.Equal("{\"state\":\"removed\"}", CliJson.Serialize(new StateReply("removed"))); + } + + [Fact] + public void SecretBearingLinksAreNotPublicCliOutputContracts() + { + var token = new string('a', 64); + var link = new PhoneLink("fixture", "Fixture", token, DateTimeOffset.UnixEpoch); + var error = Assert.Throws(() => CliJson.Serialize(link)); + Assert.DoesNotContain(token, error.Message); + } + + [Fact] + public void ContextsDoNotTakeOwnershipOfSharedCallerOptions() + { + var options = new JsonSerializerOptions { WriteIndented = true, PropertyNameCaseInsensitive = true }; + _ = CoreJson.Serialize(new Preferences(), options); + var plan = new UninstallPlan("/record", "HASH", new(1, "/app", []), 123, 456); + var encoded = CliJson.Bytes(plan, options); + Assert.Equal("/record", JsonSerializer.Deserialize(encoded, CliJson.Info(options))!.RecordPath); + Assert.False(options.IsReadOnly); + Assert.Null(options.TypeInfoResolver); + options.WriteIndented = false; + Assert.DoesNotContain('\n', CoreJson.Serialize(new Preferences(), options)); + } + + private sealed record UnknownContract(string Value); + private sealed class IdentityFixtureProtector : ISecretProtector + { + public byte[] Protect(byte[] plaintext) => plaintext.ToArray(); + public byte[] Unprotect(byte[] ciphertext) => ciphertext.ToArray(); + } +} From 7be47a58566b943432aa593a24892a47029d5305 Mon Sep 17 00:00:00 2001 From: Gordon Breuer Date: Mon, 26 Oct 2026 13:06:26 +0000 Subject: [PATCH 2/2] Compare native JSON probe side effects with existing lock behavior --- .../0004-generated-json-contracts.md | 7 ++--- scripts/json_compatibility.py | 27 ++++++++++++++++--- 2 files changed, 28 insertions(+), 6 deletions(-) diff --git a/docs/decisions/0004-generated-json-contracts.md b/docs/decisions/0004-generated-json-contracts.md index f356714..69fea10 100644 --- a/docs/decisions/0004-generated-json-contracts.md +++ b/docs/decisions/0004-generated-json-contracts.md @@ -46,9 +46,10 @@ The normal CLI and lifecycle smoke run with reflection JSON disabled. python3 scripts/json_compatibility.py /path/to/baseline/spn /path/to/candidate/spn ``` -This compares 22 read-only public JSON/error responses. Only executable-directory -and derived receipt-key differences are normalized. The isolated application config -must remain absent. Run against a stopped host; a live externally changing session +This compares 22 public JSON/error responses. Only executable-directory +and derived receipt-key differences are normalized. Preview commands must leave +configuration unchanged; other probes must add no filesystem effects beyond the +baseline. The existing native-vault phone list can create an empty store lock. Run against a stopped host; a live externally changing session is not deterministic compatibility evidence. JSON compatibility CI publishes both revisions with the same SDK on native Windows/Linux/macOS and runs this comparison. diff --git a/scripts/json_compatibility.py b/scripts/json_compatibility.py index 2e9f2f4..bdcb910 100644 --- a/scripts/json_compatibility.py +++ b/scripts/json_compatibility.py @@ -1,4 +1,4 @@ -"""Compare public read-only JSON responses with a published baseline executable.""" +"""Compare public JSON responses and their filesystem effects with a published baseline executable.""" import argparse import hashlib import json @@ -39,6 +39,16 @@ def normalize(value, executable): return value +def snapshot(root): + if not root.exists(): + return {} + entries = {'.': ('directory', root.stat().st_mode & 0o777)} + for path in sorted(root.rglob('*')): + name = str(path.relative_to(root)) + entries[name] = ('directory', path.stat().st_mode & 0o777) if path.is_dir() else ('file', hashlib.sha256(path.read_bytes()).hexdigest(), path.stat().st_mode & 0o777) + return entries + + def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('baseline', type=Path) @@ -46,9 +56,12 @@ def main(): args = parser.parse_args() baseline, candidate = args.baseline.resolve(), args.candidate.resolve() with tempfile.TemporaryDirectory(prefix='spn JSON compatibility ') as temporary: - environment = dict(os.environ, SIDEPULSE_NET_HOME=str(Path(temporary) / 'config')) + config = Path(temporary) / 'config' + environment = dict(os.environ, SIDEPULSE_NET_HOME=str(config)) for command in COMMANDS: results = [] + before = snapshot(config) + baseline_files = None for executable in (baseline, candidate): response = subprocess.run([str(executable), *command], env=environment, capture_output=True, text=True, timeout=15) @@ -58,8 +71,16 @@ def main(): except ValueError as error: raise AssertionError(f'Invalid JSON for {command}, exit {response.returncode}') from error results.append((response.returncode, value)) + files = snapshot(config) + if executable == baseline: + baseline_files = files + else: + assert files == baseline_files, f'Candidate changed configuration beyond baseline: {command}' + if '--dry-run' in command: + assert files == before, f'Preview created or changed configuration: {command}' assert results[0] == results[1], (command, results) - assert not (Path(temporary) / 'config').exists(), 'Read-only compatibility probes created configuration' + # Existing link-list behavior can create an empty store lock on native-vault + # platforms. Compare those effects rather than asserting a false baseline. print(f'{len(COMMANDS)} public JSON command/error responses match baseline.')