exec.zig

81.7 KB · raw

1// exec.zig — all process execution and SSH routing2// Commands call these functions; output is streamed or captured here.3const std = @import("std");4const builtin = @import("builtin");5const types = @import("types.zig");6const errors = @import("errors.zig");7const output = @import("output.zig");89// nixos-rebuild manages this profile; generation commands must target it10// explicitly. Bare nix-env defaults to the per-user profile, which is empty.11const SYSTEM_PROFILE = "/nix/var/nix/profiles/system";1213pub const RunResult = struct {14    stdout: []u8,15    stderr: []u8,16    exit_code: u8,17};1819pub const HookResult = enum {20    ok,21    failed,22    not_found,23};2425pub const HookRun = struct {26    result: HookResult,27    exit_code: u8 = 0,28    output: []u8,29};3031// Run a process and capture stdout+stderr (not streaming).32pub fn capture(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, cmd: []const []const u8) !RunResult {33    const argv = try buildArgv(gpa, machine, cmd);34    defer if (!machine.local) gpa.free(argv);3536    const result = std.process.run(gpa, io, .{ .argv = argv }) catch |e| {37        errors.error_info.setMessage("process failed: {s}", .{cmd[0]});38        return e;39    };4041    return .{42        .stdout = result.stdout,43        .stderr = result.stderr,44        .exit_code = switch (result.term) {45            .exited => |c| c,46            else => 1,47        },48    };49}5051// Run a process and stream its output to the terminal (inherit stdio).52pub fn stream(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, cmd: []const []const u8) !u8 {53    // The child inherits stdout and writes directly to the fd; flush any buffered54    // nina header first so it isn't reordered after the child's output.55    output.flush();56    const argv = try buildArgv(gpa, machine, cmd);57    defer if (!machine.local) gpa.free(argv);5859    var child = std.process.spawn(io, .{60        .argv = argv,61        .stdin = .inherit,62        .stdout = .inherit,63        .stderr = .inherit,64    }) catch |e| {65        errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]});66        return e;67    };6869    const term = child.wait(io) catch |e| {70        errors.error_info.setMessage("process wait failed", .{});71        return e;72    };7374    return switch (term) {75        .exited => |c| c,76        else => 1,77    };78}7980// Stream a process with an overridden PS1 in the child environment.81fn streamEnv(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, cmd: []const []const u8, base_env: *const std.process.Environ.Map, ps1: []const u8) !u8 {82    output.flush();83    const argv = try buildArgv(gpa, machine, cmd);84    defer if (!machine.local) gpa.free(argv);8586    var env = try base_env.clone(gpa);87    defer env.deinit();88    try env.put("PS1", ps1);89    try env.put("NINA_PS1", ps1);9091    var child = std.process.spawn(io, .{92        .argv = argv,93        .stdin = .inherit,94        .stdout = .inherit,95        .stderr = .inherit,96        .environ_map = &env,97    }) catch |e| {98        errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]});99        return e;100    };101102    const term = child.wait(io) catch |e| {103        errors.error_info.setMessage("process wait failed", .{});104        return e;105    };106107    return switch (term) {108        .exited => |c| c,109        else => 1,110    };111}112113fn createInteractiveShellRc(gpa: std.mem.Allocator, io: std.Io) ![]u8 {114    const out = try captureLocal(gpa, io, &.{ "mktemp", "/tmp/nina-shell-rc.XXXXXX" });115    defer gpa.free(out);116117    const path = std.mem.trim(u8, out, " \t\r\n");118    if (path.len == 0) return error.FileNotFound;119    const owned_path = try gpa.dupe(u8, path);120    errdefer gpa.free(owned_path);121122    const file = std.Io.Dir.createFile(.cwd(), io, owned_path, .{}) catch {123        errors.error_info.setMessage("could not write shell prompt setup", .{});124        return error.FileNotFound;125    };126    errdefer file.close(io);127128    const content =129        \\PS1="${NINA_PS1:-$PS1}"130        \\trap 'exit 130' INT131        \\132    ;133    file.writePositionalAll(io, content, 0) catch {134        errors.error_info.setMessage("could not write shell prompt setup", .{});135        return error.FileNotFound;136    };137    file.close(io);138139    return owned_path;140}141142// Stream a local process with inherited stdio (no SSH routing — for nix commands).143pub fn streamLocal(io: std.Io, cmd: []const []const u8) !u8 {144    output.flush();145    var child = std.process.spawn(io, .{146        .argv = cmd,147        .stdin = .inherit,148        .stdout = .inherit,149        .stderr = .inherit,150    }) catch |e| {151        errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]});152        return e;153    };154    const term = child.wait(io) catch {155        errors.error_info.setMessage("process wait failed", .{});156        return error.ProcessFailed;157    };158    return switch (term) {159        .exited => |c| c,160        else => 1,161    };162}163164// Run a process and capture output as a single string (no SSH routing — for local nix commands).165pub fn captureLocal(gpa: std.mem.Allocator, io: std.Io, cmd: []const []const u8) ![]u8 {166    const result = std.process.run(gpa, io, .{ .argv = cmd }) catch return error.ProcessFailed;167    defer gpa.free(result.stderr);168    switch (result.term) {169        .exited => |c| if (c != 0) {170            gpa.free(result.stdout);171            return error.ProcessFailed;172        },173        else => {174            gpa.free(result.stdout);175            return error.ProcessFailed;176        },177    }178    return result.stdout;179}180181// Create a directory and its parents, best-effort. Shelling out to `mkdir -p`182// matches how the rest of exec.zig provisions config locations (~/.config/nix).183pub fn ensureDir(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) void {184    _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir }) catch {};185}186187// Optional user hooks live in ~/.config/nina/hooks and must be executable.188// They are always local: hooks protect the user's local workflow before nina189// starts state-changing work.190pub fn runHook(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, hook_name: []const u8) !HookRun {191    const home = environ.get("HOME") orelse return .{192        .result = .not_found,193        .output = try gpa.dupe(u8, ""),194    };195196    const hook_dir = try std.fs.path.join(gpa, &.{ home, ".config", "nina", "hooks" });197    defer gpa.free(hook_dir);198    ensureDir(gpa, io, hook_dir);199200    const hook_path = try std.fs.path.join(gpa, &.{ hook_dir, hook_name });201    defer gpa.free(hook_path);202203    const executable = std.process.run(gpa, io, .{ .argv = &.{ "sh", "-c", "test -x \"$1\"", "nina-hook-check", hook_path } }) catch return .{204        .result = .not_found,205        .output = try gpa.dupe(u8, ""),206    };207    defer gpa.free(executable.stdout);208    defer gpa.free(executable.stderr);209    const is_executable = switch (executable.term) {210        .exited => |code| code == 0,211        else => false,212    };213    if (!is_executable) return .{214        .result = .not_found,215        .output = try gpa.dupe(u8, ""),216    };217218    const tmp_raw = try captureLocal(gpa, io, &.{ "mktemp", "/tmp/nina-hook.XXXXXX" });219    defer gpa.free(tmp_raw);220    const tmp_output = std.mem.trim(u8, tmp_raw, " \t\r\n");221    defer if (std.fs.path.isAbsolute(tmp_output)) std.Io.Dir.deleteFileAbsolute(io, tmp_output) catch {};222223    const result = try std.process.run(gpa, io, .{224        .argv = &.{225            "sh",226            "-c",227            "$1 > \"$2\" 2>&1; code=$?; tail -c 4096 \"$2\"; exit \"$code\"",228            "nina-hook-run",229            hook_path,230            tmp_output,231        },232        .stdout_limit = .limited(4096),233        .stderr_limit = .limited(512),234    });235    defer gpa.free(result.stdout);236    defer gpa.free(result.stderr);237238    const exit_code = switch (result.term) {239        .exited => |code| code,240        else => 1,241    };242    return .{243        .result = if (exit_code == 0) .ok else .failed,244        .exit_code = exit_code,245        .output = try std.fmt.allocPrint(gpa, "{s}{s}", .{ result.stdout, result.stderr }),246    };247}248249test "runHook ignores non-executable hooks and captures failures" {250    const a = std.testing.allocator;251    const io = std.testing.io;252253    var tmp = std.testing.tmpDir(.{});254    defer tmp.cleanup();255256    const home = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{&tmp.sub_path});257    defer a.free(home);258259    var env: std.process.Environ.Map = .init(a);260    defer env.deinit();261    try env.put("HOME", home);262263    var hook_dir = try tmp.dir.createDirPathOpen(io, ".config/nina/hooks", .{});264    defer hook_dir.close(io);265266    const script =267        \\#!/bin/sh268        \\echo hook says no269        \\echo detail >&2270        \\exit 3271        \\272    ;273    {274        const file = try hook_dir.createFile(io, "pre-apply", .{});275        defer file.close(io);276        try file.writePositionalAll(io, script, 0);277        try file.setPermissions(io, .fromMode(0o644));278    }279280    const missing = try runHook(a, io, &env, "pre-apply");281    defer a.free(missing.output);282    try std.testing.expectEqual(HookResult.not_found, missing.result);283284    try hook_dir.setFilePermissions(io, "pre-apply", .fromMode(0o755), .{});285286    const failed = try runHook(a, io, &env, "pre-apply");287    defer a.free(failed.output);288    try std.testing.expectEqual(HookResult.failed, failed.result);289    try std.testing.expectEqual(@as(u8, 3), failed.exit_code);290    try std.testing.expect(std.mem.indexOf(u8, failed.output, "hook says no") != null);291    try std.testing.expect(std.mem.indexOf(u8, failed.output, "detail") != null);292}293294fn buildArgv(gpa: std.mem.Allocator, machine: *const types.Machine, cmd: []const []const u8) ![]const []const u8 {295    if (machine.local) return cmd;296297    const host = machine.host orelse {298        errors.error_info.setMessage("machine '{s}' has no host configured", .{machine.name});299        return error.SshFailed;300    };301302    var ssh: std.ArrayList([]const u8) = .empty;303    try ssh.append(gpa, "ssh");304    try ssh.append(gpa, "-o");305    try ssh.append(gpa, "BatchMode=yes");306    try ssh.append(gpa, "-o");307    try ssh.append(gpa, "StrictHostKeyChecking=accept-new");308    if (machine.ssh_key) |key| {309        try ssh.append(gpa, "-i");310        try ssh.append(gpa, key);311    }312    const addr = if (machine.user) |u|313        try std.fmt.allocPrint(gpa, "{s}@{s}", .{ u, host })314    else315        try gpa.dupe(u8, host);316    try ssh.append(gpa, addr);317    for (cmd) |arg| try ssh.append(gpa, arg);318    return ssh.toOwnedSlice(gpa);319}320321// --- NixOS rebuild ---322323// True if the machine's config dir holds a flake.nix. Only meaningful for a local324// machine — the file lives on the local filesystem. Remote flake detection would325// need an ssh round-trip; a remote flake at the default /etc/nixos needs no flag326// anyway, so we don't bother.327// True if `dir` contains a flake.nix (local filesystem check).328pub fn dirHasFlake(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) bool {329    const flake_path = std.fs.path.join(gpa, &.{ dir, "flake.nix" }) catch return false;330    defer gpa.free(flake_path);331    return pathExists(io, flake_path);332}333334pub fn configHasFlake(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {335    if (!machine.local) return false;336    return dirHasFlake(gpa, io, machine.config_path);337}338339// nixos-rebuild auto-detects /etc/nixos/flake.nix, so the --flake flag is only340// needed when the flake lives elsewhere. A flake at a non-default path must be341// passed explicitly or nixos-rebuild falls back to channels. Compare with342// trailing slashes trimmed so "/etc/nixos/" is still treated as the default.343fn useFlakeFlag(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {344    if (!configHasFlake(gpa, io, machine)) return false;345    var path = machine.config_path;346    while (path.len > 1 and path[path.len - 1] == '/') path = path[0 .. path.len - 1];347    return !std.mem.eql(u8, path, "/etc/nixos");348}349350// Capture nixos-rebuild stderr for the translation pipeline. Raw nix build351// output is suppressed; on failure, reportError() translates stderr via352// errors.translateError(). The substep line above the call tells the user what353// is running; silence during the build is intentional per the error-wrapping brief.354fn nixosRebuildRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, flake: bool) !u8 {355    const argv: []const []const u8 = if (flake)356        &.{ "sudo", "nixos-rebuild", verb, "--flake", machine.config_path }357    else358        &.{ "sudo", "nixos-rebuild", verb };359    output.flush();360    const r = try capture(gpa, io, machine, argv);361    defer gpa.free(r.stdout);362    defer gpa.free(r.stderr);363    errors.setBuildStderr(r.stderr);364    return r.exit_code;365}366367pub fn nixosRebuildSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {368    const flake = useFlakeFlag(gpa, io, machine);369    if (flake) {370        output.printSubstep("nixos-rebuild switch --flake {s}", .{machine.config_path});371    } else {372        output.printSubstep("nixos-rebuild switch", .{});373    }374    return nixosRebuildRun(io, machine, gpa, "switch", flake);375}376377// Live-streaming variant used by `apply` when stdout is a TTY. Each stderr line378// from nixos-rebuild is fed to the build panel for real-time progress display379// while the full stderr is also accumulated for the error translation pipeline.380// Falls back to the silent capture path when not a TTY.381pub fn nixosRebuildSwitchWithPanel(382    io: std.Io,383    machine: *const types.Machine,384    gpa: std.mem.Allocator,385    panel: *output.BuildPanel,386) !u8 {387    const flake = useFlakeFlag(gpa, io, machine);388    if (flake) {389        output.printSubstep("nixos-rebuild switch --flake {s}", .{machine.config_path});390    } else {391        output.printSubstep("nixos-rebuild switch", .{});392    }393    if (!output.colorEnabled()) return nixosRebuildRun(io, machine, gpa, "switch", flake);394    return nixosRebuildRunStreamed(io, machine, gpa, "switch", flake, panel);395}396397fn nixosRebuildRunStreamed(398    io: std.Io,399    machine: *const types.Machine,400    gpa: std.mem.Allocator,401    verb: []const u8,402    flake: bool,403    panel: *output.BuildPanel,404) !u8 {405    const argv: []const []const u8 = if (flake)406        &.{ "sudo", "nixos-rebuild", verb, "--flake", machine.config_path }407    else408        &.{ "sudo", "nixos-rebuild", verb };409410    output.flush();411    const built_argv = try buildArgv(gpa, machine, argv);412    defer if (!machine.local) gpa.free(built_argv);413414    var child = std.process.spawn(io, .{415        .argv = built_argv,416        .stdin = .ignore,417        .stdout = .ignore,418        .stderr = .pipe,419    }) catch |e| {420        errors.error_info.setMessage("failed to spawn nixos-rebuild", .{});421        return e;422    };423424    var accumulated: std.ArrayList(u8) = .empty;425    defer accumulated.deinit(gpa);426427    if (child.stderr) |stderr_file| {428        var reader_buf: [8192]u8 = undefined;429        var fr = std.Io.File.Reader.initStreaming(stderr_file, io, &reader_buf);430        while (true) {431            const maybe = fr.interface.takeDelimiter('\n') catch break;432            const raw = maybe orelse break;433            accumulated.appendSlice(gpa, raw) catch {};434            const line = std.mem.trimEnd(u8, raw, "\r\n");435            panel.update(line);436            panel.render();437        }438    }439440    errors.setBuildStderr(accumulated.items);441442    const term = child.wait(io) catch |e| {443        errors.error_info.setMessage("nixos-rebuild wait failed", .{});444        return e;445    };446    return switch (term) {447        .exited => |code| code,448        else => 1,449    };450}451452pub fn nixosRebuildDryActivate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {453    return nixosRebuildRun(io, machine, gpa, "dry-activate", useFlakeFlag(gpa, io, machine));454}455456pub fn nixosRebuildBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {457    return nixosRebuildRun(io, machine, gpa, "build", useFlakeFlag(gpa, io, machine));458}459460// --- Generations ---461462// Read system-profile generations WITHOUT root. `nix-env --list-generations -p463// /nix/var/nix/profiles/system` takes a profile lock and fails as a normal user464// ("system.lock: Permission denied"). The generation symlinks themselves are465// world-readable, so list them directly: parse `system-N-link` names, take each466// link's own mtime for the date/time, and mark the one the `system` symlink467// points at as current. Output matches the `nix-env --list-generations` columns468// (num date time [current]) so parseGenerations is unchanged.469const GEN_LIST_SCRIPT =470    \\cur=$(readlink /nix/var/nix/profiles/system 2>/dev/null | sed 's/.*system-\([0-9]*\)-link/\1/'); find /nix/var/nix/profiles -maxdepth 1 -name 'system-*-link' -printf '%f %TY-%Tm-%Td %TH:%TM\n' 2>/dev/null | sed 's/system-\([0-9]*\)-link/\1/' | sort -n | awk -v c="$cur" '{ if ($1==c) print $0" current"; else print $0 }'471;472473pub fn getGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.GenerationInfo {474    const r = try capture(gpa, io, machine, &.{ "sh", "-c", GEN_LIST_SCRIPT });475    defer gpa.free(r.stderr);476    defer gpa.free(r.stdout);477    if (r.exit_code != 0) return error.ProcessFailed;478    return parseGenerations(gpa, r.stdout);479}480481fn parseGenerations(gpa: std.mem.Allocator, output_str: []const u8) ![]types.GenerationInfo {482    var gens: std.ArrayList(types.GenerationInfo) = .empty;483    var lines = std.mem.splitScalar(u8, output_str, '\n');484    while (lines.next()) |line| {485        const trimmed = std.mem.trim(u8, line, " \t");486        if (trimmed.len == 0) continue;487        var parts = std.mem.tokenizeAny(u8, trimmed, " \t");488        const num_str = parts.next() orelse continue;489        const date_str = parts.next() orelse continue;490        const time_str = parts.next() orelse continue;491        const rest = parts.rest();492        const current = std.mem.indexOf(u8, rest, "current") != null;493        const num = std.fmt.parseInt(u32, num_str, 10) catch continue;494        try gens.append(gpa, .{495            .number = num,496            .date = try gpa.dupe(u8, date_str),497            .time = try gpa.dupe(u8, time_str),498            .current = current,499        });500    }501    return gens.toOwnedSlice(gpa);502}503504pub fn getCurrentGeneration(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !u32 {505    const gens = try getGenerations(gpa, io, machine);506    defer gpa.free(gens);507    for (gens) |g| {508        if (g.current) return g.number;509    }510    return 0;511}512513pub fn switchGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {514    // Switch the system profile to generation n, then activate it (bootloader +515    // services). Without switch-to-configuration the change isn't applied.516    const cmd = try std.fmt.allocPrint(gpa, "nix-env -p {s} --switch-generation {d} && {s}/bin/switch-to-configuration switch", .{ SYSTEM_PROFILE, n, SYSTEM_PROFILE });517    defer gpa.free(cmd);518    return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });519}520521pub fn rollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {522    return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "switch", "--rollback" });523}524525pub fn deleteGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {526    const n_str = try std.fmt.allocPrint(gpa, "{d}", .{n});527    defer gpa.free(n_str);528    return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", n_str });529}530531pub fn deleteOldGenerations(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {532    return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", "old" });533}534535// --- Garbage collection ---536537pub fn collectGarbage(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, delete_old: bool, keep: u32) !u8 {538    if (delete_old) {539        return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage", "-d" });540    }541    // Keep the `keep` most recent system generations (+N deletes all but N),542    // then collect now-unreferenced store paths. `--delete-older-than` wants a543    // duration (e.g. 14d), not a generation count.544    const cmd = try std.fmt.allocPrint(gpa, "nix-env -p {s} --delete-generations +{d} && nix-collect-garbage", .{ SYSTEM_PROFILE, keep });545    defer gpa.free(cmd);546    return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });547}548549// --- Channels ---550551pub fn channelList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.ChannelInfo {552    const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });553    defer gpa.free(r.stderr);554    defer gpa.free(r.stdout);555    if (r.exit_code != 0) return error.ProcessFailed;556    return parseChannels(gpa, r.stdout);557}558559fn parseChannels(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ChannelInfo {560    var channels: std.ArrayList(types.ChannelInfo) = .empty;561    var lines = std.mem.splitScalar(u8, output_str, '\n');562    while (lines.next()) |line| {563        const trimmed = std.mem.trim(u8, line, " \t\r");564        if (trimmed.len == 0) continue;565        const space = std.mem.indexOfScalar(u8, trimmed, ' ') orelse continue;566        try channels.append(gpa, .{567            .name = try gpa.dupe(u8, trimmed[0..space]),568            .url = try gpa.dupe(u8, std.mem.trim(u8, trimmed[space + 1 ..], " \t")),569        });570    }571    return channels.toOwnedSlice(gpa);572}573574pub fn channelUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {575    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--update" });576}577578pub fn channelAdd(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8, name: []const u8) !u8 {579    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--add", url, name });580}581582pub fn channelRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8) !u8 {583    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--remove", name });584}585586// --- Services ---587588pub fn serviceList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, user: bool) ![]types.ServiceInfo {589    const cmd: []const []const u8 = if (user)590        &.{ "systemctl", "--user", "list-units", "--type=service", "--no-legend", "--no-pager" }591    else592        &.{ "systemctl", "list-units", "--type=service", "--no-legend", "--no-pager" };593    const r = try capture(gpa, io, machine, cmd);594    defer gpa.free(r.stderr);595    defer gpa.free(r.stdout);596    if (r.exit_code != 0) return error.ProcessFailed;597    return parseServices(gpa, r.stdout);598}599600fn parseServices(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ServiceInfo {601    var svcs: std.ArrayList(types.ServiceInfo) = .empty;602    var lines = std.mem.splitScalar(u8, output_str, '\n');603    while (lines.next()) |line| {604        const trimmed = std.mem.trim(u8, line, " \t\r");605        if (trimmed.len == 0 or trimmed[0] == 0xE2) continue; // skip UTF-8 bullet lines606        var parts = std.mem.tokenizeAny(u8, trimmed, " \t");607        const name = parts.next() orelse continue;608        _ = parts.next(); // load609        const active_str = parts.next() orelse continue;610        const sub_str = parts.next() orelse "unknown";611612        const state: types.ServiceState = if (std.mem.eql(u8, active_str, "active"))613            (if (std.mem.eql(u8, sub_str, "running") or std.mem.eql(u8, sub_str, "exited")) .active else .active)614        else if (std.mem.eql(u8, active_str, "failed"))615            .failed616        else617            .inactive;618619        try svcs.append(gpa, .{620            .name = try gpa.dupe(u8, name),621            .state = state,622            .uptime = null,623        });624    }625    return svcs.toOwnedSlice(gpa);626}627628pub fn serviceCtl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, name: []const u8, user: bool) !u8 {629    // --no-pager: `systemctl status` pipes to a pager on a tty and would block.630    // User services run under the caller's own systemd manager, so no sudo.631    if (user) {632        return stream(io, machine, gpa, &.{ "systemctl", "--user", "--no-pager", verb, name });633    }634    return stream(io, machine, gpa, &.{ "sudo", "systemctl", "--no-pager", verb, name });635}636637pub fn serviceLogs(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8, last: u32, follow: bool, user: bool) !u8 {638    const n_str = try std.fmt.allocPrint(gpa, "{d}", .{last});639    defer gpa.free(n_str);640    if (user) {641        if (follow) return stream(io, machine, gpa, &.{ "journalctl", "--user", "-u", name, "-f" });642        return stream(io, machine, gpa, &.{ "journalctl", "--user", "-u", name, "-n", n_str, "--no-pager" });643    }644    if (follow) {645        return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-f" });646    }647    return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-n", n_str, "--no-pager" });648}649650// --- Profile ---651652pub fn profileInstall(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {653    const pkg_ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{attr});654    defer gpa.free(pkg_ref);655    // `nix profile add` is the current verb; `install` is a deprecated alias that656    // prints a warning on modern nix.657    return stream(io, machine, gpa, &.{ "nix", "profile", "add", pkg_ref });658}659660pub fn profileRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {661    // `nix profile remove` matches by profile element name (e.g. "ripgrep"), not662    // by flake ref — passing nixpkgs#ripgrep matches nothing.663    return stream(io, machine, gpa, &.{ "nix", "profile", "remove", attr });664}665666pub fn profileList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {667    const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list" });668    defer gpa.free(r.stderr);669    if (r.exit_code != 0) return error.ProcessFailed;670    return r.stdout;671}672673// Machine-readable profile listing — caller parses elements -> name + version.674pub fn profileListJson(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {675    const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list", "--json" });676    defer gpa.free(r.stderr);677    if (r.exit_code != 0) {678        gpa.free(r.stdout);679        return error.ProcessFailed;680    }681    return r.stdout;682}683684// Returns the profile element name to pass to `nix profile remove/upgrade`685// (e.g. "nina" or "default"), or null if nina is not found. Caller owns the686// returned slice. A NixOS system-package install also resolves into /nix/store687// so the store path alone can't distinguish it from a profile install — the688// profile list can. A missing/empty profile (or no nix) returns null.689pub fn profileNinaElement(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ?[]const u8 {690    const js = profileListJson(gpa, io, machine) catch return null;691    defer gpa.free(js);692    return profileJsonNinaElement(gpa, js);693}694695696pub fn profileHasNina(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {697    const name = profileNinaElement(gpa, io, machine) orelse return false;698    gpa.free(name);699    return true;700}701702// True when a nix store path belongs to the nina package. Store paths have the703// form /nix/store/<32-char-hash>-<pname>-<version>[/<subpath>]. We check that704// the 33 chars after /nix/store/ are the hash+dash, and the pname that follows705// is exactly "nina" (followed by "-" or end-of-component).706fn storePathIsNina(path: []const u8) bool {707    const prefix = "/nix/store/";708    if (!std.mem.startsWith(u8, path, prefix)) return false;709    const rel = path[prefix.len..];710    // The store entry name ends at the first "/" (if any sub-path follows).711    const entry = rel[0 .. std.mem.indexOf(u8, rel, "/") orelse rel.len];712    if (entry.len < 34) return false; // 32-char hash + dash + at least one char713    const pname_ver = entry[33..]; // skip hash + dash714    return std.mem.startsWith(u8, pname_ver, "nina-") or std.mem.eql(u8, pname_ver, "nina");715}716717// Pure parse of `nix profile list --json` for a nina element, returning its718// element name (the key to pass to `nix profile remove/upgrade`) or null.719// Newer nix (2.18+) keys elements by pname ("nina"). Older nix uses an array720// with an "attrPath" field. Tarball installs via the `default` output may use721// the key "default" instead of "nina"; we detect those via storePaths.722fn profileJsonNinaElement(gpa: std.mem.Allocator, js: []const u8) ?[]const u8 {723    var parsed = std.json.parseFromSlice(std.json.Value, gpa, js, .{}) catch return null;724    defer parsed.deinit();725    const root = parsed.value;726    if (root != .object) return null;727    const elements = root.object.get("elements") orelse return null;728    switch (elements) {729        .object => |obj| {730            // Fast path: exact "nina" key (nix 2.18+ with nixpkgs#nina install).731            if (obj.contains("nina")) return gpa.dupe(u8, "nina") catch null;732            // Fallback: scan storePaths. Handles tarball installs where the default733            // output is selected and nix names the element "default" (older nix) or734            // some other key derived from the attrPath rather than the pname.735            var it = obj.iterator();736            while (it.next()) |kv| {737                const val = kv.value_ptr.*;738                if (val != .object) continue;739                const sps = val.object.get("storePaths") orelse continue;740                if (sps != .array) continue;741                for (sps.array.items) |sp| {742                    if (sp == .string and storePathIsNina(sp.string))743                        return gpa.dupe(u8, kv.key_ptr.*) catch null;744                }745            }746            return null;747        },748        .array => |arr| {749            // Older nix array format. Element name is the last component of attrPath.750            for (arr.items) |el| {751                if (el != .object) continue;752                const ap = el.object.get("attrPath") orelse continue;753                if (ap != .string) continue;754                if (std.mem.eql(u8, ap.string, "nina") or755                    std.mem.endsWith(u8, ap.string, ".nina"))756                    return gpa.dupe(u8, "nina") catch null;757                // Tarball default-output install: attrPath ends in ".default" but758                // storePaths point to nina. Return "default" as the element name.759                const sps = el.object.get("storePaths") orelse continue;760                if (sps != .array) continue;761                for (sps.array.items) |sp| {762                    if (sp != .string) continue;763                    if (!storePathIsNina(sp.string)) continue;764                    const dot = std.mem.lastIndexOf(u8, ap.string, ".") orelse 0;765                    const el_name = if (dot > 0) ap.string[dot + 1 ..] else ap.string;766                    return gpa.dupe(u8, el_name) catch null;767                }768            }769            return null;770        },771        else => return null,772    }773}774775test "profileJsonNinaElement finds element name from profile JSON" {776    const a = std.testing.allocator;777778    // Newer nix: elements keyed by pname. "nina" key present.779    const named =780        \\{"elements":{"bat":{"storePaths":["/nix/store/h0000000000000000000000000000000-bat-0.26.1"]},781        \\"nina":{"attrPath":"packages.x86_64-linux.nina","storePaths":["/nix/store/a0000000000000000000000000000000-nina-3.0.15"]}},"version":3}782    ;783    const r1 = profileJsonNinaElement(a, named);784    defer if (r1) |n| a.free(n);785    try std.testing.expectEqualStrings("nina", r1.?);786787    // Tarball install via default output: element keyed as "default", storePath is nina.788    const default_key =789        \\{"elements":{"default":{"attrPath":"packages.x86_64-linux.default","storePaths":["/nix/store/w0000000000000000000000000000000-nina-3.0.16"]}},"version":3}790    ;791    const r2 = profileJsonNinaElement(a, default_key);792    defer if (r2) |n| a.free(n);793    try std.testing.expectEqualStrings("default", r2.?);794795    // Decoy: storePath of another package contains "nina" as a substring but is not nina.796    const decoy =797        \\{"elements":{"luminance":{"storePaths":["/nix/store/x0000000000000000000000000000000-luminance-nina-1.0"]}},"version":3}798    ;799    const r3 = profileJsonNinaElement(a, decoy);800    try std.testing.expectEqual(@as(?[]const u8, null), r3);801802    // Older nix array schema, attrPath ending in ".nina".803    const arr =804        \\{"elements":[{"attrPath":"legacyPackages.x86_64-linux.nina","storePaths":["/nix/store/a0000000000000000000000000000000-nina-3.0.15"]}],"version":2}805    ;806    const r4 = profileJsonNinaElement(a, arr);807    defer if (r4) |n| a.free(n);808    try std.testing.expectEqualStrings("nina", r4.?);809810    // Older nix array schema, tarball default-output install.811    const arr_default =812        \\{"elements":[{"attrPath":"packages.x86_64-linux.default","storePaths":["/nix/store/w0000000000000000000000000000000-nina-3.0.16"]}],"version":2}813    ;814    const r5 = profileJsonNinaElement(a, arr_default);815    defer if (r5) |n| a.free(n);816    try std.testing.expectEqualStrings("default", r5.?);817818    // Empty / malformed → null.819    try std.testing.expectEqual(@as(?[]const u8, null), profileJsonNinaElement(a, "{\"elements\":{},\"version\":3}"));820    try std.testing.expectEqual(@as(?[]const u8, null), profileJsonNinaElement(a, "not json"));821}822823// The store paths that make up the running system environment. Each reference is824// a <hash>-<name>-<version> path, so the caller can list system packages with825// versions — there is no cleaner per-package list for environment.systemPackages.826pub fn systemPackagePaths(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {827    const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", "/run/current-system/sw" });828    defer gpa.free(r.stderr);829    if (r.exit_code != 0) {830        gpa.free(r.stdout);831        return error.ProcessFailed;832    }833    return r.stdout;834}835836pub fn profileUpgrade(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {837    return stream(io, machine, gpa, &.{ "nix", "profile", "upgrade", ".*" });838}839840// --- Store ---841842pub fn storeGc(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {843    return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage" });844}845846pub fn storeVerify(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {847    return stream(io, machine, gpa, &.{ "nix", "store", "verify", "--all" });848}849850// Deduplicate identical store files via hard links — frees space without851// garbage-collecting any paths.852pub fn storeOptimise(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {853    return stream(io, machine, gpa, &.{ "nix", "store", "optimise" });854}855856pub const SystemStatus = struct { size: []u8, age: []u8 };857858// One read-only pass for `nina status`: the current system's closure size (a859// single `path-info -S` of /run/current-system — fast, unlike -S over the whole860// store) and seconds since the system profile was last switched (its symlink861// mtime). Both are world-readable; no root needed.862const STATUS_SCRIPT =863    \\sz=$(nix path-info -S /run/current-system 2>/dev/null | awk '{print $NF}'); mt=$(stat -c %Y /nix/var/nix/profiles/system 2>/dev/null); now=$(date +%s); echo "${sz:-0} $(( ${now:-0} - ${mt:-0} ))"864;865866pub fn systemStatus(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) SystemStatus {867    const unknown = SystemStatus{868        .size = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },869        .age = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },870    };871    const r = capture(gpa, io, machine, &.{ "sh", "-c", STATUS_SCRIPT }) catch return unknown;872    defer gpa.free(r.stdout);873    defer gpa.free(r.stderr);874    if (r.exit_code != 0) return unknown;875876    var it = std.mem.tokenizeAny(u8, r.stdout, " \t\n\r");877    const sz_str = it.next() orelse return unknown;878    const age_str = it.next() orelse return unknown;879    const bytes = std.fmt.parseInt(u64, sz_str, 10) catch 0;880    const age_secs = std.fmt.parseInt(u64, age_str, 10) catch 0;881882    gpa.free(unknown.size);883    gpa.free(unknown.age);884    return .{885        .size = humanSize(gpa, bytes) catch (gpa.dupe(u8, "") catch ""),886        .age = humanAgo(gpa, age_secs) catch (gpa.dupe(u8, "") catch ""),887    };888}889890// `systemctl is-system-running` -> "running" / "degraded" / "starting" ... A891// one-word health signal; exits non-zero when degraded, so we read stdout, not892// the code. Caller owns the returned slice.893pub fn systemRunningState(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {894    const r = capture(gpa, io, machine, &.{ "systemctl", "is-system-running" }) catch895        return gpa.dupe(u8, "unknown");896    defer gpa.free(r.stderr);897    const state = std.mem.trim(u8, r.stdout, " \t\n\r");898    const owned = try gpa.dupe(u8, if (state.len > 0) state else "unknown");899    gpa.free(r.stdout);900    return owned;901}902903fn humanAgo(gpa: std.mem.Allocator, secs: u64) ![]u8 {904    if (secs < 60) return std.fmt.allocPrint(gpa, "{d}s ago", .{secs});905    if (secs < 3600) return std.fmt.allocPrint(gpa, "{d}m ago", .{secs / 60});906    if (secs < 86400) return std.fmt.allocPrint(gpa, "{d}h ago", .{secs / 3600});907    return std.fmt.allocPrint(gpa, "{d}d ago", .{secs / 86400});908}909910pub fn storeRepair(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {911    return stream(io, machine, gpa, &.{ "sudo", "nix", "store", "repair", "--all" });912}913914pub fn storeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !types.StoreInfo {915    // `nix path-info -S --all` computes the CLOSURE size of every path — O(paths^2)916    // graph work that takes minutes on a real store (59k+ paths) and hangs the917    // command. We don't need closures: `--all --json` (no -S) carries each path's918    // own narSize, so one fast pass gives the path count and the summed store size.919    // `du -sh /nix/store` is just as slow on a big store, so it's gone too.920    // timeout-wrapped so a pathological store degrades to "?" instead of hanging.921    const pi = try capture(gpa, io, machine, &.{ "sh", "-c", "timeout 90 nix path-info --all --json 2>/dev/null" });922    defer gpa.free(pi.stdout);923    defer gpa.free(pi.stderr);924925    const scan = scanStoreJson(pi.stdout);926    const total_owned = try humanSize(gpa, scan.total_bytes);927928    return .{929        .total_size = total_owned,930        .live_paths = scan.count,931        .reclaimable_paths = 0,932    };933}934935const StoreScan = struct { count: u64, total_bytes: u64 };936937// One linear pass over `nix path-info --json`: each path object has exactly one938// "narSize": field, so counting them gives the true path count and summing the939// values gives the total store size — no per-path closure walk.940fn scanStoreJson(json_str: []const u8) StoreScan {941    const needle = "\"narSize\":";942    var count: u64 = 0;943    var total: u64 = 0;944    var i: usize = 0;945    while (std.mem.indexOfPos(u8, json_str, i, needle)) |pos| {946        var j = pos + needle.len;947        while (j < json_str.len and json_str[j] == ' ') : (j += 1) {}948        var val: u64 = 0;949        var any = false;950        while (j < json_str.len and json_str[j] >= '0' and json_str[j] <= '9') : (j += 1) {951            val = val * 10 + (json_str[j] - '0');952            any = true;953        }954        if (any) {955            count += 1;956            total += val;957        }958        i = j;959    }960    return .{ .count = count, .total_bytes = total };961}962963fn humanSize(gpa: std.mem.Allocator, bytes: u64) ![]u8 {964    const units = [_][]const u8{ "B", "KB", "MB", "GB", "TB" };965    var val: f64 = @floatFromInt(bytes);966    var unit: usize = 0;967    while (val >= 1024.0 and unit + 1 < units.len) : (unit += 1) val /= 1024.0;968    if (unit == 0) return std.fmt.allocPrint(gpa, "{d} {s}", .{ bytes, units[0] });969    return std.fmt.allocPrint(gpa, "{d:.1} {s}", .{ val, units[unit] });970}971972pub fn storePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, attr: []const u8) ![]u8 {973    // nixpkgs#<attr>, not .#<attr>: the package lives in nixpkgs (resolved via the974    // flake registry), not a flake in the current directory.975    const expr = try std.fmt.allocPrint(gpa, "nixpkgs#{s}.outPath", .{attr});976    defer gpa.free(expr);977    const r = try capture(gpa, io, machine, &.{ "nix", "eval", "--raw", expr });978    defer gpa.free(r.stderr);979    if (r.exit_code != 0) {980        gpa.free(r.stdout);981        return error.ProcessFailed;982    }983    return r.stdout;984}985986// --- Flake ---987988pub fn flakeUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, input: ?[]const u8) !u8 {989    if (input) |inp| {990        return stream(io, machine, gpa, &.{ "nix", "flake", "update", inp });991    }992    return stream(io, machine, gpa, &.{ "nix", "flake", "update" });993}994995// Update flake inputs for the flake living in `dir` (the config dir). `nix flake996// update` operates on the flake in the working directory, so we cd there first.997// Used by `nina upgrade` on a flake system in place of nix-channel --update.998pub fn flakeUpdateAt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, dir: []const u8) !u8 {999    return stream(io, machine, gpa, &.{ "sh", "-c", "cd \"$0\" && nix flake update", dir });1000}10011002pub fn flakeCheck(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1003    return stream(io, machine, gpa, &.{ "nix", "flake", "check" });1004}10051006pub fn flakeInit(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1007    return stream(io, machine, gpa, &.{ "nix", "flake", "init" });1008}10091010pub fn flakeLock(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1011    return stream(io, machine, gpa, &.{ "nix", "flake", "lock" });1012}10131014pub fn flakeClone(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8) !u8 {1015    return stream(io, machine, gpa, &.{ "nix", "flake", "clone", url });1016}10171018pub fn flakeShow(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1019    const r = try capture(gpa, io, machine, &.{ "nix", "flake", "show", "--json" });1020    defer gpa.free(r.stderr);1021    if (r.exit_code != 0) {1022        gpa.free(r.stdout);1023        return error.ProcessFailed;1024    }1025    return r.stdout;1026}10271028// --- Build / Run / Develop ---10291030pub fn nixBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: ?[]const u8) !u8 {1031    if (attr) |a| {1032        const ref = try std.fmt.allocPrint(gpa, ".#{s}", .{a});1033        defer gpa.free(ref);1034        return stream(io, machine, gpa, &.{ "nix", "build", ref });1035    }1036    return stream(io, machine, gpa, &.{ "nix", "build" });1037}10381039pub fn nixRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1040    // nix run always gets --no-write-lock-file for remote URLs1041    const is_url = std.mem.startsWith(u8, pkg, "http://") or std.mem.startsWith(u8, pkg, "https://") or std.mem.startsWith(u8, pkg, "github:");1042    if (is_url) {1043        return stream(io, machine, gpa, &.{ "nix", "run", pkg, "--no-write-lock-file" });1044    }1045    // Already a flake ref (contains '#') → use as-is; bare name → default to nixpkgs#.1046    if (std.mem.indexOfScalar(u8, pkg, '#') != null) {1047        return stream(io, machine, gpa, &.{ "nix", "run", pkg });1048    }1049    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});1050    defer gpa.free(ref);1051    return stream(io, machine, gpa, &.{ "nix", "run", ref });1052}10531054pub fn nixShell(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1055    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});1056    defer gpa.free(ref);1057    return stream(io, machine, gpa, &.{ "nix", "shell", ref });1058}10591060pub fn nixShellPs1(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8, base_env: *const std.process.Environ.Map) !u8 {1061    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});1062    defer gpa.free(ref);1063    const ps1 = try std.fmt.allocPrint(gpa, "(nina: {s}) -> ", .{pkg});1064    defer gpa.free(ps1);1065    if (machine.local) {1066        const rc_path = try createInteractiveShellRc(gpa, io);1067        defer {1068            std.Io.Dir.deleteFile(.cwd(), io, rc_path) catch {};1069            gpa.free(rc_path);1070        }1071        return streamEnv(io, machine, gpa, &.{ "nix", "shell", ref, "--command", "bash", "--rcfile", rc_path, "-i" }, base_env, ps1);1072    }1073    return streamEnv(io, machine, gpa, &.{ "nix", "shell", ref }, base_env, ps1);1074}10751076pub fn nixDevelop(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, run_cmd: ?[]const u8) !u8 {1077    if (run_cmd) |cmd| {1078        // sh -c so a multi-word command isn't treated as a single executable name.1079        return stream(io, machine, gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });1080    }1081    return stream(io, machine, gpa, &.{ "nix", "develop" });1082}10831084pub fn nixDevelopPs1(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, run_cmd: ?[]const u8, base_env: *const std.process.Environ.Map) !u8 {1085    if (run_cmd) |cmd| {1086        // sh -c so a multi-word command isn't treated as a single executable name.1087        return stream(io, machine, gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });1088    }1089    if (machine.local) {1090        const rc_path = try createInteractiveShellRc(gpa, io);1091        defer {1092            std.Io.Dir.deleteFile(.cwd(), io, rc_path) catch {};1093            gpa.free(rc_path);1094        }1095        return streamEnv(io, machine, gpa, &.{ "nix", "develop", "--command", "bash", "--rcfile", rc_path, "-i" }, base_env, "(nina: dev) -> ");1096    }1097    return streamEnv(io, machine, gpa, &.{ "nix", "develop" }, base_env, "(nina: dev) -> ");1098}10991100pub fn nixRepl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1101    return stream(io, machine, gpa, &.{ "nix", "repl", "--expr", "import <nixpkgs> {}" });1102}11031104// --- Format ---11051106pub fn nixpkgsFmt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, path: []const u8, check: bool) !u8 {1107    if (check) {1108        return stream(io, machine, gpa, &.{ "nixpkgs-fmt", "--check", path });1109    }1110    return stream(io, machine, gpa, &.{ "nixpkgs-fmt", path });1111}11121113// --- Info ---11141115pub fn systemInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1116    const r = try capture(gpa, io, machine, &.{"nixos-version"});1117    defer gpa.free(r.stderr);1118    if (r.exit_code != 0) {1119        gpa.free(r.stdout);1120        return error.ProcessFailed;1121    }1122    return r.stdout;1123}11241125pub fn kernelInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1126    const r = try capture(gpa, io, machine, &.{ "uname", "-r" });1127    defer gpa.free(r.stderr);1128    if (r.exit_code != 0) {1129        gpa.free(r.stdout);1130        return error.ProcessFailed;1131    }1132    return r.stdout;1133}11341135pub fn uptimeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1136    const r = try capture(gpa, io, machine, &.{"uptime"});1137    defer gpa.free(r.stderr);1138    if (r.exit_code != 0) {1139        gpa.free(r.stdout);1140        return error.ProcessFailed;1141    }1142    return r.stdout;1143}11441145// --- Boot ---11461147pub fn bootEntries(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.BootEntry {1148    const r = try capture(gpa, io, machine, &.{ "bootctl", "list" });1149    defer gpa.free(r.stderr);1150    defer gpa.free(r.stdout);1151    if (r.exit_code != 0) return error.ProcessFailed;1152    return parseBootEntries(gpa, r.stdout);1153}11541155fn parseBootEntries(gpa: std.mem.Allocator, output_str: []const u8) ![]types.BootEntry {1156    var entries: std.ArrayList(types.BootEntry) = .empty;1157    var lines = std.mem.splitScalar(u8, output_str, '\n');1158    while (lines.next()) |line| {1159        const trimmed = std.mem.trim(u8, line, " \t\r");1160        if (std.mem.startsWith(u8, trimmed, "title:")) {1161            const title = std.mem.trim(u8, trimmed[6..], " \t");1162            const current = std.mem.indexOf(u8, title, "(current)") != null;1163            try entries.append(gpa, .{1164                .title = try gpa.dupe(u8, title),1165                .current = current,1166            });1167        }1168    }1169    return entries.toOwnedSlice(gpa);1170}11711172// --- Pkg info ---11731174fn pkgInstallable(gpa: std.mem.Allocator, pkg: []const u8) ![]u8 {1175    return std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});1176}11771178fn resolvePkgStorePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, installable: []const u8) ![]u8 {1179    const r = try capture(gpa, io, machine, &.{ "nix", "build", "--no-link", "--print-out-paths", installable });1180    defer gpa.free(r.stderr);1181    defer gpa.free(r.stdout);1182    if (r.exit_code != 0) return error.PackageNotFound;11831184    var lines = std.mem.tokenizeAny(u8, r.stdout, "\r\n");1185    const first_path = lines.next() orelse return error.PackageNotFound;1186    const store_path = std.mem.trim(u8, first_path, " \t");1187    if (store_path.len == 0) return error.PackageNotFound;1188    return gpa.dupe(u8, store_path);1189}11901191pub fn pkgWhy(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1192    const installable = try pkgInstallable(gpa, pkg);1193    defer gpa.free(installable);1194    const store_path = try resolvePkgStorePath(gpa, io, machine, installable);1195    defer gpa.free(store_path);1196    return stream(io, machine, gpa, &.{ "nix", "why-depends", "/run/current-system", store_path });1197}11981199pub fn pkgDeps(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1200    const installable = try pkgInstallable(gpa, pkg);1201    defer gpa.free(installable);1202    const store_path = try resolvePkgStorePath(gpa, io, machine, installable);1203    defer gpa.free(store_path);1204    return stream(io, machine, gpa, &.{ "nix-store", "--query", "--requisites", store_path });1205}12061207pub fn pkgSize(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, pkg: []const u8) ![]u8 {1208    const installable = try pkgInstallable(gpa, pkg);1209    defer gpa.free(installable);1210    const r = try capture(gpa, io, machine, &.{ "nix", "path-info", "-s", "--json", installable });1211    defer gpa.free(r.stderr);1212    defer gpa.free(r.stdout);1213    if (r.exit_code != 0) return error.ProcessFailed;12141215    const nar_size = try pathInfoNarSize(gpa, r.stdout);1216    return humanPkgSize(gpa, nar_size);1217}12181219pub fn pkgClosure(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1220    const installable = try pkgInstallable(gpa, pkg);1221    defer gpa.free(installable);1222    const store_path = try resolvePkgStorePath(gpa, io, machine, installable);1223    defer gpa.free(store_path);1224    return stream(io, machine, gpa, &.{ "nix", "path-info", "-rS", store_path });1225}12261227fn pathInfoNarSize(gpa: std.mem.Allocator, json_str: []const u8) !u64 {1228    var parsed = std.json.parseFromSlice(std.json.Value, gpa, json_str, .{}) catch return error.ProcessFailed;1229    defer parsed.deinit();1230    switch (parsed.value) {1231        .object => |obj| {1232            var it = obj.iterator();1233            while (it.next()) |entry| {1234                if (entry.value_ptr.* == .object) {1235                    if (entry.value_ptr.object.get("narSize")) |v| {1236                        if (v == .integer and v.integer >= 0) return @intCast(v.integer);1237                    }1238                }1239            }1240        },1241        .array => |arr| {1242            for (arr.items) |item| {1243                if (item == .object) {1244                    if (item.object.get("narSize")) |v| {1245                        if (v == .integer and v.integer >= 0) return @intCast(v.integer);1246                    }1247                }1248            }1249        },1250        else => {},1251    }1252    return error.ProcessFailed;1253}12541255fn humanPkgSize(gpa: std.mem.Allocator, bytes: u64) ![]u8 {1256    const units = [_][]const u8{ "B", "KiB", "MiB", "GiB", "TiB" };1257    var val: f64 = @floatFromInt(bytes);1258    var unit: usize = 0;1259    while (val >= 1024.0 and unit + 1 < units.len) : (unit += 1) val /= 1024.0;1260    if (unit == 0) return std.fmt.allocPrint(gpa, "{d} {s}", .{ bytes, units[0] });1261    return std.fmt.allocPrint(gpa, "{d:.1} {s}", .{ val, units[unit] });1262}12631264test "pathInfoNarSize parses object and array shapes" {1265    try std.testing.expectEqual(@as(u64, 1064629862), try pathInfoNarSize(std.testing.allocator,1266        \\{"/nix/store/abc-ffmpeg":{"narSize":1064629862}}1267    ));1268    try std.testing.expectEqual(@as(u64, 2048), try pathInfoNarSize(std.testing.allocator,1269        \\[{"path":"/nix/store/abc-pkg","narSize":2048}]1270    ));1271}12721273// --- Hash / Fetch ---12741275pub fn nixHash(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, path: []const u8) ![]u8 {1276    const r = try capture(gpa, io, machine, &.{ "nix", "hash", "path", path });1277    defer gpa.free(r.stderr);1278    if (r.exit_code != 0) {1279        gpa.free(r.stdout);1280        return error.ProcessFailed;1281    }1282    return r.stdout;1283}12841285pub fn nixFetch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, url: []const u8) ![]u8 {1286    const r = try capture(gpa, io, machine, &.{ "nix-prefetch-url", url });1287    defer gpa.free(r.stderr);1288    if (r.exit_code != 0) {1289        gpa.free(r.stdout);1290        return error.ProcessFailed;1291    }1292    return r.stdout;1293}12941295// --- Pin ---12961297pub fn editFlakeLock(_: std.mem.Allocator, _: []const u8, _: []const u8) !void {1298    // Stub: full implementation would parse and edit flake.lock JSON1299    // The pin/unpin flow works via nix flake update which regenerates flake.lock1300}13011302pub fn openEditor(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8, line: ?u32) !u8 {1303    if (line) |l| {1304        const line_arg = try std.fmt.allocPrint(gpa, "+{d}", .{l});1305        defer gpa.free(line_arg);1306        return stream(io, &types.Machine{}, gpa, &.{ editor, path, line_arg });1307    }1308    return stream(io, &types.Machine{}, gpa, &.{ editor, path });1309}13101311// Open a config directory as root with `sudo -E <editor> <path>` — `-E`1312// preserves the user's environment (PATH, TERM, EDITOR config) so the editor1313// behaves the same as it does unprivileged. Used by `nina edit --dir`.1314pub fn openEditorSudo(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8) !u8 {1315    return stream(io, &types.Machine{}, gpa, &.{ "sudo", "-E", editor, path });1316}13171318pub fn diffClosures(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a: u32, b: u32) !u8 {1319    const a_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{a});1320    defer gpa.free(a_str);1321    const b_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{b});1322    defer gpa.free(b_str);1323    // On a tty, the child's own color is fine — stream it directly.1324    if (output.colorEnabled()) {1325        return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_str, b_str });1326    }1327    // Piped/redirected: nix store diff-closures colorizes regardless of NO_COLOR,1328    // so we can't ask it to stop — capture its output and strip the ANSI ourselves.1329    const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_str, b_str });1330    defer gpa.free(r.stdout);1331    defer gpa.free(r.stderr);1332    const cleaned = try stripAnsi(gpa, r.stdout);1333    defer gpa.free(cleaned);1334    output.raw(cleaned);1335    return r.exit_code;1336}13371338// Strip CSI escape sequences (ESC '[' ... final-byte) from text. Used to clean a1339// child process's color when it writes ANSI unconditionally.1340fn stripAnsi(gpa: std.mem.Allocator, input: []const u8) ![]u8 {1341    var out: std.ArrayList(u8) = .empty;1342    errdefer out.deinit(gpa);1343    var i: usize = 0;1344    while (i < input.len) {1345        if (input[i] == 0x1b and i + 1 < input.len and input[i + 1] == '[') {1346            i += 2;1347            while (i < input.len and !(input[i] >= 0x40 and input[i] <= 0x7e)) : (i += 1) {}1348            if (i < input.len) i += 1; // consume the final byte1349            continue;1350        }1351        try out.append(gpa, input[i]);1352        i += 1;1353    }1354    return out.toOwnedSlice(gpa);1355}13561357test "stripAnsi removes CSI color sequences" {1358    const cleaned = try stripAnsi(std.testing.allocator, "kepr: \x1b[31;1m13.1 KiB\x1b[0m");1359    defer std.testing.allocator.free(cleaned);1360    try std.testing.expectEqualStrings("kepr: 13.1 KiB", cleaned);1361}13621363// --- Doctor checks ---13641365pub fn runDoctorChecks(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.DoctorCheck {1366    var checks: std.ArrayList(types.DoctorCheck) = .empty;13671368    // Check nix daemon1369    {1370        const r = try capture(gpa, io, machine, &.{ "systemctl", "is-active", "nix-daemon" });1371        defer gpa.free(r.stdout);1372        defer gpa.free(r.stderr);1373        const active = std.mem.indexOf(u8, r.stdout, "active") != null;1374        try checks.append(gpa, .{ .name = "nix daemon", .status = if (active) .ok else .fail });1375    }13761377    // Check config syntax. Flake-aware like apply/upgrade: on a flake system a1378    // plain `nixos-rebuild dry-build` evaluates <nixpkgs/nixos> + <nixos-config>1379    // (channel style) and fails, so pass --flake when the config dir has one.1380    {1381        const argv: []const []const u8 = if (useFlakeFlag(gpa, io, machine))1382            &.{ "sudo", "nixos-rebuild", "dry-build", "--flake", machine.config_path }1383        else1384            &.{ "sudo", "nixos-rebuild", "dry-build" };1385        const r = try capture(gpa, io, machine, argv);1386        defer gpa.free(r.stdout);1387        defer gpa.free(r.stderr);1388        try checks.append(gpa, .{ .name = "config syntax", .status = if (r.exit_code == 0) .ok else .fail });1389    }13901391    // Check channel1392    {1393        const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });1394        defer gpa.free(r.stdout);1395        defer gpa.free(r.stderr);1396        const has_channel = r.exit_code == 0 and r.stdout.len > 0;1397        try checks.append(gpa, .{ .name = "channel", .status = if (has_channel) .ok else .warn });1398    }13991400    return checks.toOwnedSlice(gpa);1401}14021403// --- Home Manager ---1404//1405// Home Manager has three usage modes. nina detects which one is in play before1406// any `home` command so it can either drive the standalone CLI or redirect the1407// user to `nina apply` (when HM is a NixOS/flake module activated by rebuild).14081409pub const HomeManagerMode = enum {1410    // home-manager binary on PATH — manages the user env on its own.1411    standalone,1412    // No binary, but a home.nix exists — HM is a NixOS/flake module rebuilt by1413    // nixos-rebuild. `nina home apply` redirects to `nina apply`.1414    module,1415    none,1416};14171418fn homeConfigDir(gpa: std.mem.Allocator, environ: *const std.process.Environ.Map) ?[]const u8 {1419    const home = environ.get("HOME") orelse return null;1420    return std.fmt.allocPrint(gpa, "{s}/.config/home-manager", .{home}) catch null;1421}14221423// Path to the standalone home.nix. Caller frees.1424pub fn homeNixPath(gpa: std.mem.Allocator, environ: *const std.process.Environ.Map) ?[]const u8 {1425    const dir = homeConfigDir(gpa, environ) orelse return null;1426    defer gpa.free(dir);1427    return std.fmt.allocPrint(gpa, "{s}/home.nix", .{dir}) catch null;1428}14291430pub fn pathExists(io: std.Io, path: []const u8) bool {1431    const f = std.Io.Dir.openFile(.cwd(), io, path, .{}) catch return false;1432    f.close(io);1433    return true;1434}14351436// `command -v <name>` — true if the binary resolves on PATH. Silent (captured),1437// unlike streamLocal which would inherit stdio.1438fn commandExists(gpa: std.mem.Allocator, io: std.Io, name: []const u8) bool {1439    var buf: [256]u8 = undefined;1440    const cmd = std.fmt.bufPrint(&buf, "command -v {s} >/dev/null 2>&1", .{name}) catch return false;1441    const r = std.process.run(gpa, io, .{ .argv = &.{ "sh", "-c", cmd } }) catch return false;1442    defer gpa.free(r.stdout);1443    defer gpa.free(r.stderr);1444    return switch (r.term) {1445        .exited => |code| code == 0,1446        else => false,1447    };1448}14491450pub fn detectHomeManager(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) HomeManagerMode {1451    if (commandExists(gpa, io, "home-manager")) return .standalone;1452    if (homeNixPath(gpa, environ)) |p| {1453        defer gpa.free(p);1454        if (pathExists(io, p)) return .module;1455    }1456    return .none;1457}14581459// The home-manager config dir when it holds a flake.nix (a flake-based home1460// config that `home-manager switch --flake` drives). null for a channel-based1461// config, which uses a plain `home-manager switch`. Caller frees.1462pub fn homeFlakeDir(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ?[]const u8 {1463    const dir = homeConfigDir(gpa, environ) orelse return null;1464    const flake = std.fmt.allocPrint(gpa, "{s}/flake.nix", .{dir}) catch {1465        gpa.free(dir);1466        return null;1467    };1468    defer gpa.free(flake);1469    if (!pathExists(io, flake)) {1470        gpa.free(dir);1471        return null;1472    }1473    return dir;1474}14751476// Platform-specific home-manager attribute "<user>-<arch>-<os>" (e.g.1477// murazaki-x86_64-linux) — the homeConfigurations key many flakes derive from1478// ${USER}-${system}. arch/os come from uname on the local host (home commands1479// are local-only). Caller frees.1480pub fn homeManagerAttr(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, environ: *const std.process.Environ.Map) ![]const u8 {1481    const user = environ.get("USER") orelse "user";14821483    const arch_r = try capture(gpa, io, machine, &.{ "uname", "-m" });1484    defer gpa.free(arch_r.stdout);1485    defer gpa.free(arch_r.stderr);1486    if (arch_r.exit_code != 0) return error.ProcessFailed;1487    const arch = std.mem.trim(u8, arch_r.stdout, " \t\r\n");14881489    const os_r = try capture(gpa, io, machine, &.{ "uname", "-s" });1490    defer gpa.free(os_r.stdout);1491    defer gpa.free(os_r.stderr);1492    if (os_r.exit_code != 0) return error.ProcessFailed;1493    const os = try gpa.dupe(u8, std.mem.trim(u8, os_r.stdout, " \t\r\n"));1494    defer gpa.free(os);1495    for (os) |*ch| ch.* = std.ascii.toLower(ch.*);14961497    if (arch.len == 0 or os.len == 0) return error.ProcessFailed;1498    return std.fmt.allocPrint(gpa, "{s}-{s}-{s}", .{ user, arch, os });1499}15001501// Map a nixos-version string to the matching home-manager branch: an unstable1502// channel ("…pre…"/"unstable") → master; a stable release like1503// "25.05.20250115.abcdef (Warbler)" → release-25.05. Anything unparseable1504// falls back to master. Caller frees.1505fn homeBranchFromVersion(gpa: std.mem.Allocator, version_raw: []const u8) ![]const u8 {1506    const v = std.mem.trim(u8, version_raw, " \t\r\n");1507    if (std.mem.indexOf(u8, v, "pre") != null or1508        std.mem.indexOf(u8, v, "unstable") != null)1509        return gpa.dupe(u8, "master");15101511    const head = v[0 .. std.mem.indexOfScalar(u8, v, ' ') orelse v.len];1512    var it = std.mem.splitScalar(u8, head, '.');1513    const major = it.next() orelse "";1514    const minor = it.next() orelse "";1515    if (allDigits(major) and allDigits(minor))1516        return std.fmt.allocPrint(gpa, "release-{s}.{s}", .{ major, minor });15171518    return gpa.dupe(u8, "master");1519}15201521fn allDigits(s: []const u8) bool {1522    if (s.len == 0) return false;1523    for (s) |ch| if (!std.ascii.isDigit(ch)) return false;1524    return true;1525}15261527test "homeBranchFromVersion maps channels to HM branches" {1528    const a = std.testing.allocator;1529    const cases = [_]struct { in: []const u8, want: []const u8 }{1530        .{ .in = "25.05.20250115.abcdef (Warbler)", .want = "release-25.05" },1531        .{ .in = "24.11.20241201.deadbee (Vicuna)", .want = "release-24.11" },1532        .{ .in = "25.11pre-git", .want = "master" },1533        .{ .in = "25.05pre789012.abcdef (Warbler)", .want = "master" },1534        .{ .in = "nixos-unstable", .want = "master" },1535        .{ .in = "garbage", .want = "master" },1536    };1537    for (cases) |c| {1538        const got = try homeBranchFromVersion(a, c.in);1539        defer a.free(got);1540        try std.testing.expectEqualStrings(c.want, got);1541    }1542}15431544// The home-manager branch matching the running nixpkgs. Falls back to master1545// when nixos-version is unavailable (non-NixOS host). Caller frees.1546fn detectHomeManagerBranch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]const u8 {1547    const r = capture(gpa, io, machine, &.{"nixos-version"}) catch1548        return gpa.dupe(u8, "master");1549    defer gpa.free(r.stdout);1550    defer gpa.free(r.stderr);1551    if (r.exit_code != 0) return gpa.dupe(u8, "master");1552    return homeBranchFromVersion(gpa, r.stdout);1553}15541555// `nix run home-manager/<branch> -- init [--switch] [dir]` — generates1556// flake.nix + home.nix (in dir, or ~/.config/home-manager by default),1557// activating immediately when switch_on_init is set.1558pub fn homeManagerInit(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, switch_on_init: bool, dir: ?[]const u8) !u8 {1559    const branch = try detectHomeManagerBranch(gpa, io, machine);1560    defer gpa.free(branch);1561    const flake_ref = try std.fmt.allocPrint(gpa, "home-manager/{s}", .{branch});1562    defer gpa.free(flake_ref);15631564    var argv: std.ArrayList([]const u8) = .empty;1565    defer argv.deinit(gpa);1566    try argv.appendSlice(gpa, &.{ "nix", "run", flake_ref, "--", "init" });1567    if (switch_on_init) try argv.append(gpa, "--switch");1568    if (dir) |d| try argv.append(gpa, d);15691570    return stream(io, machine, gpa, argv.items);1571}15721573pub fn homeManagerSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1574    output.flush();1575    const r = try capture(gpa, io, machine, &.{ "home-manager", "switch" });1576    defer gpa.free(r.stdout);1577    defer gpa.free(r.stderr);1578    errors.setBuildStderr(r.stderr);1579    return r.exit_code;1580}15811582// Outcome of a flake-based switch, so the caller can fall back to a less1583// specific attribute on a missing-attribute evaluation error — but never on a1584// genuine build failure.1585pub const SwitchOutcome = enum { ok, attr_missing, failed };15861587pub fn homeManagerSwitchFlake(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, flake_ref: []const u8) !SwitchOutcome {1588    output.flush();1589    const r = try capture(gpa, io, machine, &.{ "home-manager", "switch", "--flake", flake_ref });1590    defer gpa.free(r.stdout);1591    defer gpa.free(r.stderr);1592    if (r.exit_code == 0) return .ok;1593    // A flake that doesn't define this homeConfiguration fails during evaluation1594    // with "does not provide attribute" — surface that so the caller can retry a1595    // different attr rather than treating it as a build failure.1596    if (std.mem.indexOf(u8, r.stderr, "does not provide attribute") != null)1597        return .attr_missing;1598    errors.setBuildStderr(r.stderr);1599    return .failed;1600}16011602// home-manager has no system-profile rollback; it re-activates the previous1603// generation via `switch --rollback`.1604pub fn homeManagerRollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1605    output.flush();1606    const r = try capture(gpa, io, machine, &.{ "home-manager", "switch", "--rollback" });1607    defer gpa.free(r.stdout);1608    defer gpa.free(r.stderr);1609    errors.setBuildStderr(r.stderr);1610    return r.exit_code;1611}16121613// Build (and validate) the home config without activating it — used by `home1614// check` and `home apply --dry`. `home-manager build` drops a ./result symlink1615// in the cwd, so run it in a throwaway temp dir to avoid littering the directory1616// nina was invoked from.1617pub fn homeManagerBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1618    output.flush();1619    const r = try capture(gpa, io, machine, &.{ "sh", "-c", "d=$(mktemp -d) && cd \"$d\" && home-manager build" });1620    defer gpa.free(r.stdout);1621    defer gpa.free(r.stderr);1622    errors.setBuildStderr(r.stderr);1623    return r.exit_code;1624}16251626pub fn homeGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1627    const r = try capture(gpa, io, machine, &.{ "home-manager", "generations" });1628    defer gpa.free(r.stderr);1629    if (r.exit_code != 0) {1630        gpa.free(r.stdout);1631        return error.ProcessFailed;1632    }1633    return r.stdout;1634}16351636// Store paths referenced by a home generation — used to list managed packages.1637pub fn homeGenerationReferences(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, gen_path: []const u8) ![]u8 {1638    const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", gen_path });1639    defer gpa.free(r.stderr);1640    if (r.exit_code != 0) {1641        gpa.free(r.stdout);1642        return error.ProcessFailed;1643    }1644    return r.stdout;1645}16461647// diff-closures between two arbitrary store paths (home generations), mirroring1648// diffClosures' tty/piped color handling.1649pub fn diffClosuresPaths(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a_path: []const u8, b_path: []const u8) !u8 {1650    if (output.colorEnabled()) {1651        return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_path, b_path });1652    }1653    const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_path, b_path });1654    defer gpa.free(r.stdout);1655    defer gpa.free(r.stderr);1656    const cleaned = try stripAnsi(gpa, r.stdout);1657    defer gpa.free(cleaned);1658    output.raw(cleaned);1659    return r.exit_code;1660}16611662// --- Log ---16631664pub fn readNinaLog(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, last: u32) ![]u8 {1665    const home = environ.get("HOME") orelse return error.FileNotFound;1666    const path = try std.fmt.allocPrint(gpa, "{s}/.nina.log", .{home});1667    defer gpa.free(path);1668    const content = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return error.FileNotFound;1669    if (last == 0) return content;16701671    // Collect non-empty lines, then keep only the final `last`. Slices point into1672    // `content`, so copy them out before freeing it.1673    var lines: std.ArrayList([]const u8) = .empty;1674    defer lines.deinit(gpa);1675    var it = std.mem.splitScalar(u8, content, '\n');1676    while (it.next()) |line| {1677        if (std.mem.trim(u8, line, " \t\r").len == 0) continue;1678        try lines.append(gpa, line);1679    }1680    if (lines.items.len <= last) return content;16811682    var out: std.ArrayList(u8) = .empty;1683    errdefer out.deinit(gpa);1684    for (lines.items[lines.items.len - last ..]) |line| {1685        try out.appendSlice(gpa, line);1686        try out.append(gpa, '\n');1687    }1688    gpa.free(content);1689    return out.toOwnedSlice(gpa);1690}16911692// nina is a one-shot process, so "did the last apply fail this session?" can't1693// live in memory — it's persisted as a ~/.nina-apply-failed flag, mirroring the1694// other ~/.nina-* state files. This lets a later successful apply earn the1695// excited kaomoji. mark sets it; take reads-and-clears so it fires exactly once.1696pub fn markApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) void {1697    const home = environ.get("HOME") orelse return;1698    var buf: [512]u8 = undefined;1699    const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return;1700    const file = std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return;1701    file.close(io);1702}17031704pub fn takeApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) bool {1705    const home = environ.get("HOME") orelse return false;1706    var buf: [512]u8 = undefined;1707    const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return false;1708    if (std.Io.Dir.openFile(.cwd(), io, path, .{})) |f| {1709        f.close(io);1710        std.Io.Dir.deleteFile(.cwd(), io, path) catch {};1711        return true;1712    } else |_| {1713        return false;1714    }1715}17161717pub fn appendNinaLog(io: std.Io, environ: *const std.process.Environ.Map, entry: []const u8) void {1718    const home = environ.get("HOME") orelse return;1719    var path_buf: [512]u8 = undefined;1720    const path = std.fmt.bufPrint(&path_buf, "{s}/.nina.log", .{home}) catch return;1721    const file = std.Io.Dir.openFile(.cwd(), io, path, .{ .mode = .read_write }) catch1722        (std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return);1723    defer file.close(io);1724    const size = file.length(io) catch 0;1725    file.writePositionalAll(io, entry, size) catch {};1726}17271728// --- Update helpers ---17291730// Fetch a URL with curl and return the response body. Caller must free.1731// error.NetworkError = DNS/connect failure; error.HttpError = non-2xx response.1732pub fn fetchUrl(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1733    const argv = [_][]const u8{1734        "curl", "-s", "-L", "-w", "\nHTTP_STATUS:%{http_code}", "-m", "30", "--", url,1735    };1736    const result = std.process.run(gpa, io, .{ .argv = &argv }) catch return error.NetworkError;1737    defer gpa.free(result.stderr);17381739    const marker = "\nHTTP_STATUS:";1740    const mark_idx = std.mem.lastIndexOf(u8, result.stdout, marker) orelse {1741        gpa.free(result.stdout);1742        return error.NetworkError;1743    };1744    const status_str = std.mem.trim(u8, result.stdout[mark_idx + marker.len ..], " \r\n");1745    const status = std.fmt.parseInt(u16, status_str, 10) catch {1746        gpa.free(result.stdout);1747        return error.NetworkError;1748    };1749    if (status == 0) { gpa.free(result.stdout); return error.NetworkError; }1750    if (status < 200 or status >= 300) { gpa.free(result.stdout); return error.HttpError; }1751    const body = gpa.dupe(u8, result.stdout[0..mark_idx]) catch |e| {1752        gpa.free(result.stdout);1753        return e;1754    };1755    gpa.free(result.stdout);1756    return body;1757}17581759// Download a URL to a temp file. Returns the temp path (caller must gpa.free).1760// The file is written to /tmp/nina-update-<pid> and left for the caller to use.1761pub fn downloadToTemp(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1762    const tmp_path = try gpa.dupe(u8, "/tmp/nina-update.bin");1763    errdefer gpa.free(tmp_path);17641765    var child = std.process.spawn(io, .{1766        .argv = &.{ "curl", "-fsSL", "-m", "300", "-o", tmp_path, "--", url },1767        .stdin = .close,1768        .stdout = .close,1769        .stderr = .inherit,1770    }) catch return error.NetworkError;1771    const term = child.wait(io) catch return error.NetworkError;1772    switch (term) {1773        .exited => |c| if (c != 0) return error.NetworkError,1774        else => return error.NetworkError,1775    }1776    return tmp_path;1777}17781779// Get the current executable path into buf. Returns slice of buf.1780pub fn selfExePath(io: std.Io, buf: *[std.Io.Dir.max_path_bytes]u8) ![]const u8 {1781    const len = try std.process.executablePath(io, buf);1782    return buf[0..len];1783}17841785// Verify blake3 of tmp_path against expected_hex (raw hex, no prefix), then1786// atomically install the binary to install_path. Errors: ChecksumMismatch,1787// AccessDenied (with error_info set), or underlying I/O errors.1788pub fn verifyAndInstall(gpa: std.mem.Allocator, io: std.Io, tmp_path: []const u8, expected_hex: []const u8, install_path: []const u8) !void {1789    const bytes = std.Io.Dir.readFileAlloc(.cwd(), io, tmp_path, gpa, .unlimited) catch {1790        errors.error_info.setMessage("downloaded file not found: {s}", .{tmp_path});1791        return error.FileNotFound;1792    };1793    defer gpa.free(bytes);17941795    var hasher = std.crypto.hash.Blake3.init(.{});1796    hasher.update(bytes);1797    var raw: [32]u8 = undefined;1798    hasher.final(&raw);1799    const hex = std.fmt.bytesToHex(raw, .lower);1800    if (!std.mem.eql(u8, &hex, expected_hex)) return error.ChecksumMismatch;18011802    var inst_tmp_buf: [std.Io.Dir.max_path_bytes + 8]u8 = undefined;1803    const inst_tmp = std.fmt.bufPrint(&inst_tmp_buf, "{s}.new", .{install_path}) catch1804        return error.NameTooLong;18051806    {1807        const f = std.Io.Dir.createFileAbsolute(io, inst_tmp, .{}) catch {1808            errors.error_info.setMessage("cannot write to {s}", .{install_path});1809            errors.error_info.setSuggestion("try: sudo nina update", .{});1810            return error.AccessDenied;1811        };1812        defer f.close(io);1813        f.writePositionalAll(io, bytes, 0) catch {1814            errors.error_info.setMessage("cannot write to {s}", .{install_path});1815            return error.AccessDenied;1816        };1817        try f.setPermissions(io, .fromMode(0o755));1818    }1819    errdefer std.Io.Dir.deleteFileAbsolute(io, inst_tmp) catch {};18201821    if (comptime builtin.os.tag == .macos) {1822        _ = captureLocal(gpa, io, &.{ "codesign", "-f", "-s", "-", inst_tmp }) catch {};1823    }18241825    std.Io.Dir.renameAbsolute(inst_tmp, install_path, io) catch |e| switch (e) {1826        error.AccessDenied => {1827            errors.error_info.setMessage("cannot replace {s}", .{install_path});1828            errors.error_info.setSuggestion("try: sudo nina update", .{});1829            return error.AccessDenied;1830        },1831        else => return e,1832    };1833}18341835// --- Nix feature setup ---18361837pub const NixFeatureStatus = struct {1838    nix_command: bool = false,1839    flakes: bool = false,18401841    pub fn allEnabled(self: NixFeatureStatus) bool {1842        return self.nix_command and self.flakes;1843    }1844};18451846fn scanConfFeatures(conf: []const u8, status: *NixFeatureStatus) void {1847    var lines = std.mem.splitScalar(u8, conf, '\n');1848    while (lines.next()) |line| {1849        const trimmed = std.mem.trim(u8, line, " \t");1850        if (!std.mem.startsWith(u8, trimmed, "experimental-features")) continue;1851        if (std.mem.indexOf(u8, trimmed, "nix-command") != null) status.nix_command = true;1852        if (std.mem.indexOf(u8, trimmed, "flakes") != null) status.flakes = true;1853    }1854}18551856pub fn checkNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) NixFeatureStatus {1857    var status = NixFeatureStatus{};18581859    if (std.Io.Dir.readFileAlloc(.cwd(), io, "/etc/nix/nix.conf", gpa, .unlimited) catch null) |conf| {1860        defer gpa.free(conf);1861        scanConfFeatures(conf, &status);1862    }18631864    if (environ.get("HOME")) |home| {1865        var buf: [512]u8 = undefined;1866        const path = std.fmt.bufPrint(&buf, "{s}/.config/nix/nix.conf", .{home}) catch return status;1867        if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |conf| {1868            defer gpa.free(conf);1869            scanConfFeatures(conf, &status);1870        }1871    }18721873    return status;1874}18751876pub fn isNixOS(io: std.Io) bool {1877    const file = std.Io.Dir.openFile(.cwd(), io, "/etc/NIXOS", .{}) catch return false;1878    file.close(io);1879    return true;1880}18811882// Appends `experimental-features = nix-command flakes` to ~/.config/nix/nix.conf.1883// Returns the path written (caller must free).1884pub fn enableNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ![]const u8 {1885    const home = environ.get("HOME") orelse {1886        errors.error_info.setMessage("HOME not set", .{});1887        return error.ConfigNotFound;1888    };18891890    const dir_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix", .{home});1891    defer gpa.free(dir_path);1892    const file_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix/nix.conf", .{home});1893    errdefer gpa.free(file_path);18941895    _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir_path }) catch {};18961897    const line = "experimental-features = nix-command flakes\n";1898    const file = std.Io.Dir.openFile(.cwd(), io, file_path, .{ .mode = .read_write }) catch1899        (std.Io.Dir.createFile(.cwd(), io, file_path, .{}) catch {1900        errors.error_info.setMessage("could not write {s}", .{file_path});1901        return error.FileNotFound;1902    });1903    defer file.close(io);19041905    const size = file.length(io) catch 0;1906    file.writePositionalAll(io, line, size) catch {1907        errors.error_info.setMessage("could not write {s}", .{file_path});1908        return error.FileNotFound;1909    };19101911    return file_path;1912}19131914// --- NixOS: declarative experimental-features ---1915//1916// On NixOS the permanent, declarative home for these flags is configuration.nix,1917// not ~/.config/nix/nix.conf. nina offers to add this one line and then leaves1918// the `nixos-rebuild switch` to the user.19191920pub const NIXOS_FEATURES_LINE =1921    "nix.settings.experimental-features = [ \"nix-command\" \"flakes\" ];";19221923// Best-effort, non-sudo check (configuration.nix is 0644 by default). Returns1924// false on any read error so the caller still offers to add the line.1925pub fn nixosConfigEnablesFeatures(gpa: std.mem.Allocator, io: std.Io, path: []const u8) bool {1926    const conf = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return false;1927    defer gpa.free(conf);1928    return std.mem.indexOf(u8, conf, "experimental-features") != null and1929        std.mem.indexOf(u8, conf, "nix-command") != null and1930        std.mem.indexOf(u8, conf, "flakes") != null;1931}19321933fn readMaybeSudo(gpa: std.mem.Allocator, io: std.Io, path: []const u8) ![]u8 {1934    if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |data| return data;1935    return captureLocal(gpa, io, &.{ "sudo", "cat", path });1936}19371938// Insert NIXOS_FEATURES_LINE just before the final `}` of configuration.nix1939// (i.e. inside the top-level attribute set) and write it back via a single1940// `sudo cp`, which prompts for the password on the terminal. Returns an error1941// for the caller to fall back to printed manual instructions.1942pub fn appendFeaturesToNixosConfig(1943    gpa: std.mem.Allocator,1944    io: std.Io,1945    environ: *const std.process.Environ.Map,1946    path: []const u8,1947) !void {1948    const conf = readMaybeSudo(gpa, io, path) catch {1949        errors.error_info.setMessage("could not read {s}", .{path});1950        return error.ConfigNotFound;1951    };1952    defer gpa.free(conf);19531954    if (std.mem.indexOf(u8, conf, "experimental-features") != null) return; // already declared19551956    const brace = std.mem.lastIndexOfScalar(u8, conf, '}') orelse {1957        errors.error_info.setMessage("no closing brace in {s} — add the line by hand", .{path});1958        return error.MalformedConfig;1959    };19601961    const home = environ.get("HOME") orelse {1962        errors.error_info.setMessage("HOME not set", .{});1963        return error.ConfigNotFound;1964    };1965    const tmp_path = try std.fmt.allocPrint(gpa, "{s}/.nina-configuration.nix", .{home});1966    defer gpa.free(tmp_path);19671968    var buf: std.ArrayList(u8) = .empty;1969    defer buf.deinit(gpa);1970    try buf.appendSlice(gpa, conf[0..brace]);1971    if (brace == 0 or conf[brace - 1] != '\n') try buf.append(gpa, '\n');1972    try buf.appendSlice(gpa, "  # added by nina setup — flakes + the new nix CLI\n");1973    try buf.appendSlice(gpa, "  ");1974    try buf.appendSlice(gpa, NIXOS_FEATURES_LINE);1975    try buf.append(gpa, '\n');1976    try buf.appendSlice(gpa, conf[brace..]);19771978    const tmp = std.Io.Dir.createFile(.cwd(), io, tmp_path, .{}) catch {1979        errors.error_info.setMessage("could not write {s}", .{tmp_path});1980        return error.FileNotFound;1981    };1982    tmp.writePositionalAll(io, buf.items, 0) catch {1983        tmp.close(io);1984        std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1985        errors.error_info.setMessage("could not write {s}", .{tmp_path});1986        return error.FileNotFound;1987    };1988    tmp.close(io);19891990    // Back up the existing config, then replace it — in one sudo call so the1991    // password is asked for at most once. Paths travel as positional args ($0,1992    // $1) to sidestep shell quoting.1993    const code = streamLocal(io, &.{1994        "sudo", "sh", "-c", "cp -- \"$0\" \"$0.nina-bak\" && cp -- \"$1\" \"$0\"", path, tmp_path,1995    }) catch {1996        std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1997        errors.error_info.setMessage("could not write {s}", .{path});1998        return error.ProcessFailed;1999    };2000    std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};2001    if (code != 0) {2002        errors.error_info.setMessage("sudo cp into {s} failed", .{path});2003        return error.ProcessFailed;2004    }2005}