diff --git a/docs/wiki/Agent-Integrations.md b/docs/wiki/Agent-Integrations.md index 30317aa..1d28df5 100644 --- a/docs/wiki/Agent-Integrations.md +++ b/docs/wiki/Agent-Integrations.md @@ -147,3 +147,68 @@ Checked 2026-10-23: - [OpenCode question events](https://github.com/anomalyco/opencode/blob/v1.2.27/packages/opencode/src/question/service.ts) - [Kiro standalone schema](https://kiro.dev/docs/hooks/) - [Kiro triggers and session identity](https://kiro.dev/docs/hooks/types/) + +## Repair paths after moving or installing SPN + +```shell +spn agents repair --json +spn agents repair claude --exe "/permanent/path/spn" --dry-run --json +spn host stop +spn agents repair claude --exe "/permanent/path/spn" --apply +spn host start --phone default +``` + +`agents repair` previews all five current providers. Select a provider to repair +only that integration; `--config` requires a selected provider. The default target +executable is the verified installed location when one is registered, otherwise +the running SPN. Use `--exe` to select another existing `spn`/`spn.exe`. The old +executable may already be gone. Use the actual previous host options when restarting; +the example phone option above is not a remembered host configuration. + +Preview shows provider/file, old/new paths and `ready`, `already-current`, +`not-installed`, `modified`, `unavailable`, `unrecognized` or `repair-pending` state. +It creates no settings, locks, backups or ownership records. Repair changes only +files owned by this SPN installation and matching their recorded hash. It regenerates +the complete prior configuration from the exact original backup and recognized path; +if that does not match, it refuses. This supports existing beta ownership records +without requiring the old executable to exist. Unknown older generator formats may +need manual review or explicit uninstall/reinstall instead. + +Apply requires `--apply`; `--dry-run` is also accepted as an explicit preview. +Unknown/repeated options fail before mutation. A running SPN host blocks apply or +recovery: stop it first and restart explicitly with the same output/profile options. +No provider trust/permission file or approval is changed. Providers may ask you to +review the changed hook command when next started. Unrelated provider settings are +preserved, and handlers are regenerated from the original baseline rather than +appended again. + +Before writing, SPN rechecks ownership under the target lock and makes a private, +byte-exact `*.sidepulse-net-repair-*.bak`. The original pre-install backup remains +intact so uninstall can restore the original bytes even after multiple repairs. +Repair also preserves the provider file's access permissions. Edited files, +missing/modified backups, symlinks and unknown configurations are refused. A batch +with known conflicts refuses before changing any provider. A later I/O failure may +leave earlier providers repaired; their status and backups remain inspectable. +Preview again, then retry only the affected provider. + +## Interrupted repair + +```shell +spn agents repair claude --recover --dry-run --json +spn agents repair claude --recover --json +spn agents repair claude --dry-run --json +``` + +A journal records the old/new hashes before replacing provider configuration. An +interruption at either atomic-write boundary is reported as `repair-pending`. +`--recover` verifies the repair backup and current bytes, then reconciles ownership +metadata to whichever recognized version is present; it never rewrites the provider +file. It refuses if the file or repair backup was manually edited. Use a preview +before retrying repair. Uninstall refuses pending repairs until reconciled. Keep +both backups for manual recovery if ownership checks cannot be satisfied. + +JSON uses `dryRun`, `hostRunning`, and `providers`; each provider includes `Provider`, +`Target`, `State`, `OldExecutable`, `NewExecutable`, `Backup`, and `Reason`. Preview +returns inspection results even for conflicts; apply refuses conflicted batches. +Recovery returns exit 1 when any provider remains blocked. These commands do not +claim validation of a real external provider session; that acceptance remains #40. diff --git a/docs/wiki/Installation.md b/docs/wiki/Installation.md index 23b59c7..eda77ce 100644 --- a/docs/wiki/Installation.md +++ b/docs/wiki/Installation.md @@ -113,3 +113,7 @@ measured smaller executable incurred additional startup CPU cost and did not reduce the gzip download. See the repository's [startup report](https://github.com/Anheledir/SidePulse.NET/blob/main/docs/performance/2026-10-26-startup.md) for numbers, limits and reproduction; Native AOT/trimming remains a separate investigation. + +After adopting a portable executable into a permanent directory, use `spn agents repair --dry-run` +to inspect existing managed hooks, stop the host, then apply with `spn agents repair --apply`. +See [integration path repair and recovery](Agent-Integrations.md#repair-paths-after-moving-or-installing-spn). diff --git a/scripts/agent_smoke.py b/scripts/agent_smoke.py index e9a825d..25e5954 100644 --- a/scripts/agent_smoke.py +++ b/scripts/agent_smoke.py @@ -1,16 +1,72 @@ """Exercise native generated wrappers, owned hook setup and detached host control, without agent accounts.""" import json +import hashlib import os from pathlib import Path import shlex +import shutil import subprocess import sys import tempfile import time +def repair_checks(exe): + with tempfile.TemporaryDirectory(prefix="SidePulse repair ' ü ") as directory: + root = Path(directory).resolve() + env = dict(os.environ, SIDEPULSE_NET_HOME=str(root / 'state')) + old = root / 'Downloads' / Path(exe).name + new = root / 'Programs ü' / Path(exe).name + for path in (old, new): + path.parent.mkdir() + shutil.copy2(exe, path) + def run(*args, success=True): + result = subprocess.run([exe, *args], capture_output=True, text=True, env=env, timeout=15) + assert (result.returncode == 0) == success, (args, result.stdout, result.stderr) + return result + preview = json.loads(run('agents', 'repair', '--exe', str(new), '--json').stdout) + assert len(preview['providers']) == 5 and preview['dryRun'] + assert not (root / 'state').exists(), 'Default preview created configuration/lock/backup files' + for provider in ('copilot', 'codex', 'claude', 'kiro', 'opencode'): + config = root / (provider + ('.js' if provider == 'opencode' else '.json')) + original = b'{"permissions":{"allow":["Read"]},"trust":"keep","hooks":{}}\n' if provider in ('codex', 'claude') else None + if original: + config.write_bytes(original) + run('agents', 'install', provider, '--config', str(config), '--exe', str(old)) + installed = config.read_bytes() + before = {str(p.relative_to(root)): p.read_bytes() for p in root.rglob('*') if p.is_file()} + plan = json.loads(run('agents', 'repair', provider, '--config', str(config), '--exe', str(new), '--dry-run', '--json').stdout) + assert plan['providers'][0]['State'] == 'ready', plan + assert Path(plan['providers'][0]['OldExecutable']).samefile(old), (plan, str(old)) + after = {str(p.relative_to(root)): p.read_bytes() for p in root.rglob('*') if p.is_file()} + assert before == after, 'Repair preview changed files' + reply = json.loads(run('agents', 'repair', provider, '--config', str(config), '--exe', str(new), '--apply', '--json').stdout) + result = reply['providers'][0] + assert result['State'] == 'repaired' and Path(result['Backup']).read_bytes() == installed + current = config.read_bytes() + assert json.loads(run('agents', 'repair', provider, '--config', str(config), '--exe', str(new), '--apply', '--json').stdout)['providers'][0]['State'] == 'already-current' + run('agents', 'repair', provider, '--config', str(config), '--exe', str(new), '--apply', '--dryrun', '--json', success=False) + assert config.read_bytes() == current + # Simulate a process stopping after replacing provider bytes but before + # clearing its journal. Recovery must change only metadata, not settings. + ownership = next(p for p in (root / 'state' / 'integrations').glob('*.json') if Path(json.loads(p.read_text())['Target']).samefile(config)) + journal = json.loads(ownership.read_text()) + journal['PreviousInstalledHash'] = hashlib.sha256(installed).hexdigest().upper() + ownership.write_text(json.dumps(journal), encoding='utf-8') + pending = ownership.read_bytes() + assert json.loads(run('agents', 'repair', provider, '--config', str(config), '--exe', str(new), '--recover', '--dry-run', '--json').stdout)['providers'][0]['State'] == 'preview-recover' + assert ownership.read_bytes() == pending and config.read_bytes() == current + recovered = json.loads(run('agents', 'repair', provider, '--config', str(config), '--exe', str(new), '--recover', '--json').stdout)['providers'][0] + assert recovered['State'] == 'recovered' and recovered['Reason'] is None + assert config.read_bytes() == current + run('agents', 'uninstall', provider, '--config', str(config)) + assert (config.read_bytes() if config.exists() else None) == original + print('Five-provider repair previews, exact backups, repeat apply and original restoration passed.', flush=True) + + def main(): exe = str(Path(sys.argv[1]).resolve()) + repair_checks(exe) with tempfile.TemporaryDirectory(prefix="SidePulse agents ü ") as directory: root = Path(directory) env = os.environ.copy() @@ -53,6 +109,11 @@ def status(): print('Detached host ready.', flush=True) assert first['Running'] assert status()['Running'] + hook_path = configs['claude'][0] + before_repair = hook_path.read_bytes() + refused = subprocess.run([exe, 'agents', 'repair', 'claude', '--config', str(hook_path), '--exe', exe, '--apply', '--json'], env=env, capture_output=True, text=True, timeout=15) + assert refused.returncode != 0 and 'Stop the host' in refused.stderr + assert hook_path.read_bytes() == before_repair second = json.loads(run('host', 'start', '--exe', exe, '--device', directory, '--json')) assert second['ProcessId'] == first['ProcessId'] diff --git a/src/SidePulse.Cli/AgentRepair.cs b/src/SidePulse.Cli/AgentRepair.cs new file mode 100644 index 0000000..f5d845c --- /dev/null +++ b/src/SidePulse.Cli/AgentRepair.cs @@ -0,0 +1,77 @@ +using System.ComponentModel; +using SidePulse.Core; +using Spectre.Console; +using Spectre.Console.Cli; + +namespace SidePulse.Cli; + +public sealed class AgentRepairSettings : CommandSettings +{ + [CommandArgument(0, "[AGENT]")] public AgentProvider? Agent { get; init; } + [CommandOption("--exe ")] public string Executable { get; init; } = Installation.PreferredExecutable; + [CommandOption("--config ")] public string? Config { get; init; } + [CommandOption("--apply")] [Description("Apply only after reviewing the default preview; stop the host first.")] + public bool Apply { get; init; } + [CommandOption("--dry-run")] public bool DryRun { get; init; } + [CommandOption("--recover")] [Description("Reconcile an interrupted repair journal without rewriting provider settings.")] + public bool Recover { get; init; } + [CommandOption("--json")] public bool Json { get; init; } + public override ValidationResult Validate() => Agent is { } provider && !Enum.IsDefined(provider) ? ValidationResult.Error("Unknown provider.") + : Config is not null && Agent is null ? ValidationResult.Error("--config requires a selected provider.") + : Apply && (DryRun || Recover) ? ValidationResult.Error("Choose --apply, --dry-run or --recover.") : ValidationResult.Success(); +} +public sealed record AgentRepairReply(bool dryRun, bool hostRunning, IReadOnlyList providers); +public sealed class AgentRepairCommand : AsyncCommand +{ + public override async Task ExecuteAsync(CommandContext context, AgentRepairSettings settings, CancellationToken token) + { + var executable = HookConfiguration.Executable(settings.Executable); + var host = await HostControl.Request("status", token, waitForConnection: false); + if ((settings.Apply || settings.Recover && !settings.DryRun) && host.Running) + throw new IOException("Stop the host before repairing paths: spn host stop. Restart it afterwards with its previous target/profile options."); + var providers = settings.Agent is { } selected ? new[] { selected } : Enum.GetValues(); + var plans = new List<(AgentSettings Settings, HookRepairPreview Preview)>(); + foreach (var provider in providers) + { + var agent = new AgentSettings { Agent = provider, Config = settings.Config }; + HookRepairPreview preview; + try { preview = agent.Installation.PreviewRepair(agent.Target, provider, executable); } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or System.Text.Json.JsonException) + { preview = new(provider, agent.Target, "unavailable", null, executable, null, ex.Message); } + plans.Add((agent, preview)); + } + // Refuse a batch with an edited, unavailable or interrupted provider before repairing any. + if (settings.Apply && plans.Any(p => p.Preview.State is not "ready" and not "already-current" and not "not-installed")) + throw new IOException("Repair batch contains conflicts. Preview and resolve them, or select one provider; no provider was changed."); + var results = new List(); + foreach (var (agent, preview) in plans) + { + token.ThrowIfCancellationRequested(); + try + { + if (settings.Recover && preview.State == "repair-pending") + { + var status = agent.Installation.RecoverRepair(agent.Target, settings.DryRun); + results.Add(preview with { State = status.State, Backup = status.Backup, Reason = null }); + } + else results.Add(settings.Apply && preview.State == "ready" ? agent.Installation.Repair(agent.Target, agent.Agent, executable) : preview); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + if (results.Count > 0) throw new IOException($"Repair stopped at {agent.Agent}. Earlier completed providers remain repaired; their backups are retained. Preview again before retrying. {ex.Message}", ex); + throw; + } + } + if (settings.Json) Output.Print(new AgentRepairReply(!settings.Apply && (!settings.Recover || settings.DryRun), host.Running, results)); + else + { + foreach (var result in results) + Console.WriteLine($"{result.Provider}: {result.State}\n {result.Target}\n {result.OldExecutable ?? "unknown"} -> {result.NewExecutable}" + + (result.Backup is null ? "" : $"\n Backup: {result.Backup}") + (result.Reason is null ? "" : $"\n {result.Reason}")); + Console.WriteLine(settings.Apply ? "Restart the host with its previous options, then review provider hook trust prompts. No trust or permission settings were changed." + : settings.Recover && !settings.DryRun ? "Recovery inspection complete. Review per-provider states; provider configuration bytes were preserved." + : "Preview only. Stop the host and use --apply to change managed executable paths."); + } + return settings.Recover && results.Any(r => r.State is "modified" or "unavailable" or "unrecognized" or "repair-pending") ? 1 : 0; + } +} diff --git a/src/SidePulse.Cli/CliApplication.cs b/src/SidePulse.Cli/CliApplication.cs index 2399bc1..5fd463a 100644 --- a/src/SidePulse.Cli/CliApplication.cs +++ b/src/SidePulse.Cli/CliApplication.cs @@ -107,6 +107,7 @@ static string[] Normalize(string[] command) { agents.SetDescription("Set up Copilot, Codex, Claude Code, Kiro and OpenCode lifecycle integrations."); agents.AddCommand("list"); + agents.AddCommand("repair").WithDescription("Preview or repair owned hook paths without changing trust settings."); agents.AddCommand("install"); agents.AddCommand("status"); agents.AddCommand("uninstall"); diff --git a/src/SidePulse.Cli/JsonContracts.cs b/src/SidePulse.Cli/JsonContracts.cs index 2fcaf23..13063d9 100644 --- a/src/SidePulse.Cli/JsonContracts.cs +++ b/src/SidePulse.Cli/JsonContracts.cs @@ -66,6 +66,7 @@ public static JsonTypeInfo Info(JsonSerializerOptions? options = null) [JsonSerializable(typeof(ExportReply))] [JsonSerializable(typeof(ProfileReply))] [JsonSerializable(typeof(AgentInstallReply))] +[JsonSerializable(typeof(AgentRepairReply))] [JsonSerializable(typeof(InstallationStatus))] [JsonSerializable(typeof(LinkReply))] [JsonSerializable(typeof(AboutReply))] diff --git a/src/SidePulse.Cli/MaintenanceArguments.cs b/src/SidePulse.Cli/MaintenanceArguments.cs index 0b20acc..c1fcdac 100644 --- a/src/SidePulse.Cli/MaintenanceArguments.cs +++ b/src/SidePulse.Cli/MaintenanceArguments.cs @@ -5,6 +5,11 @@ public static class MaintenanceArguments { public static void Validate(string[] args) { + if (args.Length >= 2 && args[0] == "agents" && args[1] == "repair") + { + ValidateRepair(args); + return; + } if (args.Length == 0 || args[0] is not "firmware" and not "storage") return; if (args.Skip(1).Any(a => a is "--help" or "-h" or "-?")) return; if (args.Length < 2 || (args[0] == "firmware" ? args[1] is not "version" and not "upgrade" : args[1] is not "status" and not "on" and not "off")) @@ -24,4 +29,27 @@ public static void Validate(string[] args) else if (!flags.Contains(option[0]) || option.Length != 1) throw new ArgumentException("Unknown maintenance option: " + args[i]); } } + private static void ValidateRepair(string[] args) + { + var seen = new HashSet(StringComparer.Ordinal); + var provider = false; + for (var i = 2; i < args.Length; i++) + { + var option = args[i].Split('=', 2); + if (option[0] is "--help" or "-h" or "-?") return; + if (!args[i].StartsWith('-')) + { + if (provider) throw new ArgumentException("Select only one provider."); + provider = true; continue; + } + if (!seen.Add(option[0])) throw new ArgumentException("Repeated repair option: " + option[0]); + if (option[0] is "--exe" or "--config") + { + if (option.Length == 2 && option[1].Length > 0) continue; + if (option.Length == 2 || ++i >= args.Length || args[i].StartsWith('-')) throw new ArgumentException("Missing value for " + option[0]); + } + else if (option.Length != 1 || option[0] is not "--apply" and not "--dry-run" and not "--recover" and not "--json") + throw new ArgumentException("Unknown repair option: " + args[i]); + } + } } diff --git a/src/SidePulse.Core/CoreJson.cs b/src/SidePulse.Core/CoreJson.cs index 4a759a7..19caaee 100644 --- a/src/SidePulse.Core/CoreJson.cs +++ b/src/SidePulse.Core/CoreJson.cs @@ -5,7 +5,7 @@ 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 HookOwnershipManifest(string Target, string BeforeHash, string InstalledHash, string? Backup, string? PreviousInstalledHash = null, string? RepairBackup = null); 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); diff --git a/src/SidePulse.Core/HookExecutableCandidates.cs b/src/SidePulse.Core/HookExecutableCandidates.cs new file mode 100644 index 0000000..811205b --- /dev/null +++ b/src/SidePulse.Core/HookExecutableCandidates.cs @@ -0,0 +1,44 @@ +using System.Text; +using System.Text.Json.Nodes; +using System.Text.RegularExpressions; + +namespace SidePulse.Core; + +// Candidate extraction is not ownership proof: callers must regenerate the entire +// configuration from the exact original backup and compare the recorded hash. +internal static class HookExecutableCandidates +{ + public static IEnumerable Read(AgentProvider provider, byte[] bytes) + { + var candidates = new HashSet(StringComparer.Ordinal); + void Command(string text) + { + var end = text.LastIndexOf("' hook ", StringComparison.Ordinal); + if (end > 0) + { + if (text.StartsWith('\'')) candidates.Add(text[1..end].Replace("'\"'\"'", "'")); + const string prefix = "$ErrorActionPreference = 'SilentlyContinue'; try { $input | & '"; + if (text.StartsWith(prefix, StringComparison.Ordinal)) candidates.Add(text[prefix.Length..end].Replace("''", "'")); + } + const string encoded = "pwsh -NoLogo -NoProfile -NonInteractive -EncodedCommand "; + if (text.StartsWith(encoded, StringComparison.Ordinal)) + { + try { Command(Encoding.Unicode.GetString(Convert.FromBase64String(text[encoded.Length..]))); } + catch (FormatException) { } + } + } + void Visit(JsonNode? node) + { + if (node is JsonObject obj) foreach (var value in obj.Select(p => p.Value)) Visit(value); + else if (node is JsonArray array) foreach (var value in array) Visit(value); + else if (node is JsonValue value && value.TryGetValue(out var text)) Command(text); + } + if (provider == AgentProvider.OpenCode) + { + var match = Regex.Match(Encoding.UTF8.GetString(bytes), "(?m)^const executable =\\s*(\"(?:[^\"\\\\]|\\\\.)*\");", RegexOptions.CultureInvariant); + if (match.Success) candidates.Add(JsonNode.Parse(match.Groups[1].Value)!.GetValue()); + } + else Visit(JsonNode.Parse(bytes)); + return candidates; + } +} diff --git a/src/SidePulse.Core/HookInstallation.cs b/src/SidePulse.Core/HookInstallation.cs index c92ed95..045de0d 100644 --- a/src/SidePulse.Core/HookInstallation.cs +++ b/src/SidePulse.Core/HookInstallation.cs @@ -5,6 +5,7 @@ namespace SidePulse.Core; public sealed record InstallationStatus(string State, string Target, string? Backup); +public sealed record HookRepairPreview(AgentProvider Provider, string Target, string State, string? OldExecutable, string NewExecutable, string? Backup, string? Reason = null); public sealed class HookInstallation(string manifestDirectory) { private static string Hash(byte[]? bytes) => bytes is null ? "absent" : Convert.ToHexString(SHA256.HashData(bytes)); @@ -16,7 +17,10 @@ public sealed class HookInstallation(string manifestDirectory) var path = ManifestPath(target); if (!File.Exists(path)) return null; 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)) + bool ValidBackup(string? backup, string prefix) => backup is null || + Path.IsPathFullyQualified(backup) && Path.GetFullPath(backup) == backup && Path.GetDirectoryName(backup) == Path.GetDirectoryName(target) + && backup.StartsWith(target + prefix, StringComparison.Ordinal) && backup.EndsWith(".bak", StringComparison.Ordinal); + if (record.Target != target || !ValidBackup(record.Backup, ".sidepulse-net-") || !ValidBackup(record.RepairBackup, ".sidepulse-net-repair-")) throw new IOException("Installation manifest paths do not match this target."); return record; } @@ -26,6 +30,8 @@ public InstallationStatus Status(string path) var manifest = Load(target); if (manifest is null) return new("not-installed", target, null); var hash = Hash(Read(target)); + if (manifest.PreviousInstalledHash is not null) + return new(hash == manifest.InstalledHash || hash == manifest.PreviousInstalledHash ? "repair-pending" : "modified", target, manifest.RepairBackup); return new(hash == manifest.InstalledHash ? "installed" : hash == manifest.BeforeHash ? "pending-or-restored" : "modified", target, manifest.Backup); } public InstallationStatus Install(string path, AgentProvider provider, JsonObject generated, bool dryRun) @@ -83,6 +89,7 @@ public InstallationStatus Uninstall(string path, bool dryRun) if (dryRun) { var preview = Status(target); + if (preview.State == "repair-pending") throw new IOException("Recover the interrupted repair before uninstalling."); if (preview.State == "modified") throw new IOException("Configuration was edited after installation. Review the backup and merge manually; uninstall will not overwrite those changes."); return preview with { State = "preview-remove" }; } @@ -90,6 +97,7 @@ public InstallationStatus Uninstall(string path, bool dryRun) manifest = Load(target); if (manifest is null) return new("not-installed", target, null); var status = Status(target); + if (status.State == "repair-pending") throw new IOException("An interrupted repair needs agents repair --recover before uninstalling."); if (status.State == "modified") throw new IOException("Configuration was edited after installation. Review the backup and merge manually; uninstall will not overwrite those changes."); if (status.State == "installed") { @@ -104,6 +112,90 @@ public InstallationStatus Uninstall(string path, bool dryRun) File.Delete(ManifestPath(target)); return status with { State = "removed" }; } + public HookRepairPreview PreviewRepair(string path, AgentProvider provider, string executable) + => PrepareRepair(path, provider, HookConfiguration.Executable(executable)).Preview; + + private (HookRepairPreview Preview, HookOwnershipManifest? Manifest, byte[]? After) PrepareRepair(string path, AgentProvider provider, string executable) + { + var target = Target(path); + void RejectLink(string file) + { + if (new FileInfo(file).LinkTarget is not null) throw new IOException("Repair refuses symbolic links and reparse points."); + } + RejectLink(target); RejectLink(ManifestPath(target)); + var record = Load(target); + if (record is null) return (new(provider, target, "not-installed", null, executable, null), null, null); + if (record.Backup is not null) RejectLink(record.Backup); + if (record.RepairBackup is not null) RejectLink(record.RepairBackup); + var state = Status(target).State; + if (state != "installed") return (new(provider, target, state, null, executable, record.RepairBackup ?? record.Backup, + state == "repair-pending" ? "Recover the interrupted repair first." : "Manual edits or incomplete ownership prevent automatic repair."), record, null); + var original = record.BeforeHash == "absent" ? null : record.Backup is null ? null : Read(record.Backup); + if (Hash(original) != record.BeforeHash) throw new IOException("Original backup is missing or modified; no repair is allowed."); + JsonObject? baseline = original is null ? null : provider == AgentProvider.OpenCode ? new JsonObject() : JsonNode.Parse(original)!.AsObject(); + var bytes = Read(target)!; + var matches = new List<(string Executable, bool Windows)>(); + foreach (var candidate in HookExecutableCandidates.Read(provider, bytes)) + foreach (var windows in new[] { false, true }) + { + var previous = Serialize(provider, HookConfiguration.Merge(provider, baseline, HookConfiguration.Generate(provider, candidate, windows))); + if (Hash(previous) == record.InstalledHash) matches.Add((candidate, windows)); + } + if (matches.Select(m => m.Executable).Distinct(StringComparer.Ordinal).Count() != 1) + return (new(provider, target, "unrecognized", null, executable, record.Backup, "The owned file does not match a supported generated configuration."), record, null); + var recognized = matches[0]; + var after = Serialize(provider, HookConfiguration.Merge(provider, baseline, HookConfiguration.Generate(provider, executable, recognized.Windows))); + return (new(provider, target, Hash(after) == record.InstalledHash ? "already-current" : "ready", recognized.Executable, executable, record.Backup), record, after); + } + + public HookRepairPreview Repair(string path, AgentProvider provider, string executable) + { + executable = HookConfiguration.Executable(executable); + var prepared = PrepareRepair(path, provider, executable); + if (prepared.Preview.State == "already-current") return prepared.Preview; + if (prepared.Preview.State != "ready") throw new IOException("Repair refused: " + prepared.Preview.State + ". " + prepared.Preview.Reason); + var target = prepared.Preview.Target; + using var gate = PrivateFile(target + ".sidepulse-net.lock", FileMode.OpenOrCreate); + prepared = PrepareRepair(target, provider, executable); + if (prepared.Preview.State == "already-current") return prepared.Preview; + if (prepared.Preview.State != "ready") throw new IOException("Configuration changed while preparing repair; review it again."); + var record = prepared.Manifest!; + var before = Read(target)!; + var backup = target + ".sidepulse-net-repair-" + Guid.NewGuid().ToString("N") + ".bak"; + using (var file = PrivateFile(backup, FileMode.CreateNew)) { file.Write(before); file.Flush(true); } + var pending = record with { InstalledHash = Hash(prepared.After), PreviousInstalledHash = record.InstalledHash, RepairBackup = backup }; + if (Hash(Read(target)) != record.InstalledHash) throw new IOException("Configuration changed before repair; the exact backup was retained."); + AtomicWrite(ManifestPath(target), CoreJson.Bytes(pending)); + try + { + if (Hash(Read(target)) != record.InstalledHash) throw new IOException("Configuration changed during repair."); + AtomicWrite(target, prepared.After!, target); + AtomicWrite(ManifestPath(target), CoreJson.Bytes(pending with { PreviousInstalledHash = null })); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { throw new IOException("Repair interrupted. Backups are retained; inspect and use agents repair --recover before retrying.", ex); } + return prepared.Preview with { State = "repaired", Backup = backup }; + } + + public InstallationStatus RecoverRepair(string path, bool dryRun) + { + var target = Target(path); + InstallationStatus Recover() + { + var record = Load(target); + if (record?.PreviousInstalledHash is null) return Status(target); + if (record.RepairBackup is null || !File.Exists(record.RepairBackup) || new FileInfo(record.RepairBackup).LinkTarget is not null + || Hash(Read(record.RepairBackup)) != record.PreviousInstalledHash || new FileInfo(target).LinkTarget is not null) + throw new IOException("Repair backup is missing or modified. Recovery refused."); + var hash = Hash(Read(target)); + if (hash != record.InstalledHash && hash != record.PreviousInstalledHash) throw new IOException("Configuration changed during repair. Recovery will not overwrite it."); + if (!dryRun) AtomicWrite(ManifestPath(target), CoreJson.Bytes(record with { InstalledHash = hash, PreviousInstalledHash = null })); + return new(dryRun ? "preview-recover" : "recovered", target, record.RepairBackup); + } + if (dryRun) return Recover(); + using var gate = PrivateFile(target + ".sidepulse-net.lock", FileMode.OpenOrCreate); + return Recover(); + } private static FileStream PrivateFile(string path, FileMode mode) { var options = new FileStreamOptions { Mode = mode, Access = FileAccess.ReadWrite, Share = FileShare.None }; @@ -111,12 +203,17 @@ private static FileStream PrivateFile(string path, FileMode mode) return new FileStream(path, options); } private static byte[] Serialize(AgentProvider provider, JsonObject value) => System.Text.Encoding.UTF8.GetBytes(provider == AgentProvider.OpenCode ? value["plugin"]!.GetValue() : value.ToJsonString(new JsonSerializerOptions { WriteIndented = true }) + "\n"); - private static void AtomicWrite(string path, byte[] bytes) + private static void AtomicWrite(string path, byte[] bytes, string? accessSource = null) { var temporary = path + "." + Guid.NewGuid().ToString("N") + ".tmp"; try { using (var file = PrivateFile(temporary, FileMode.CreateNew)) { file.Write(bytes); file.Flush(true); } + if (accessSource is not null) + { + if (OperatingSystem.IsWindows()) FileSystemAclExtensions.SetAccessControl(new FileInfo(temporary), FileSystemAclExtensions.GetAccessControl(new FileInfo(accessSource), System.Security.AccessControl.AccessControlSections.Access)); + else File.SetUnixFileMode(temporary, File.GetUnixFileMode(accessSource)); + } File.Move(temporary, path, true); } finally { if (File.Exists(temporary)) File.Delete(temporary); } diff --git a/tests/SidePulse.Tests/HookRepairTests.cs b/tests/SidePulse.Tests/HookRepairTests.cs new file mode 100644 index 0000000..785dbff --- /dev/null +++ b/tests/SidePulse.Tests/HookRepairTests.cs @@ -0,0 +1,178 @@ +using System.Security.Cryptography; +using System.Text.Json.Nodes; +using SidePulse.Core; +using Xunit; + +namespace SidePulse.Tests; + +public sealed class HookRepairTests +{ + [Theory] + [InlineData(AgentProvider.Copilot, false)] [InlineData(AgentProvider.Copilot, true)] + [InlineData(AgentProvider.Codex, false)] [InlineData(AgentProvider.Codex, true)] + [InlineData(AgentProvider.Claude, false)] [InlineData(AgentProvider.Claude, true)] + [InlineData(AgentProvider.Kiro, false)] [InlineData(AgentProvider.Kiro, true)] + [InlineData(AgentProvider.OpenCode, false)] [InlineData(AgentProvider.OpenCode, true)] + public void RepairRecognizesAllProvidersAndRestoresTheExactOriginalOnUninstall(AgentProvider provider, bool windows) + { + using var fixture = new Fixture(provider, windows); + var before = File.ReadAllBytes(fixture.Target); + var manifest = Directory.GetFiles(fixture.Manifests, "*.json").Single(); + // Existing beta ownership records have only these four fields. + var legacy = JsonNode.Parse(File.ReadAllBytes(manifest))!.AsObject(); + legacy.Remove("PreviousInstalledHash"); legacy.Remove("RepairBackup"); File.WriteAllText(manifest, legacy.ToJsonString()); + var filesBefore = Directory.GetFiles(fixture.Root).Order().ToArray(); + File.Delete(fixture.OldExecutable); // Downloads was removed; recognition must not require the old binary. + var preview = fixture.Installation.PreviewRepair(fixture.Target, provider, fixture.NewExecutable); + Assert.Equal("ready", preview.State); + Assert.Equal(fixture.OldExecutable, preview.OldExecutable); + Assert.Equal(before, File.ReadAllBytes(fixture.Target)); + Assert.Equal(filesBefore.Where(p => p != fixture.OldExecutable), Directory.GetFiles(fixture.Root).Order()); + var repaired = fixture.Installation.Repair(fixture.Target, provider, fixture.NewExecutable); + Assert.Equal("repaired", repaired.State); + Assert.Equal(before, File.ReadAllBytes(repaired.Backup!)); + Assert.Equal("installed", fixture.Installation.Status(fixture.Target).State); + var after = File.ReadAllBytes(fixture.Target); + if (fixture.Original is not null) + { + var configuration = JsonNode.Parse(after)!; + Assert.Equal("Read", configuration["permissions"]!["allow"]![0]!.GetValue()); + Assert.Equal("keep exactly", configuration["trust"]!.GetValue()); + } + Assert.Equal("already-current", fixture.Installation.Repair(fixture.Target, provider, fixture.NewExecutable).State); + Assert.Equal(after, File.ReadAllBytes(fixture.Target)); + fixture.Installation.Uninstall(fixture.Target, false); + if (fixture.Original is null) Assert.False(File.Exists(fixture.Target)); + else Assert.Equal(fixture.Original, File.ReadAllBytes(fixture.Target)); + Assert.True(File.Exists(repaired.Backup)); + } + + [Fact] + public void ModifiedProviderFileAndCorruptOriginalBackupAreNeverOverwritten() + { + using var fixture = new Fixture(AgentProvider.Claude, false); + var installed = File.ReadAllBytes(fixture.Target); + File.AppendAllText(fixture.Target, " "); + var changed = File.ReadAllBytes(fixture.Target); + Assert.Equal("modified", fixture.Installation.PreviewRepair(fixture.Target, AgentProvider.Claude, fixture.NewExecutable).State); + Assert.Throws(() => fixture.Installation.Repair(fixture.Target, AgentProvider.Claude, fixture.NewExecutable)); + Assert.Equal(changed, File.ReadAllBytes(fixture.Target)); + File.WriteAllBytes(fixture.Target, installed); + File.WriteAllText(fixture.Installation.Status(fixture.Target).Backup!, "corrupted backup"); + Assert.Throws(() => fixture.Installation.PreviewRepair(fixture.Target, AgentProvider.Claude, fixture.NewExecutable)); + Assert.Equal(installed, File.ReadAllBytes(fixture.Target)); + } + + [Fact] + public void AnExistingProviderFileWithoutOwnershipIsOnlyReported() + { + using var fixture = new Fixture(AgentProvider.Claude, false); + Directory.Delete(fixture.Manifests, true); + var before = File.ReadAllBytes(fixture.Target); + Assert.Equal("not-installed", fixture.Installation.PreviewRepair(fixture.Target, AgentProvider.Claude, fixture.NewExecutable).State); + Assert.False(Directory.Exists(fixture.Manifests)); + Assert.Equal(before, File.ReadAllBytes(fixture.Target)); + } + + [Theory] + [InlineData(false)] [InlineData(true)] + public void InterruptedRepairCanReconcileEitherAtomicWriteBoundary(bool targetWasReplaced) + { + using var fixture = new Fixture(AgentProvider.Claude, false); + var before = File.ReadAllBytes(fixture.Target); + var completed = fixture.Installation.Repair(fixture.Target, AgentProvider.Claude, fixture.NewExecutable); + var manifest = Directory.GetFiles(fixture.Manifests, "*.json").Single(); + var journal = JsonNode.Parse(File.ReadAllBytes(manifest))!.AsObject(); + journal["PreviousInstalledHash"] = Convert.ToHexString(SHA256.HashData(before)); + File.WriteAllText(manifest, journal.ToJsonString()); + if (!targetWasReplaced) File.WriteAllBytes(fixture.Target, before); + var providerBytes = File.ReadAllBytes(fixture.Target); + Assert.Equal("repair-pending", fixture.Installation.Status(fixture.Target).State); + Assert.Throws(() => fixture.Installation.Uninstall(fixture.Target, true)); + Assert.Throws(() => fixture.Installation.Uninstall(fixture.Target, false)); + Assert.Equal("preview-recover", fixture.Installation.RecoverRepair(fixture.Target, true).State); + Assert.Equal("repair-pending", fixture.Installation.Status(fixture.Target).State); + Assert.Equal("recovered", fixture.Installation.RecoverRepair(fixture.Target, false).State); + Assert.Equal("installed", fixture.Installation.Status(fixture.Target).State); + Assert.Equal(providerBytes, File.ReadAllBytes(fixture.Target)); + Assert.True(File.Exists(completed.Backup)); + fixture.Installation.Uninstall(fixture.Target, false); + Assert.Equal(fixture.Original, File.ReadAllBytes(fixture.Target)); + } + + [Theory] + [InlineData("provider")] [InlineData("backup")] [InlineData("missing-backup")] + public void RecoveryNeverOverwritesManualEditsOrTrustsAModifiedRepairBackup(string changed) + { + using var fixture = new Fixture(AgentProvider.Claude, false); + var before = File.ReadAllBytes(fixture.Target); + var repair = fixture.Installation.Repair(fixture.Target, AgentProvider.Claude, fixture.NewExecutable); + var manifest = Directory.GetFiles(fixture.Manifests, "*.json").Single(); + var journal = JsonNode.Parse(File.ReadAllBytes(manifest))!.AsObject(); + journal["PreviousInstalledHash"] = Convert.ToHexString(SHA256.HashData(before)); + if (changed == "missing-backup") + { + journal["PreviousInstalledHash"] = "absent"; // Corrupt metadata must not make a missing backup look valid. + File.Delete(repair.Backup!); + } + else File.AppendAllText(changed == "backup" ? repair.Backup! : fixture.Target, " manual change"); + File.WriteAllText(manifest, journal.ToJsonString()); + var current = File.ReadAllBytes(fixture.Target); + Assert.Throws(() => fixture.Installation.RecoverRepair(fixture.Target, false)); + Assert.Equal(current, File.ReadAllBytes(fixture.Target)); + } + + [Fact] + public void RepairPreservesUnixAccessMode() + { + if (OperatingSystem.IsWindows()) return; + using var fixture = new Fixture(AgentProvider.Claude, false); + File.SetUnixFileMode(fixture.Target, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.GroupRead); + fixture.Installation.Repair(fixture.Target, AgentProvider.Claude, fixture.NewExecutable); + Assert.Equal(UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.GroupRead, File.GetUnixFileMode(fixture.Target)); + } + + [Fact] + public void RefusesAProviderSymlink() + { + if (OperatingSystem.IsWindows()) return; + using var fixture = new Fixture(AgentProvider.Claude, false); + var real = fixture.Target + ".real"; File.Move(fixture.Target, real); File.CreateSymbolicLink(fixture.Target, real); + Assert.Throws(() => fixture.Installation.PreviewRepair(fixture.Target, AgentProvider.Claude, fixture.NewExecutable)); + } + + [Fact] + public void RepairOptionsFailClosedOnMisspellings() + { + Assert.Throws(() => SidePulse.Cli.MaintenanceArguments.Validate(["agents", "repair", "--apply", "--dryrun"])); + Assert.Throws(() => SidePulse.Cli.MaintenanceArguments.Validate(["agents", "repair", "--exe="])); + } + + private sealed class Fixture : IDisposable + { + public string Root { get; } = Path.Combine(Path.GetTempPath(), "SidePulse repair ' ü " + Guid.NewGuid()); + public string Target { get; } + public string Manifests { get; } + public string OldExecutable { get; } + public string NewExecutable { get; } + public HookInstallation Installation { get; } + public byte[]? Original { get; } + public Fixture(AgentProvider provider, bool windows) + { + Directory.CreateDirectory(Root); + Target = Path.Combine(Root, provider == AgentProvider.OpenCode ? "plugin.js" : "settings.json"); + Manifests = Path.Combine(Root, "manifests"); + OldExecutable = Path.Combine(Root, "old ' ü", OperatingSystem.IsWindows() ? "spn.exe" : "spn"); + NewExecutable = Path.Combine(Root, "new ' ü", OperatingSystem.IsWindows() ? "spn.exe" : "spn"); + foreach (var path in new[] { OldExecutable, NewExecutable }) { Directory.CreateDirectory(Path.GetDirectoryName(path)!); File.WriteAllText(path, "fixture"); } + if (provider is AgentProvider.Claude or AgentProvider.Codex) + { + Original = System.Text.Encoding.UTF8.GetBytes("{\n \"permissions\":{\"allow\":[\"Read\"]},\"trust\":\"keep exactly\",\"hooks\":{\"Stop\":[{\"hooks\":[{\"command\":\"unrelated\"}]}]}\n}"); + File.WriteAllBytes(Target, Original); + } + Installation = new HookInstallation(Manifests); + Installation.Install(Target, provider, HookConfiguration.Generate(provider, OldExecutable, windows), false); + } + public void Dispose() => Directory.Delete(Root, true); + } +}