commands.zig

64.5 KB · raw

1// commands.zig — all command handlers2// Orchestrates exec/api/output. Zero direct stdout writes.3const std = @import("std");4const builtin = @import("builtin");5const types = @import("types.zig");6const errors = @import("errors.zig");7const config = @import("config.zig");8const output = @import("output.zig");9const exec = @import("exec.zig");10const api = @import("api.zig");11const search_tui = @import("search.zig");12const version = @import("version.zig");1314const UPDATE_URL = "https://kepr.uk/api/nina/releases/latest";1516pub const Ctx = struct {17    gpa: std.mem.Allocator,18    io: std.Io,19    environ: *const std.process.Environ.Map,20    machine: types.Machine,21    cfg: types.NinaConfig,22    args: []const []const u8,   // positional args after subcommand23    sub: []const u8,            // subcommand (e.g. "list" in "service list")24    dry: bool,25    check: bool,26    no_apply: bool,27    all: bool,28    last: u32,29    json: bool,30    user: bool,            // --user: operate on user (vs system) services31};3233// A system is flake-managed when the config says so OR a flake.nix is present in34// the config dir. Detection means a fresh channel user who points nina at a flake35// dir gets the right behavior without editing config first.36fn flakeSystem(ctx: Ctx) bool {37    return ctx.cfg.flake or exec.configHasFlake(ctx.gpa, ctx.io, &ctx.machine);38}3940pub fn apply(ctx: Ctx) !void {41    if (ctx.dry) {42        output.applyDry(ctx.machine.name);43        const code = try exec.nixosRebuildDryActivate(ctx.io, &ctx.machine, ctx.gpa);44        if (code != 0) return error.BuildFailed;45        output.applyDryDone();46        return;47    }48    if (ctx.check) {49        return check(ctx);50    }5152    output.applyStart(ctx.machine.name);53    const start = std.Io.Clock.awake.now(ctx.io);5455    const code = exec.nixosRebuildSwitch(ctx.io, &ctx.machine, ctx.gpa) catch |e| {56        exec.markApplyFailed(ctx.io, ctx.environ);57        output.applyFailed("");58        return e;59    };6061    if (code != 0) {62        exec.markApplyFailed(ctx.io, ctx.environ);63        output.applyFailed("");64        return error.BuildFailed;65    }6667    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());68    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));69    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;70    const after_failure = exec.takeApplyFailed(ctx.io, ctx.environ);71    output.applyDone(gen, elapsed, after_failure);72    logAction(ctx, "apply", gen);73}7475pub fn check(ctx: Ctx) !void {76    output.checkStart(ctx.machine.name);77    const code = try exec.nixosRebuildBuild(ctx.io, &ctx.machine, ctx.gpa);78    if (code != 0) {79        output.checkFailed("");80        return error.BuildFailed;81    }82    output.checkOk();83}8485pub fn back(ctx: Ctx) !void {86    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);87    defer ctx.gpa.free(gens);8889    var current: u32 = 0;90    for (gens) |g| if (g.current) { current = g.number; };9192    // Newest generation older than current. If there is none, we're already at the93    // oldest — stop cleanly instead of letting rollback fail with 'build failed'.94    var prev: u32 = 0;95    var has_prev = false;96    for (gens) |g| {97        if (g.number < current and (!has_prev or g.number > prev)) {98            prev = g.number;99            has_prev = true;100        }101    }102    if (!has_prev) {103        output.alreadyOldest();104        return;105    }106107    output.backStart(ctx.machine.name, current, prev);108    if (ctx.cfg.confirm and !output.confirm("")) return;109110    const code = try exec.rollback(ctx.io, &ctx.machine, ctx.gpa);111    if (code != 0) return error.BuildFailed;112    output.backDone(prev);113}114115pub fn go(ctx: Ctx) !void {116    if (ctx.args.len == 0) return error.Internal;117    const target = std.fmt.parseInt(u32, ctx.args[0], 10) catch return error.Internal;118    const current = try exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine);119120    output.goStart(ctx.machine.name, current, target);121    if (ctx.cfg.confirm and !output.confirm("")) return;122123    const code = try exec.switchGeneration(ctx.io, &ctx.machine, ctx.gpa, target);124    if (code != 0) return error.ProcessFailed;125    output.generationDone(target);126}127128pub fn history(ctx: Ctx) !void {129    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);130    defer ctx.gpa.free(gens);131    output.historyHeader(ctx.machine.name);132    for (gens) |g| output.historyRow(g);133}134135const gen_help = [_][2][]const u8{136    .{ "list", "list generations" },137    .{ "current", "show current generation" },138    .{ "delete <n>", "delete generation n" },139    .{ "delete old", "delete old generations" },140};141142pub fn genCmd(ctx: Ctx) !void {143    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("gen", &gen_help, null);144    if (std.mem.eql(u8, ctx.sub, "list")) return history(ctx);145    if (std.mem.eql(u8, ctx.sub, "current")) {146        const n = try exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine);147        output.genCurrent(n);148        return;149    }150    if (std.mem.eql(u8, ctx.sub, "delete")) {151        if (ctx.args.len == 0) return error.Internal;152        if (std.mem.eql(u8, ctx.args[0], "old")) {153            if (ctx.cfg.confirm and !output.confirm("")) return;154            _ = try exec.deleteOldGenerations(ctx.io, &ctx.machine, ctx.gpa);155        } else {156            const n = std.fmt.parseInt(u32, ctx.args[0], 10) catch return error.Internal;157            if (ctx.cfg.confirm and !output.confirm("")) return;158            _ = try exec.deleteGeneration(ctx.io, &ctx.machine, ctx.gpa, n);159        }160        output.done();161        return;162    }163    return error.Internal;164}165166pub fn clean(ctx: Ctx) !void {167    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);168    defer ctx.gpa.free(gens);169    const all = ctx.all or std.mem.eql(u8, ctx.sub, "all");170    const total: u32 = @intCast(gens.len);171    // `clean all` keeps only the current generation; otherwise keep the configured172    // count. With nothing older than the keep limit, there's nothing to collect.173    const keep: u32 = if (all) 1 else ctx.cfg.generations;174    if (total <= keep) {175        output.cleanNothing(ctx.machine.name, total);176        return;177    }178    output.cleanStart(ctx.machine.name, keep, total);179    if (ctx.cfg.confirm and !output.confirm("removing — cannot be undone")) return;180    _ = try exec.collectGarbage(ctx.io, &ctx.machine, ctx.gpa, all, ctx.cfg.generations);181    output.cleanDone();182}183184pub fn statusCmd(ctx: Ctx) !void {185    output.statusHeader();186    // --all renders every configured machine; remotes route through the same SSH187    // path as exec.capture. An unreachable machine is shown in red, not fatal.188    if (ctx.all and ctx.cfg.machines.len > 0) {189        for (ctx.cfg.machines) |m| statusRowFor(ctx, &m);190    } else {191        statusRowFor(ctx, &ctx.machine);192    }193    homeStatusLine(ctx);194}195196// When standalone Home Manager is present, show its current generation as a dim197// line indented under the machine rows. Gated on standalone mode (the only mode198// where we can read a generation), so a machine without HM is unaffected.199fn homeStatusLine(ctx: Ctx) void {200    if (exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ) != .standalone) return;201    const out = exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine) catch return;202    defer ctx.gpa.free(out);203    const gens = parseHomeGenerations(ctx.gpa, out) catch return;204    defer freeHomeGens(ctx.gpa, gens);205    if (gens.len == 0) return;206    output.statusHomeRow(gens[0].number, gens[0].date);207}208209fn statusRowFor(ctx: Ctx, machine: *const types.Machine) void {210    // A failure to read the current generation means we couldn't reach or query211    // the machine — mark it unreachable rather than reporting a bogus gen 0.212    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, machine) catch {213        output.statusRow(machine.name, 0, "", "", false);214        return;215    };216    const st = exec.systemStatus(ctx.gpa, ctx.io, machine);217    defer ctx.gpa.free(st.size);218    defer ctx.gpa.free(st.age);219    output.statusRow(machine.name, gen, st.age, st.size, true);220}221222pub fn diff(ctx: Ctx) !void {223    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);224    defer ctx.gpa.free(gens);225    var current: u32 = 0;226    var prev: u32 = 0;227    for (gens) |g| {228        if (g.current) current = g.number;229        if (!g.current and g.number > prev and g.number < current) prev = g.number;230    }231    if (ctx.args.len >= 2) {232        const a = std.fmt.parseInt(u32, ctx.args[0], 10) catch current - 1;233        const b = std.fmt.parseInt(u32, ctx.args[1], 10) catch current;234        output.diffHeader(a, b, ctx.machine.name);235        if (try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, a, b) != 0) return error.ProcessFailed;236    } else {237        output.diffHeader(if (prev > 0) prev else current - 1, current, ctx.machine.name);238        if (try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, if (prev > 0) prev else current - 1, current) != 0) return error.ProcessFailed;239    }240}241242pub fn mood(ctx: Ctx) !void {243    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;244    const st = exec.systemStatus(ctx.gpa, ctx.io, &ctx.machine);245    defer ctx.gpa.free(st.size);246    defer ctx.gpa.free(st.age);247    const state = exec.systemRunningState(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");248    defer ctx.gpa.free(state);249    output.mood(ctx.machine.name, state, gen, st.age, st.size);250}251252pub fn doctor(ctx: Ctx) !void {253    output.doctorHeader(ctx.machine.name);254    const checks = try exec.runDoctorChecks(ctx.gpa, ctx.io, &ctx.machine);255    defer ctx.gpa.free(checks);256    var warnings: u32 = 0;257    var failures: u32 = 0;258    for (checks) |ch| {259        output.doctorRow(ch);260        if (ch.status == .warn) warnings += 1;261        if (ch.status == .fail) failures += 1;262    }263264    // Home Manager row only when present — absent on a machine without HM, so265    // doctor's table is unchanged there.266    const hm_mode = exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ);267    if (hm_mode != .none) {268        const note = homeDoctorNote(ctx, hm_mode);269        defer ctx.gpa.free(note);270        output.doctorRow(.{ .name = "home manager", .status = .ok, .note = note });271    }272273    output.doctorSummary(warnings, failures);274}275276// "standalone  gen 765" / "module" — the note shown in doctor's home manager row.277// Caller owns the returned slice.278fn homeDoctorNote(ctx: Ctx, mode: exec.HomeManagerMode) []const u8 {279    const label = switch (mode) {280        .standalone => "standalone",281        .module => "module",282        .none => "",283    };284    if (mode == .standalone) {285        const gen = homeCurrentGen(ctx);286        if (gen != 0)287            return std.fmt.allocPrint(ctx.gpa, "{s}  gen {d}", .{ label, gen }) catch288                (ctx.gpa.dupe(u8, label) catch "");289    }290    return ctx.gpa.dupe(u8, label) catch "";291}292293// nina update — kepr self-update for the nina binary itself.294pub fn update(ctx: Ctx) !void {295    output.updateSelfStart();296297    if (comptime std.mem.eql(u8, version.PLATFORM, "unsupported")) {298        output.updateSelfNoPlatform(@tagName(builtin.cpu.arch) ++ "-" ++ @tagName(builtin.os.tag));299        return error.Internal;300    }301302    const env_url = ctx.environ.get("NINA_UPDATE_SOURCE");303    const source_url = env_url orelse UPDATE_URL;304305    const body = exec.fetchUrl(ctx.gpa, ctx.io, source_url) catch |e| switch (e) {306        error.NetworkError, error.HttpError => {307            output.updateSelfNetworkError();308            return;309        },310        else => return e,311    };312    defer ctx.gpa.free(body);313314    const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, body, .{}) catch {315        output.printWarning("could not parse release metadata");316        return;317    };318    defer parsed.deinit();319320    const root = parsed.value;321    if (root != .object) { output.printWarning("malformed release metadata"); return; }322323    const remote_ver = blk: {324        const v = root.object.get("version") orelse { output.printWarning("malformed release metadata"); return; };325        break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };326    };327328    if (std.mem.eql(u8, remote_ver, version.VERSION)) {329        output.updateSelfCurrent(version.VERSION);330        return;331    }332333    output.updateSelfAvailable(version.VERSION, remote_ver);334    if (ctx.check) return;335336    var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;337    const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {338        errors.error_info.setMessage("could not determine install path", .{});339        return error.Internal;340    };341342    // When running from the nix store, defer to nix profile upgrade so nix343    // manages the transition (the store is read-only; binary replacement fails).344    // A NixOS system install also resolves into the store but isn't a profile345    // element, so check the profile to avoid a no-op `upgrade` — it updates with346    // the next nixos-rebuild instead.347    if (std.mem.startsWith(u8, install_path, "/nix/store/")) {348        const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);349        defer {350            if (nina_element) |n| ctx.gpa.free(n);351        }352        if (nina_element == null) {353            output.updateSelfNotInProfile();354            return;355        }356        const element = nina_element.?;357        output.updateSelfNixManaged(remote_ver);358        if (ctx.cfg.confirm and !output.confirm("")) return;359        const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "upgrade", element }) catch {360            output.updateSelfNixFailed();361            return;362        };363        if (ec != 0) output.updateSelfNixFailed();364        return;365    }366367    const plat_info = blk: {368        const pv = root.object.get("platforms") orelse break :blk null;369        if (pv != .object) break :blk null;370        break :blk pv.object.get(version.PLATFORM);371    };372    if (plat_info == null) { output.updateSelfNoPlatform(version.PLATFORM); return; }373374    const dl_url = blk: {375        const v = plat_info.?.object.get("url") orelse { output.printWarning("malformed release metadata"); return; };376        break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };377    };378379    const raw_cksum = blk: {380        if (plat_info.?.object.get("blake3")) |v|381            break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };382        if (plat_info.?.object.get("checksum")) |v|383            break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };384        output.printWarning("missing checksum in release metadata");385        return;386    };387    const expected_hex = if (std.mem.startsWith(u8, raw_cksum, "blake3:")) raw_cksum["blake3:".len..] else raw_cksum;388389    if (ctx.cfg.confirm and !output.confirm("")) return;390391    output.updateSelfDownloading(remote_ver, version.PLATFORM);392    const tmp_path = exec.downloadToTemp(ctx.gpa, ctx.io, dl_url) catch {393        output.printWarning("download failed — check your connection and try again");394        return;395    };396    defer ctx.gpa.free(tmp_path);397398    output.updateSelfVerifying();399    exec.verifyAndInstall(ctx.gpa, ctx.io, tmp_path, expected_hex, install_path) catch |e| switch (e) {400        error.ChecksumMismatch => { output.updateSelfChecksumFailed(); return; },401        else => return e,402    };403404    output.updateSelfDone(version.VERSION, remote_ver);405}406407// nina goodbye — clean uninstall. Three install paths:408// - nix profile (binary in nix store with a profile element) → nix profile remove409// - koh build or source build (plain binary on PATH) → delete the file410pub fn goodbye(ctx: Ctx) !void {411    output.goodbyeStart();412413    var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;414    const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {415        errors.error_info.setMessage("could not determine install path", .{});416        return error.Internal;417    };418419    // A binary outside the nix store is a koh build or source build — delete it.420    if (!std.mem.startsWith(u8, install_path, "/nix/store/")) {421        output.goodbyeFile(install_path);422        if (ctx.cfg.confirm and !output.confirm("")) return;423        std.Io.Dir.deleteFileAbsolute(ctx.io, install_path) catch |e| {424            errors.error_info.setMessage("could not remove {s}", .{install_path});425            return e;426        };427        output.goodbyeDone();428        return;429    }430431    // Binary is in the nix store — find and remove the profile element.432    const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);433    defer {434        if (nina_element) |n| ctx.gpa.free(n);435    }436437    if (nina_element == null) {438        errors.error_info.setMessage("nina not found in nix profile — was it installed via 'nix profile add'?", .{});439        return error.Internal;440    }441442    output.goodbyeNix();443    if (ctx.cfg.confirm and !output.confirm("")) return;444    const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "remove", nina_element.? }) catch {445        output.goodbyeFailed("nix profile remove failed");446        return;447    };448    if (ec != 0) {449        output.goodbyeFailed("nix profile remove failed");450        return;451    }452    output.goodbyeDone();453}454455fn channelUpdateCmd(ctx: Ctx) !void {456    output.updateStart(ctx.machine.name);457    _ = try exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa);458    output.updateDone();459}460461pub fn upgrade(ctx: Ctx) !void {462    output.upgradeStart(ctx.machine.name);463    // Flake systems update inputs (flake.lock); channel systems update channels.464    // Running nix-channel --update on a flake system is a no-op at best. The465    // rebuild below is already flake-aware via exec.nixosRebuildSwitch.466    if (flakeSystem(ctx)) {467        output.printSubstep("updating flake inputs", .{});468        _ = exec.flakeUpdateAt(ctx.io, &ctx.machine, ctx.gpa, ctx.machine.config_path) catch {};469    } else {470        output.printSubstep("updating channels", .{});471        _ = exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa) catch {};472    }473    output.printSubstep("rebuilding", .{});474    const start = std.Io.Clock.awake.now(ctx.io);475    const code = try exec.nixosRebuildSwitch(ctx.io, &ctx.machine, ctx.gpa);476    if (code != 0) {477        output.applyFailed("");478        return error.BuildFailed;479    }480    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());481    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));482    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;483    output.applyDone(gen, elapsed, false);484}485486pub fn log(ctx: Ctx) !void {487    output.logHeader(ctx.machine.name);488    const content = exec.readNinaLog(ctx.gpa, ctx.io, ctx.environ, ctx.last) catch {489        // No log yet — that's fine490        return;491    };492    defer ctx.gpa.free(content);493    var lines = std.mem.splitScalar(u8, content, '\n');494    while (lines.next()) |line| {495        const t = std.mem.trim(u8, line, " \t\r");496        if (t.len == 0) continue;497        if (t[0] == '{') {498            renderJsonLogLine(ctx.gpa, t);499        } else {500            // legacy tab-separated format501            var parts = std.mem.tokenizeScalar(u8, t, '\t');502            const date = parts.next() orelse continue;503            const time = parts.next() orelse "";504            const action = parts.next() orelse "";505            const detail = parts.next() orelse "";506            output.logRow(date, time, action, detail);507        }508    }509}510511// The on-disk log is JSON Lines: {"ts","machine","command","outcome","gen_after",...}.512// Render ts -> date/time columns, command -> action, outcome(+gen) -> detail.513fn renderJsonLogLine(gpa: std.mem.Allocator, line: []const u8) void {514    const parsed = std.json.parseFromSlice(std.json.Value, gpa, line, .{}) catch {515        output.logRow(line, "", "", ""); // unparseable — show raw rather than drop516        return;517    };518    defer parsed.deinit();519    if (parsed.value != .object) return;520    const o = parsed.value.object;521522    const ts = jsonStr(o, "ts");523    const date = if (ts.len >= 10) ts[0..10] else ts;524    const time = if (ts.len >= 16) ts[11..16] else "";525    const action = jsonStr(o, "command");526    const outcome = jsonStr(o, "outcome");527528    var buf: [160]u8 = undefined;529    var detail: []const u8 = outcome;530    if (o.get("gen_after")) |g| {531        if (g == .integer) {532            detail = std.fmt.bufPrint(&buf, "{s}   -> gen {d}", .{ outcome, g.integer }) catch outcome;533        }534    }535    output.logRow(date, time, action, detail);536}537538fn jsonStr(o: std.json.ObjectMap, key: []const u8) []const u8 {539    if (o.get(key)) |v| {540        if (v == .string) return v.string;541    }542    return "";543}544545pub fn edit(ctx: Ctx) !void {546    const hardware = ctx.args.len > 0 and std.mem.eql(u8, ctx.args[0], "hardware");547    const filename = if (hardware) "hardware-configuration.nix" else "configuration.nix";548    const path = try std.fmt.allocPrint(ctx.gpa, "{s}/{s}", .{ ctx.machine.config_path, filename });549    defer ctx.gpa.free(path);550    output.editOpen(path, ctx.cfg.editor);551    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);552}553554pub fn fmt(ctx: Ctx) !void {555    const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});556    defer ctx.gpa.free(path);557    if (ctx.check) {558        const code = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, true);559        if (code != 0) output.fmtNeedsFormat() else output.fmtDone();560        return;561    }562    output.fmtStart(path);563    _ = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, false);564    output.fmtDone();565}566567pub fn repl(ctx: Ctx) !void {568    output.replStart();569    _ = try exec.nixRepl(ctx.io, &ctx.machine, ctx.gpa);570}571572pub fn develop(ctx: Ctx) !void {573    if (std.mem.eql(u8, ctx.sub, "show")) {574        _ = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, null);575        return;576    }577    const run_cmd: ?[]const u8 = if (ctx.args.len > 0 and std.mem.eql(u8, ctx.sub, "run"))578        ctx.args[0]579    else580        null;581    output.developStart(&.{});582    _ = try exec.nixDevelopPs1(ctx.io, &ctx.machine, ctx.gpa, run_cmd, ctx.environ);583    output.developDone();584}585586pub fn info(ctx: Ctx) !void {587    output.infoHeader(ctx.machine.name);588    const nixos_ver = exec.systemInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");589    defer ctx.gpa.free(nixos_ver);590    output.infoRow("nixos", std.mem.trim(u8, nixos_ver, " \t\n\r"));591592    const kernel = exec.kernelInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");593    defer ctx.gpa.free(kernel);594    output.infoRow("kernel", std.mem.trim(u8, kernel, " \t\n\r"));595596    const uptime = exec.uptimeInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");597    defer ctx.gpa.free(uptime);598    output.infoRow("uptime", std.mem.trim(u8, uptime, " \t\n\r"));599}600601pub fn boot(ctx: Ctx) !void {602    output.bootHeader(ctx.machine.name);603    const entries = exec.bootEntries(ctx.gpa, ctx.io, &ctx.machine) catch &.{};604    defer ctx.gpa.free(entries);605    for (entries, 0..) |entry, i| output.bootEntry(entry, i);606}607608pub fn searchCmd(ctx: Ctx) !void {609    const query = if (ctx.args.len > 0) ctx.args[0] else "";610    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);611    const selected = try search_tui.run(ctx.gpa, ctx.io, query, .packages);612    if (selected) |npkg| try selectAndInstall(ctx, npkg);613}614615pub fn optionCmd(ctx: Ctx) !void {616    const query = if (ctx.args.len > 0) ctx.args[0] else "";617    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);618    _ = try search_tui.run(ctx.gpa, ctx.io, query, .options);619}620621pub fn install(ctx: Ctx) !void {622    const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;623624    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);625626    // Search for the package to get the attr627    const pkgs = api.searchPackages(ctx.gpa, ctx.io, pkg_name) catch {628        errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});629        errors.error_info.setSuggestion("nina search {s}", .{pkg_name});630        return error.PackageNotFound;631    };632633    if (pkgs.len == 0) {634        // No matches — likely a typo. Suggest the closest real package and offer it.635        if (closestPackage(ctx, pkg_name)) |sugg| {636            output.didYouMean(pkg_name, sugg.pname);637            if (output.confirm("")) try selectAndInstall(ctx, sugg);638            return;639        }640        errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});641        errors.error_info.setSuggestion("nina search {s}", .{pkg_name});642        return error.PackageNotFound;643    }644645    // Prefer an exact name match over the first search result — `install ripgrep`646    // must pick "ripgrep", not the alphabetically-first match like "repgrep".647    var found = pkgs[0];648    for (pkgs) |p| {649        if (std.mem.eql(u8, p.pname, pkg_name)) {650            found = p;651            break;652        }653    }654    try selectAndInstall(ctx, found);655}656657// Find the real package whose name is closest to a not-found query (typo help).658// Typos usually keep the leading characters, so gather candidates with a prefix659// search and rank by edit distance; return the best only if it's typo-close.660fn closestPackage(ctx: Ctx, query: []const u8) ?types.NixPackage {661    if (query.len < 2) return null;662    var candidates = api.searchPackages(ctx.gpa, ctx.io, query[0..@min(query.len, 4)]) catch &.{};663    if (candidates.len == 0 and query.len > 2) {664        candidates = api.searchPackages(ctx.gpa, ctx.io, query[0..2]) catch &.{};665    }666    if (candidates.len == 0) return null;667668    var best: ?types.NixPackage = null;669    var best_dist: usize = std.math.maxInt(usize);670    for (candidates) |p| {671        const d = editDistance(query, p.pname);672        if (d > 0 and d < best_dist) {673            best_dist = d;674            best = p;675        }676    }677    // Only suggest a genuinely close name, scaled to query length.678    const threshold = @max(@as(usize, 2), query.len / 3);679    return if (best_dist <= threshold) best else null;680}681682// Case-insensitive Levenshtein distance. Names longer than the row buffer are683// treated as far away (never suggested).684fn editDistance(a: []const u8, b: []const u8) usize {685    const n = b.len;686    if (a.len == 0) return n;687    if (n == 0) return a.len;688    if (n + 1 > 128) return std.math.maxInt(usize);689    var prev: [128]usize = undefined;690    var curr: [128]usize = undefined;691    var j: usize = 0;692    while (j <= n) : (j += 1) prev[j] = j;693    var i: usize = 1;694    while (i <= a.len) : (i += 1) {695        curr[0] = i;696        j = 1;697        while (j <= n) : (j += 1) {698            const cost: usize = if (std.ascii.toLower(a[i - 1]) == std.ascii.toLower(b[j - 1])) 0 else 1;699            curr[j] = @min(prev[j] + 1, @min(curr[j - 1] + 1, prev[j - 1] + cost));700        }701        @memcpy(prev[0 .. n + 1], curr[0 .. n + 1]);702    }703    return prev[n];704}705706test "editDistance is case-insensitive Levenshtein" {707    try std.testing.expectEqual(@as(usize, 1), editDistance("firefux", "firefox"));708    try std.testing.expectEqual(@as(usize, 0), editDistance("git", "GIT"));709    try std.testing.expectEqual(@as(usize, 2), editDistance("fierfox", "firefox"));710    try std.testing.expectEqual(@as(usize, 7), editDistance("", "firefox"));711}712713// Prompt for the install method (profile / system / try) and dispatch. Shared by714// `nina install <pkg>` and the search widget's Enter-to-select — the letter keys715// are read here, after the search widget's raw mode is gone, so they don't716// collide with typing a query.717fn selectAndInstall(ctx: Ctx, npkg: types.NixPackage) !void {718    output.installSelectPrompt(npkg.pname, npkg.version);719720    var choice_buf: [8]u8 = undefined;721    var choice_len: usize = 0;722    while (choice_len < choice_buf.len) {723        const n = std.posix.read(std.posix.STDIN_FILENO, choice_buf[choice_len .. choice_len + 1]) catch break;724        if (n == 0) break;725        if (choice_buf[choice_len] == '\n') break;726        choice_len += 1;727    }728    const choice = std.mem.trim(u8, choice_buf[0..choice_len], " \t");729730    if (choice.len == 0 or choice[0] == 'i' or choice[0] == 'I') {731        try profileInstallPkg(ctx, npkg);732    } else if (choice[0] == 's' or choice[0] == 'S') {733        try systemInstallPkg(ctx, npkg);734    } else if (choice[0] == 't' or choice[0] == 'T') {735        try tryPkg(ctx, npkg);736    }737}738739fn profileInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {740    output.installStart(npkg.pname, .profile);741    output.printSubstep("nix profile add nixpkgs#{s}", .{npkg.attr});742    output.printTeach(try std.fmt.allocPrint(ctx.gpa, "nix profile add nixpkgs#{s}", .{npkg.attr}));743    const code = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, npkg.attr);744    if (code != 0) return error.ProcessFailed;745    output.installDone(npkg.pname);746}747748fn systemInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {749    const config_path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});750    defer ctx.gpa.free(config_path);751    const line = api.findSystemPackagesLine(ctx.io, config_path) orelse 1;752    output.installEditorPrompt(npkg.pname, config_path, line, ctx.cfg.editor);753    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, config_path, line);754    if (ctx.cfg.confirm) {755        if (output.confirm("apply now? ")) {756            try apply(ctx);757        }758    }759}760761fn tryPkg(ctx: Ctx, npkg: types.NixPackage) !void {762    output.tryStart(npkg.pname);763    output.printSubstep("nix shell nixpkgs#{s}", .{npkg.attr});764    output.tryExitHint();765    _ = try exec.nixShellPs1(ctx.io, &ctx.machine, ctx.gpa, npkg.attr, ctx.environ);766    output.tryDone();767}768769pub fn remove(ctx: Ctx) !void {770    const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;771    output.removeStart(pkg_name);772    const code = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, pkg_name);773    if (code != 0) return error.ProcessFailed;774    output.done();775}776777pub fn list(ctx: Ctx) !void {778    output.listHeader(ctx.machine.name);779780    // Profile packages: parse `nix profile list --json` into clean name+version781    // rows instead of dumping nix's verbose multi-line "Name:/Flake attribute:"782    // blocks.783    if (exec.profileListJson(ctx.gpa, ctx.io, &ctx.machine) catch null) |json| {784        defer ctx.gpa.free(json);785        output.listSection("profile");786        renderProfileJson(ctx.gpa, json);787    }788789    // System packages: the references of /run/current-system/sw, each a790    // <hash>-<name>-<version> store path.791    if (exec.systemPackagePaths(ctx.gpa, ctx.io, &ctx.machine) catch null) |paths| {792        defer ctx.gpa.free(paths);793        output.blankLine();794        output.listSection("system");795        var lines = std.mem.splitScalar(u8, paths, '\n');796        while (lines.next()) |line| {797            const t = std.mem.trim(u8, line, " \t\r");798            if (t.len == 0) continue;799            const row = pkgFromStorePath(t);800            // Skip support paths with no parseable version (man pages, wrappers).801            if (row.version.len == 0) continue;802            output.listPkg(row.name, row.version);803        }804    }805}806807const PkgRow = struct { name: []const u8, version: []const u8 };808809// Split a nix store path basename (<hash>-<name>-<version>) into name + version.810// Version begins at the first '-' followed by a digit, which reliably lands on811// the name/version boundary since the 32-char hash and package names start with812// non-digits.813fn pkgFromStorePath(path: []const u8) PkgRow {814    const base = std.fs.path.basename(path);815    const after_hash = if (base.len > 33 and base[32] == '-') base[33..] else base;816    var i: usize = 0;817    while (i + 1 < after_hash.len) : (i += 1) {818        if (after_hash[i] == '-' and std.ascii.isDigit(after_hash[i + 1])) {819            return .{ .name = after_hash[0..i], .version = stripOutputSuffix(after_hash[i + 1 ..]) };820        }821    }822    return .{ .name = after_hash, .version = "" };823}824825// Multi-output derivations append the output name to the store path (e.g.826// curl-8.20.0-bin, less-692-man). Strip that suffix so the version column reads827// as just the version.828fn stripOutputSuffix(ver: []const u8) []const u8 {829    const suffixes = [_][]const u8{ "-bin", "-man", "-dev", "-doc", "-lib", "-info", "-out", "-static", "-devdoc" };830    for (suffixes) |s| {831        if (std.mem.endsWith(u8, ver, s)) return ver[0 .. ver.len - s.len];832    }833    return ver;834}835836test "pkgFromStorePath splits name and version at first dash-digit" {837    const a = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-ripgrep-15.1.0");838    try std.testing.expectEqualStrings("ripgrep", a.name);839    try std.testing.expectEqualStrings("15.1.0", a.version);840841    const b = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-helix-25.01");842    try std.testing.expectEqualStrings("helix", b.name);843    try std.testing.expectEqualStrings("25.01", b.version);844845    // multi-output store paths drop their output-name suffix846    const c = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-curl-8.20.0-bin");847    try std.testing.expectEqualStrings("curl", c.name);848    try std.testing.expectEqualStrings("8.20.0", c.version);849}850851fn firstStorePath(el: std.json.Value) ?[]const u8 {852    if (el != .object) return null;853    const sp = el.object.get("storePaths") orelse return null;854    if (sp != .array or sp.array.items.len == 0) return null;855    const first = sp.array.items[0];856    return if (first == .string) first.string else null;857}858859// `nix profile list --json` has two shapes across nix versions: newer keys each860// element by name (object), older lists them positionally (array). Handle both.861fn renderProfileJson(gpa: std.mem.Allocator, json: []const u8) void {862    const parsed = std.json.parseFromSlice(std.json.Value, gpa, json, .{}) catch return;863    defer parsed.deinit();864    if (parsed.value != .object) return;865    const elements = parsed.value.object.get("elements") orelse return;866    switch (elements) {867        .object => |obj| {868            var it = obj.iterator();869            while (it.next()) |entry| {870                const ver = if (firstStorePath(entry.value_ptr.*)) |p| pkgFromStorePath(p).version else "";871                output.listPkg(entry.key_ptr.*, ver);872            }873        },874        .array => |arr| {875            for (arr.items) |el| {876                const path = firstStorePath(el) orelse continue;877                const row = pkgFromStorePath(path);878                output.listPkg(row.name, row.version);879            }880        },881        else => {},882    }883}884885pub fn tryCmd(ctx: Ctx) !void {886    const pkg_name_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;887    const shell_pkg = types.NixPackage{ .attr = pkg_name_arg, .pname = pkg_name_arg, .version = "", .description = "" };888    try tryPkg(ctx, shell_pkg);889}890891// --- Home Manager commands ---892893const home_help = [_][2][]const u8{894    .{ "apply", "apply home manager configuration" },895    .{ "apply --dry", "preview changes" },896    .{ "back", "roll back one generation" },897    .{ "history", "list all generations" },898    .{ "edit", "open home.nix" },899    .{ "check", "validate without applying" },900    .{ "diff", "changes between generations" },901    .{ "packages", "list managed packages" },902};903904const HomeGen = struct {905    number: u32,906    date: []const u8,907    time: []const u8,908    path: []const u8,909};910911// `home-manager generations` lines read:912//   2026-06-01 11:56 : id 765 -> /nix/store/<hash>-home-manager-generation913// Newest first, so index 0 is the current generation.914fn parseHomeGenerations(gpa: std.mem.Allocator, out_str: []const u8) ![]HomeGen {915    var gens: std.ArrayList(HomeGen) = .empty;916    var lines = std.mem.splitScalar(u8, out_str, '\n');917    while (lines.next()) |line| {918        const t = std.mem.trim(u8, line, " \t\r");919        if (t.len == 0) continue;920        var it = std.mem.tokenizeAny(u8, t, " \t");921        const date = it.next() orelse continue;922        const time = it.next() orelse continue;923        var number: ?u32 = null;924        var path: []const u8 = "";925        while (it.next()) |tok| {926            if (std.mem.eql(u8, tok, "id")) {927                if (it.next()) |n| number = std.fmt.parseInt(u32, n, 10) catch null;928            } else if (std.mem.startsWith(u8, tok, "/nix/store/")) {929                path = tok;930            }931        }932        const num = number orelse continue;933        try gens.append(gpa, .{934            .number = num,935            .date = try gpa.dupe(u8, date),936            .time = try gpa.dupe(u8, time),937            .path = try gpa.dupe(u8, path),938        });939    }940    return gens.toOwnedSlice(gpa);941}942943fn freeHomeGens(gpa: std.mem.Allocator, gens: []HomeGen) void {944    for (gens) |g| {945        gpa.free(g.date);946        gpa.free(g.time);947        gpa.free(g.path);948    }949    gpa.free(gens);950}951952test "parseHomeGenerations reads id, date and store path" {953    const a = std.testing.allocator;954    const sample =955        \\2026-06-01 11:56 : id 765 -> /nix/store/aaaa-home-manager-generation956        \\2026-05-31 10:29 : id 764 -> /nix/store/bbbb-home-manager-generation957    ;958    const gens = try parseHomeGenerations(a, sample);959    defer freeHomeGens(a, gens);960    try std.testing.expectEqual(@as(usize, 2), gens.len);961    try std.testing.expectEqual(@as(u32, 765), gens[0].number);962    try std.testing.expectEqualStrings("2026-06-01", gens[0].date);963    try std.testing.expectEqualStrings("11:56", gens[0].time);964    try std.testing.expectEqualStrings("/nix/store/aaaa-home-manager-generation", gens[0].path);965    try std.testing.expectEqual(@as(u32, 764), gens[1].number);966}967968// Current (newest) home generation number, or 0 if unavailable.969fn homeCurrentGen(ctx: Ctx) u32 {970    const out = exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine) catch return 0;971    defer ctx.gpa.free(out);972    const gens = parseHomeGenerations(ctx.gpa, out) catch return 0;973    defer freeHomeGens(ctx.gpa, gens);974    return if (gens.len > 0) gens[0].number else 0;975}976977pub fn home(ctx: Ctx) !void {978    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help"))979        return output.subcommandHelp("home", &home_help, null);980981    // Home Manager manages the local user's environment. Detection (which binary,982    // ~/.config/home-manager, $HOME/$USER for the flake ref) all read the LOCAL983    // host, while exec routes over SSH for a remote machine — so `home --on984    // <remote>` would decide mode/flake-ref from the wrong box. Refuse it cleanly985    // rather than acting on a mismatch.986    if (!ctx.machine.local) {987        output.homeLocalOnly(ctx.machine.name);988        return;989    }990991    const mode = exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ);992    if (mode == .none) {993        output.homeNotInstalled();994        return;995    }996997    // apply is the only command meaningful in module mode (it redirects to998    // `nina apply`); everything else needs the standalone home-manager CLI.999    if (std.mem.eql(u8, ctx.sub, "apply")) return homeApply(ctx, mode);1000    // edit just opens the local home.nix — fine in module mode too.1001    if (std.mem.eql(u8, ctx.sub, "edit")) return homeEdit(ctx);10021003    if (mode == .module) {1004        output.homeModuleManaged();1005        return;1006    }10071008    if (std.mem.eql(u8, ctx.sub, "back")) return homeBack(ctx);1009    if (std.mem.eql(u8, ctx.sub, "history")) return homeHistory(ctx);1010    if (std.mem.eql(u8, ctx.sub, "check")) return homeCheck(ctx);1011    if (std.mem.eql(u8, ctx.sub, "diff")) return homeDiff(ctx);1012    if (std.mem.eql(u8, ctx.sub, "packages")) return homePackages(ctx);10131014    return output.subcommandHelp("home", &home_help, null);1015}10161017fn homePackages(ctx: Ctx) !void {1018    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1019    defer ctx.gpa.free(out);1020    const gens = try parseHomeGenerations(ctx.gpa, out);1021    defer freeHomeGens(ctx.gpa, gens);10221023    output.homePackagesHeader(ctx.machine.name);1024    if (gens.len == 0 or gens[0].path.len == 0) return;10251026    // The generation's OWN references are home-manager's activation deps1027    // (bash, coreutils, ...), not what the user installed. The user's packages1028    // live one level down, in the `…-home-manager-path` env the generation1029    // references — descend into it and list ITS references. Fall back to the1030    // generation refs if that env isn't present (older home-manager layouts).1031    const gen_refs = exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, gens[0].path) catch return;1032    defer ctx.gpa.free(gen_refs);10331034    var refs = gen_refs;1035    var env_refs: ?[]u8 = null;1036    defer if (env_refs) |e| ctx.gpa.free(e);1037    if (findHomeManagerPath(gen_refs)) |pkg_path| {1038        if (exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, pkg_path)) |e| {1039            env_refs = e;1040            refs = e;1041        } else |_| {}1042    }10431044    // Dedup by name: multi-output derivations (jq, jq-lib, jq-doc) collapse to1045    // the same name after the output suffix is stripped. Keys are slices into1046    // `refs`, valid for this function's lifetime.1047    var seen = std.StringHashMap(void).init(ctx.gpa);1048    defer seen.deinit();1049    var lines = std.mem.splitScalar(u8, refs, '\n');1050    while (lines.next()) |line| {1051        const t = std.mem.trim(u8, line, " \t\r");1052        if (t.len == 0) continue;1053        const row = pkgFromStorePath(t);1054        if (row.version.len == 0) continue;1055        if (std.mem.indexOf(u8, row.name, "home-manager") != null) continue;1056        if (seen.contains(row.name)) continue;1057        seen.put(row.name, {}) catch {};1058        output.listPkg(row.name, row.version);1059    }1060}10611062// The `…-home-manager-path` env among a generation's references — the buildEnv1063// of the user's home.packages. Returns the full store-path line, or null.1064fn findHomeManagerPath(refs: []const u8) ?[]const u8 {1065    var lines = std.mem.splitScalar(u8, refs, '\n');1066    while (lines.next()) |line| {1067        const t = std.mem.trim(u8, line, " \t\r");1068        if (std.mem.indexOf(u8, t, "home-manager-path") != null) return t;1069    }1070    return null;1071}10721073test "findHomeManagerPath picks the env, not the generation or infra" {1074    const refs =1075        \\/nix/store/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-bash-5.31076        \\/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path1077        \\/nix/store/cccccccccccccccccccccccccccccccc-coreutils-9.111078    ;1079    try std.testing.expectEqualStrings(1080        "/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path",1081        findHomeManagerPath(refs).?,1082    );1083    try std.testing.expectEqual(@as(?[]const u8, null), findHomeManagerPath("/nix/store/x-bash-5.3\n"));1084}10851086fn homeDiff(ctx: Ctx) !void {1087    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1088    defer ctx.gpa.free(out);1089    const gens = try parseHomeGenerations(ctx.gpa, out);1090    defer freeHomeGens(ctx.gpa, gens);10911092    // Need two generations and both their store paths to diff their closures.1093    if (gens.len < 2 or gens[0].path.len == 0 or gens[1].path.len == 0) {1094        output.homeNothingToDiff();1095        return;1096    }1097    const newer = gens[0];1098    const older = gens[1];1099    output.homeDiffHeader(older.number, newer.number, ctx.machine.name);1100    if (try exec.diffClosuresPaths(ctx.io, &ctx.machine, ctx.gpa, older.path, newer.path) != 0)1101        return error.ProcessFailed;1102}11031104fn homeCheck(ctx: Ctx) !void {1105    output.homeCheckStart(ctx.machine.name);1106    const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa);1107    if (code != 0) {1108        output.checkFailed("");1109        return error.BuildFailed;1110    }1111    output.homeCheckOk();1112}11131114fn homeEdit(ctx: Ctx) !void {1115    // Standalone home config lives at ~/.config/home-manager/home.nix; the same1116    // path is what detection keys on for module mode, so it resolves for both.1117    const path = exec.homeNixPath(ctx.gpa, ctx.environ) orelse {1118        errors.error_info.setMessage("could not resolve ~/.config/home-manager/home.nix", .{});1119        return error.ConfigNotFound;1120    };1121    defer ctx.gpa.free(path);1122    output.homeEditOpen(path, ctx.cfg.editor);1123    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);1124}11251126fn homeHistory(ctx: Ctx) !void {1127    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1128    defer ctx.gpa.free(out);1129    const gens = try parseHomeGenerations(ctx.gpa, out);1130    defer freeHomeGens(ctx.gpa, gens);1131    output.homeHistoryHeader(ctx.machine.name);1132    // Newest-first from home-manager; the first row is the current generation.1133    for (gens, 0..) |g, i| output.homeHistoryRow(g.number, g.date, g.time, i == 0);1134}11351136fn homeBack(ctx: Ctx) !void {1137    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1138    defer ctx.gpa.free(out);1139    const gens = try parseHomeGenerations(ctx.gpa, out);1140    defer freeHomeGens(ctx.gpa, gens);11411142    // Newest-first: [0] is current, [1] is the generation to roll back to.1143    if (gens.len < 2) {1144        output.alreadyOldest();1145        return;1146    }1147    const current = gens[0].number;1148    const prev = gens[1].number;11491150    output.homeBackStart(ctx.machine.name, current, prev);1151    if (ctx.cfg.confirm and !output.confirm("")) return;1152    const code = try exec.homeManagerRollback(ctx.io, &ctx.machine, ctx.gpa);1153    if (code != 0) return error.BuildFailed;1154    output.homeBackDone(prev);1155}11561157fn homeApply(ctx: Ctx, mode: exec.HomeManagerMode) !void {1158    // NixOS/flake module: home config is rebuilt by nixos-rebuild — redirect.1159    if (mode == .module) {1160        output.homeModuleManaged();1161        return;1162    }1163    if (ctx.dry) {1164        output.homeApplyDry(ctx.machine.name);1165        const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa);1166        if (code != 0) return error.BuildFailed;1167        output.homeApplyDryDone();1168        return;1169    }11701171    output.homeApplyStart(ctx.machine.name);1172    const flake_ref = exec.homeFlakeRef(ctx.gpa, ctx.io, ctx.environ);1173    defer if (flake_ref) |r| ctx.gpa.free(r);1174    if (flake_ref) |ref| {1175        output.printSubstep("home-manager switch --flake {s}", .{ref});1176    } else {1177        output.printSubstep("home-manager switch", .{});1178    }11791180    const start = std.Io.Clock.awake.now(ctx.io);1181    const code = if (flake_ref) |ref|1182        try exec.homeManagerSwitchFlake(ctx.io, &ctx.machine, ctx.gpa, ref)1183    else1184        try exec.homeManagerSwitch(ctx.io, &ctx.machine, ctx.gpa);1185    if (code != 0) return error.BuildFailed;11861187    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());1188    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));1189    output.homeApplyDone(homeCurrentGen(ctx), elapsed);1190}11911192// --- Service commands ---11931194const service_help = [_][2][]const u8{1195    .{ "list", "list running services" },1196    .{ "logs <svc>", "show service logs" },1197    .{ "status <svc>", "service status" },1198    .{ "start <svc>", "start a service" },1199    .{ "stop <svc>", "stop a service" },1200    .{ "restart <svc>", "restart a service" },1201    .{ "enable <svc>", "enable at boot" },1202    .{ "disable <svc>", "disable at boot" },1203};12041205pub fn service(ctx: Ctx) !void {1206    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("service", &service_help, "add --user to act on user services");1207    if (std.mem.eql(u8, ctx.sub, "list")) {1208        output.serviceListHeader(ctx.machine.name);1209        const svcs = exec.serviceList(ctx.gpa, ctx.io, &ctx.machine, ctx.user) catch &.{};1210        defer ctx.gpa.free(svcs);1211        for (svcs) |s| output.serviceRow(s);1212        return;1213    }1214    if (std.mem.eql(u8, ctx.sub, "logs")) {1215        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1216        const follow = ctx.args.len > 1 and std.mem.eql(u8, ctx.args[1], "-f");1217        output.serviceLogsHeader(name, ctx.last, ctx.machine.name);1218        _ = try exec.serviceLogs(ctx.io, &ctx.machine, ctx.gpa, name, ctx.last, follow, ctx.user);1219        return;1220    }1221    if (std.mem.eql(u8, ctx.sub, "status")) {1222        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1223        output.serviceVerb("status", name, ctx.machine.name);1224        _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, "status", name, ctx.user);1225        return;1226    }1227    // start/stop/restart/enable/disable1228    const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1229    if (ctx.cfg.confirm and (std.mem.eql(u8, ctx.sub, "stop") or std.mem.eql(u8, ctx.sub, "disable"))) {1230        if (!output.confirm("")) return;1231    }1232    output.serviceVerb(ctx.sub, name, ctx.machine.name);1233    _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, ctx.sub, name, ctx.user);1234    output.serviceDone();1235}12361237// --- Flake commands ---12381239const flake_help = [_][2][]const u8{1240    .{ "init", "create a new flake.nix" },1241    .{ "update", "update flake inputs" },1242    .{ "update <in>", "update a specific input" },1243    .{ "check", "validate the flake" },1244    .{ "show", "inspect flake outputs" },1245    .{ "lock", "regenerate flake.lock" },1246    .{ "clone <url>", "clone a flake repository" },1247};12481249pub fn flake(ctx: Ctx) !void {1250    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("flake", &flake_help, null);1251    if (std.mem.eql(u8, ctx.sub, "update")) {1252        output.flakeUpdateStart();1253        const input: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1254        _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1255        output.flakeLockWritten();1256        return;1257    }1258    if (std.mem.eql(u8, ctx.sub, "check")) {1259        output.flakeCheckStart();1260        const code = try exec.flakeCheck(ctx.io, &ctx.machine, ctx.gpa);1261        if (code == 0) output.flakeValid() else output.checkFailed("");1262        return;1263    }1264    if (std.mem.eql(u8, ctx.sub, "show")) {1265        const json_out = exec.flakeShow(ctx.gpa, ctx.io, &ctx.machine) catch null;1266        if (json_out) |j| {1267            defer ctx.gpa.free(j);1268            output.flakeShowHeader("flake outputs");1269            // Parse and display the flake outputs1270            const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, j, .{}) catch return;1271            defer parsed.deinit();1272            if (parsed.value == .object) {1273                var it = parsed.value.object.iterator();1274                while (it.next()) |entry| {1275                    if (entry.value_ptr.* == .object) {1276                        var inner = entry.value_ptr.object.iterator();1277                        while (inner.next()) |e2| {1278                            const desc = if (e2.value_ptr.* == .object)1279                                if (e2.value_ptr.object.get("description")) |d|1280                                    if (d == .string) d.string else ""1281                                else ""1282                            else "";1283                            output.flakeShowEntry(entry.key_ptr.*, e2.key_ptr.*, desc);1284                        }1285                    }1286                }1287            }1288        }1289        return;1290    }1291    if (std.mem.eql(u8, ctx.sub, "init")) {1292        _ = try exec.flakeInit(ctx.io, &ctx.machine, ctx.gpa);1293        return;1294    }1295    if (std.mem.eql(u8, ctx.sub, "lock")) {1296        _ = try exec.flakeLock(ctx.io, &ctx.machine, ctx.gpa);1297        return;1298    }1299    if (std.mem.eql(u8, ctx.sub, "clone")) {1300        const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1301        _ = try exec.flakeClone(ctx.io, &ctx.machine, ctx.gpa, url);1302        return;1303    }1304}13051306// --- Store commands ---13071308const store_help = [_][2][]const u8{1309    .{ "info", "store size and counts" },1310    .{ "path <attr>", "store path of a package" },1311    .{ "gc", "collect garbage" },1312    .{ "verify", "verify store integrity" },1313    .{ "repair", "repair corrupted paths" },1314};13151316pub fn store(ctx: Ctx) !void {1317    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("store", &store_help, null);1318    if (std.mem.eql(u8, ctx.sub, "gc")) {1319        _ = try exec.storeGc(ctx.io, &ctx.machine, ctx.gpa);1320        return;1321    }1322    if (std.mem.eql(u8, ctx.sub, "verify")) {1323        output.storeVerifyStart();1324        _ = try exec.storeVerify(ctx.io, &ctx.machine, ctx.gpa);1325        return;1326    }1327    if (std.mem.eql(u8, ctx.sub, "repair")) {1328        if (ctx.cfg.confirm and !output.confirm("")) return;1329        output.storeRepairStart();1330        _ = try exec.storeRepair(ctx.io, &ctx.machine, ctx.gpa);1331        return;1332    }1333    if (std.mem.eql(u8, ctx.sub, "info")) {1334        const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1335        output.storeInfo(si);1336        return;1337    }1338    if (std.mem.eql(u8, ctx.sub, "path")) {1339        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1340        const path = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, attr);1341        defer ctx.gpa.free(path);1342        output.storePath(path);1343        return;1344    }1345    // default: info1346    const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1347    output.storeInfo(si);1348}13491350// --- Channel commands ---13511352const channel_help = [_][2][]const u8{1353    .{ "list", "list channels" },1354    .{ "add <url> [name]", "add a channel" },1355    .{ "remove <name>", "remove a channel" },1356    .{ "update", "update all channels" },1357};13581359pub fn channel(ctx: Ctx) !void {1360    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("channel", &channel_help, null);1361    // On a flake-managed system, nix-channel operations generally don't apply.1362    if (flakeSystem(ctx)) output.flakeChannelNote();1363    if (std.mem.eql(u8, ctx.sub, "list")) {1364        output.channelListHeader(ctx.machine.name);1365        const chans = try exec.channelList(ctx.gpa, ctx.io, &ctx.machine);1366        defer ctx.gpa.free(chans);1367        for (chans) |ch| output.channelRow(ch);1368        return;1369    }1370    if (std.mem.eql(u8, ctx.sub, "add")) {1371        const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1372        const name = if (ctx.args.len > 1) ctx.args[1] else "";1373        _ = try exec.channelAdd(ctx.io, &ctx.machine, ctx.gpa, url, name);1374        output.channelDone();1375        return;1376    }1377    if (std.mem.eql(u8, ctx.sub, "remove")) {1378        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1379        _ = try exec.channelRemove(ctx.io, &ctx.machine, ctx.gpa, name);1380        output.channelDone();1381        return;1382    }1383    if (std.mem.eql(u8, ctx.sub, "update")) {1384        return channelUpdateCmd(ctx);1385    }1386}13871388// --- Profile commands ---13891390pub fn profile(ctx: Ctx) !void {1391    if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {1392        output.profileListHeader();1393        const out = exec.profileList(ctx.gpa, ctx.io, &ctx.machine) catch null;1394        if (out) |o| {1395            defer ctx.gpa.free(o);1396            var lines = std.mem.splitScalar(u8, o, '\n');1397            while (lines.next()) |line| {1398                const t = std.mem.trim(u8, line, " \t\r");1399                if (t.len == 0) continue;1400                output.profileRow(t, "", "");1401            }1402        }1403        return;1404    }1405    if (std.mem.eql(u8, ctx.sub, "install")) {1406        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1407        _ = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, attr);1408        output.done();1409        return;1410    }1411    if (std.mem.eql(u8, ctx.sub, "remove")) {1412        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1413        _ = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, attr);1414        output.done();1415        return;1416    }1417    if (std.mem.eql(u8, ctx.sub, "upgrade")) {1418        _ = try exec.profileUpgrade(ctx.io, &ctx.machine, ctx.gpa);1419        output.done();1420        return;1421    }1422}14231424// --- Pkg commands ---14251426const pkg_help = [_][2][]const u8{1427    .{ "why <pkg>", "what pulled it in" },1428    .{ "deps <pkg>", "direct dependencies" },1429    .{ "size <pkg>", "closure size" },1430    .{ "path <pkg>", "store path" },1431    .{ "closure <pkg>", "full closure" },1432};14331434pub fn pkg(ctx: Ctx) !void {1435    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("pkg", &pkg_help, null);1436    const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1437    if (std.mem.eql(u8, ctx.sub, "why")) {1438        _ = try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name);1439        return;1440    }1441    if (std.mem.eql(u8, ctx.sub, "deps")) {1442        _ = try exec.pkgDeps(ctx.io, &ctx.machine, ctx.gpa, name);1443        return;1444    }1445    if (std.mem.eql(u8, ctx.sub, "size")) {1446        const s = exec.pkgSize(ctx.gpa, ctx.io, &ctx.machine, name) catch null;1447        if (s) |sz| {1448            defer ctx.gpa.free(sz);1449            output.pkgResult("size", sz);1450        }1451        return;1452    }1453    if (std.mem.eql(u8, ctx.sub, "path")) {1454        const p = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, name);1455        defer ctx.gpa.free(p);1456        output.pkgResult("path", p);1457        return;1458    }1459    if (std.mem.eql(u8, ctx.sub, "closure")) {1460        _ = try exec.pkgClosure(ctx.io, &ctx.machine, ctx.gpa, name);1461        return;1462    }1463}14641465// Top-level alias for `nina pkg why <pkg>` — surfaces what pulled a package in1466// without the user needing to know about the `pkg` subgroup.1467pub fn why(ctx: Ctx) !void {1468    const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1469    _ = try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name);1470}14711472// --- Pin / Unpin ---14731474pub fn pin(ctx: Ctx) !void {1475    const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1476    const commit = if (ctx.args.len > 1) ctx.args[1] else return error.Internal;1477    exec.editFlakeLock(ctx.gpa, input, commit) catch return error.ProcessFailed;1478    output.pinDone(input, commit);1479}14801481pub fn unpin(ctx: Ctx) !void {1482    const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1483    _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1484    output.unpinDone(input);1485}14861487// --- Hash / Fetch ---14881489pub fn hash(ctx: Ctx) !void {1490    const path = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1491    const h = try exec.nixHash(ctx.gpa, ctx.io, &ctx.machine, path);1492    defer ctx.gpa.free(h);1493    output.hashResult(std.mem.trim(u8, h, " \t\n\r"));1494}14951496pub fn fetch(ctx: Ctx) !void {1497    const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1498    const h = try exec.nixFetch(ctx.gpa, ctx.io, &ctx.machine, url);1499    defer ctx.gpa.free(h);1500    output.fetchResult(std.mem.trim(u8, h, " \t\n\r"), url);1501}15021503// --- Build / Run ---15041505pub fn build(ctx: Ctx) !void {1506    const attr: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1507    output.buildStart(attr orelse "default");1508    const code = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, attr);1509    if (code != 0) return error.BuildFailed;1510    output.buildDone();1511}15121513pub fn runCmd(ctx: Ctx) !void {1514    const pkg_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1515    output.runStart(pkg_arg);1516    _ = try exec.nixRun(ctx.io, &ctx.machine, ctx.gpa, pkg_arg);1517}15181519// --- Hello ---15201521pub fn hello(ctx: Ctx) !void {1522    output.hello(ctx.cfg.machines);1523}15241525const ConfigKind = enum { flake, channel, none };15261527// Scan the conventional /etc/nixos for a flake.nix (flake-based) or a1528// configuration.nix (channel-based) to pre-fill the wizard's defaults.1529fn scanConfig(io: std.Io) ConfigKind {1530    if (exec.pathExists(io, "/etc/nixos/flake.nix")) return .flake;1531    if (exec.pathExists(io, "/etc/nixos/configuration.nix")) return .channel;1532    return .none;1533}15341535// Runs when the config is absent on first invocation (interactive TTY only).1536// Scans for an existing nixos config, detects flake vs channel, and offers a1537// smart default path — flake-ness is detected, never asked.1538pub fn firstRunWizard(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1539    output.firstRunBanner();1540    output.firstRunNoConfig();15411542    var name_buf: [256]u8 = undefined;1543    var path_buf: [256]u8 = undefined;15441545    const machine_name = output.firstRunPrompt("machine name", "my-machine", &name_buf);15461547    output.firstRunScanning();1548    const kind = scanConfig(io);1549    switch (kind) {1550        .flake => output.firstRunDetected("/etc/nixos/flake.nix", true),1551        .channel => output.firstRunDetected("/etc/nixos/configuration.nix", false),1552        .none => output.firstRunNoneFound(),1553    }15541555    // Detected systems default to /etc/nixos (press enter to confirm); when1556    // nothing was found, leave the default empty so the user must type a path.1557    const default_path: []const u8 = if (kind == .none) "" else "/etc/nixos";1558    const config_path = output.firstRunPromptDefault("config path", default_path, kind != .none, &path_buf);15591560    // Re-detect at the chosen path in case the user pointed elsewhere — flake.nix1561    // there means a flake system, recorded so channel commands warn appropriately.1562    const use_flakes = exec.dirHasFlake(gpa, io, config_path);15631564    const conf_path = try config.configPath(gpa, environ);1565    defer gpa.free(conf_path);1566    if (std.fs.path.dirname(conf_path)) |dir| exec.ensureDir(gpa, io, dir);15671568    // `flake` is a top-level config field, so it must precede the [machine] block.1569    const flake_line = if (use_flakes) "flake = true\n" else "";1570    var content_buf: [1024]u8 = undefined;1571    const content = try std.fmt.bufPrint(1572        &content_buf,1573        "{s}[machine]\nname = {s}\nconfig = {s}\nlocal = true\n",1574        .{ flake_line, machine_name, config_path },1575    );15761577    const file = std.Io.Dir.createFile(.cwd(), io, conf_path, .{}) catch {1578        errors.error_info.setMessage("could not write {s}", .{conf_path});1579        return error.Internal;1580    };1581    defer file.close(io);1582    file.writePositionalAll(io, content, 0) catch {1583        errors.error_info.setMessage("could not write {s}", .{conf_path});1584        return error.Internal;1585    };15861587    output.firstRunWritten(conf_path);1588}15891590pub fn setup(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1591    // Create the config first if it doesn't exist. This makes `nina setup`1592    // a complete onboarding command — not just a nix-features check. Any legacy1593    // ~/.nina.conf is migrated to the XDG path before we decide to run the wizard.1594    config.migrateLegacyConfig(gpa, io, environ);1595    if (config.configPath(gpa, environ)) |conf_path| {1596        defer gpa.free(conf_path);1597        if (std.Io.Dir.openFile(.cwd(), io, conf_path, .{})) |f| {1598            f.close(io);1599        } else |_| {1600            try firstRunWizard(gpa, io, environ);1601            errors.error_info.reset();1602        }1603    } else |_| {}16041605    output.setupCheck();1606    const status = exec.checkNixFeatures(gpa, io, environ);1607    output.setupFeatures(status.nix_command, status.flakes);16081609    if (status.allEnabled()) {1610        output.setupAllSet();1611        api.ensureRegistryPinned(gpa, io, environ);1612        return;1613    }16141615    // On NixOS the features belong in configuration.nix (the declarative,1616    // permanent home), not ~/.config/nix/nix.conf. Offer to add the one line;1617    // the user runs the rebuild. We don't pin the registry here because the1618    // features aren't live until that rebuild lands.1619    if (exec.isNixOS(io)) {1620        const conf_path = "/etc/nixos/configuration.nix";1621        if (exec.nixosConfigEnablesFeatures(gpa, io, conf_path)) {1622            output.setupNixosNeedsRebuild(conf_path);1623            return;1624        }1625        output.setupNixosOffer(exec.NIXOS_FEATURES_LINE, conf_path);1626        if (output.confirmDefaultNo("add it now?")) {1627            if (exec.appendFeaturesToNixosConfig(gpa, io, environ, conf_path)) |_| {1628                output.setupNixosWrote(conf_path);1629            } else |_| {1630                output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);1631            }1632        } else {1633            output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);1634        }1635        return;1636    }16371638    // Non-NixOS: a user-level nix.conf takes effect immediately, no sudo needed.1639    output.setupEnabling();1640    const path = try exec.enableNixFeatures(gpa, io, environ);1641    defer gpa.free(path);16421643    output.setupDone(path);1644    api.ensureRegistryPinned(gpa, io, environ);1645}16461647// --- Log helper ---16481649fn logAction(ctx: Ctx, action: []const u8, gen: u32) void {1650    var ts_buf: [32]u8 = undefined;1651    const ts = nowIso(ctx.io, &ts_buf);1652    var buf: [256]u8 = undefined;1653    const entry = std.fmt.bufPrint(&buf, "{{\"ts\":\"{s}\",\"machine\":\"{s}\",\"command\":\"{s}\",\"outcome\":\"success\",\"gen_before\":null,\"gen_after\":{d},\"duration_ms\":0}}\n", .{1654        ts, ctx.machine.name, action, gen,1655    }) catch return;1656    exec.appendNinaLog(ctx.io, ctx.environ, entry);1657}16581659// Wall-clock UTC as ISO-8601. Uses Io.Clock.real (the settable Unix-epoch clock);1660// Io.Clock.awake is monotonic and unsuitable for timestamps. Falls back to epoch 0.1661fn nowIso(io: std.Io, buf: []u8) []const u8 {1662    const fallback = "1970-01-01T00:00:00Z";1663    const ns = std.Io.Clock.real.now(io).toNanoseconds();1664    if (ns <= 0) return fallback;1665    const secs: u64 = @intCast(@divFloor(ns, 1_000_000_000));1666    const es = std.time.epoch.EpochSeconds{ .secs = secs };1667    const ed = es.getEpochDay();1668    const yd = ed.calculateYearDay();1669    const md = yd.calculateMonthDay();1670    const ds = es.getDaySeconds();1671    return std.fmt.bufPrint(buf, "{d:0>4}-{d:0>2}-{d:0>2}T{d:0>2}:{d:0>2}:{d:0>2}Z", .{1672        yd.year, md.month.numeric(), @as(u32, md.day_index) + 1,1673        ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(),1674    }) catch return fallback;1675}