Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions docs/wiki/Agent-Integrations.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
4 changes: 4 additions & 0 deletions docs/wiki/Installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
61 changes: 61 additions & 0 deletions scripts/agent_smoke.py
Original file line number Diff line number Diff line change
@@ -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()
Expand Down Expand Up @@ -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']

Expand Down
77 changes: 77 additions & 0 deletions src/SidePulse.Cli/AgentRepair.cs
Original file line number Diff line number Diff line change
@@ -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 <PATH>")] public string Executable { get; init; } = Installation.PreferredExecutable;
[CommandOption("--config <PATH>")] 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<HookRepairPreview> providers);
public sealed class AgentRepairCommand : AsyncCommand<AgentRepairSettings>
{
public override async Task<int> 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<AgentProvider>();
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<HookRepairPreview>();
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;
}
}
1 change: 1 addition & 0 deletions src/SidePulse.Cli/CliApplication.cs
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ static string[] Normalize(string[] command)
{
agents.SetDescription("Set up Copilot, Codex, Claude Code, Kiro and OpenCode lifecycle integrations.");
agents.AddCommand<AgentsListCommand>("list");
agents.AddCommand<AgentRepairCommand>("repair").WithDescription("Preview or repair owned hook paths without changing trust settings.");
agents.AddCommand<AgentInstallCommand>("install");
agents.AddCommand<AgentStatusCommand>("status");
agents.AddCommand<AgentUninstallCommand>("uninstall");
Expand Down
1 change: 1 addition & 0 deletions src/SidePulse.Cli/JsonContracts.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ public static JsonTypeInfo<T> Info<T>(JsonSerializerOptions? options = null)
[JsonSerializable(typeof(ExportReply))]
[JsonSerializable(typeof(ProfileReply))]
[JsonSerializable(typeof(AgentInstallReply))]
[JsonSerializable(typeof(AgentRepairReply))]
[JsonSerializable(typeof(InstallationStatus))]
[JsonSerializable(typeof(LinkReply))]
[JsonSerializable(typeof(AboutReply))]
Expand Down
28 changes: 28 additions & 0 deletions src/SidePulse.Cli/MaintenanceArguments.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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"))
Expand All @@ -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<string>(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]);
}
}
}
2 changes: 1 addition & 1 deletion src/SidePulse.Core/CoreJson.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
namespace SidePulse.Core;

internal sealed record LinkStoreDocument(int Version, string? DefaultAlias, List<PhoneLink> 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);
Expand Down
Loading
Loading