commands.zig

64.0 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    const mode = exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ);982    if (mode == .none) {983        output.homeNotInstalled();984        return;985    }986987    // apply is the only command meaningful in module mode (it redirects to988    // `nina apply`); everything else needs the standalone home-manager CLI.989    if (std.mem.eql(u8, ctx.sub, "apply")) return homeApply(ctx, mode);990    // edit just opens the local home.nix — fine in module mode too.991    if (std.mem.eql(u8, ctx.sub, "edit")) return homeEdit(ctx);992993    if (mode == .module) {994        output.homeModuleManaged();995        return;996    }997998    if (std.mem.eql(u8, ctx.sub, "back")) return homeBack(ctx);999    if (std.mem.eql(u8, ctx.sub, "history")) return homeHistory(ctx);1000    if (std.mem.eql(u8, ctx.sub, "check")) return homeCheck(ctx);1001    if (std.mem.eql(u8, ctx.sub, "diff")) return homeDiff(ctx);1002    if (std.mem.eql(u8, ctx.sub, "packages")) return homePackages(ctx);10031004    return output.subcommandHelp("home", &home_help, null);1005}10061007fn homePackages(ctx: Ctx) !void {1008    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1009    defer ctx.gpa.free(out);1010    const gens = try parseHomeGenerations(ctx.gpa, out);1011    defer freeHomeGens(ctx.gpa, gens);10121013    output.homePackagesHeader(ctx.machine.name);1014    if (gens.len == 0 or gens[0].path.len == 0) return;10151016    // The generation's OWN references are home-manager's activation deps1017    // (bash, coreutils, ...), not what the user installed. The user's packages1018    // live one level down, in the `…-home-manager-path` env the generation1019    // references — descend into it and list ITS references. Fall back to the1020    // generation refs if that env isn't present (older home-manager layouts).1021    const gen_refs = exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, gens[0].path) catch return;1022    defer ctx.gpa.free(gen_refs);10231024    var refs = gen_refs;1025    var env_refs: ?[]u8 = null;1026    defer if (env_refs) |e| ctx.gpa.free(e);1027    if (findHomeManagerPath(gen_refs)) |pkg_path| {1028        if (exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, pkg_path)) |e| {1029            env_refs = e;1030            refs = e;1031        } else |_| {}1032    }10331034    // Dedup by name: multi-output derivations (jq, jq-lib, jq-doc) collapse to1035    // the same name after the output suffix is stripped. Keys are slices into1036    // `refs`, valid for this function's lifetime.1037    var seen = std.StringHashMap(void).init(ctx.gpa);1038    defer seen.deinit();1039    var lines = std.mem.splitScalar(u8, refs, '\n');1040    while (lines.next()) |line| {1041        const t = std.mem.trim(u8, line, " \t\r");1042        if (t.len == 0) continue;1043        const row = pkgFromStorePath(t);1044        if (row.version.len == 0) continue;1045        if (std.mem.indexOf(u8, row.name, "home-manager") != null) continue;1046        if (seen.contains(row.name)) continue;1047        seen.put(row.name, {}) catch {};1048        output.listPkg(row.name, row.version);1049    }1050}10511052// The `…-home-manager-path` env among a generation's references — the buildEnv1053// of the user's home.packages. Returns the full store-path line, or null.1054fn findHomeManagerPath(refs: []const u8) ?[]const u8 {1055    var lines = std.mem.splitScalar(u8, refs, '\n');1056    while (lines.next()) |line| {1057        const t = std.mem.trim(u8, line, " \t\r");1058        if (std.mem.indexOf(u8, t, "home-manager-path") != null) return t;1059    }1060    return null;1061}10621063test "findHomeManagerPath picks the env, not the generation or infra" {1064    const refs =1065        \\/nix/store/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-bash-5.31066        \\/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path1067        \\/nix/store/cccccccccccccccccccccccccccccccc-coreutils-9.111068    ;1069    try std.testing.expectEqualStrings(1070        "/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path",1071        findHomeManagerPath(refs).?,1072    );1073    try std.testing.expectEqual(@as(?[]const u8, null), findHomeManagerPath("/nix/store/x-bash-5.3\n"));1074}10751076fn homeDiff(ctx: Ctx) !void {1077    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1078    defer ctx.gpa.free(out);1079    const gens = try parseHomeGenerations(ctx.gpa, out);1080    defer freeHomeGens(ctx.gpa, gens);10811082    // Need two generations and both their store paths to diff their closures.1083    if (gens.len < 2 or gens[0].path.len == 0 or gens[1].path.len == 0) {1084        output.homeNothingToDiff();1085        return;1086    }1087    const newer = gens[0];1088    const older = gens[1];1089    output.homeDiffHeader(older.number, newer.number, ctx.machine.name);1090    if (try exec.diffClosuresPaths(ctx.io, &ctx.machine, ctx.gpa, older.path, newer.path) != 0)1091        return error.ProcessFailed;1092}10931094fn homeCheck(ctx: Ctx) !void {1095    output.homeCheckStart(ctx.machine.name);1096    const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa);1097    if (code != 0) {1098        output.checkFailed("");1099        return error.BuildFailed;1100    }1101    output.homeCheckOk();1102}11031104fn homeEdit(ctx: Ctx) !void {1105    // Standalone home config lives at ~/.config/home-manager/home.nix; the same1106    // path is what detection keys on for module mode, so it resolves for both.1107    const path = exec.homeNixPath(ctx.gpa, ctx.environ) orelse {1108        errors.error_info.setMessage("could not resolve ~/.config/home-manager/home.nix", .{});1109        return error.ConfigNotFound;1110    };1111    defer ctx.gpa.free(path);1112    output.homeEditOpen(path, ctx.cfg.editor);1113    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);1114}11151116fn homeHistory(ctx: Ctx) !void {1117    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1118    defer ctx.gpa.free(out);1119    const gens = try parseHomeGenerations(ctx.gpa, out);1120    defer freeHomeGens(ctx.gpa, gens);1121    output.homeHistoryHeader(ctx.machine.name);1122    // Newest-first from home-manager; the first row is the current generation.1123    for (gens, 0..) |g, i| output.homeHistoryRow(g.number, g.date, g.time, i == 0);1124}11251126fn homeBack(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);11311132    // Newest-first: [0] is current, [1] is the generation to roll back to.1133    if (gens.len < 2) {1134        output.alreadyOldest();1135        return;1136    }1137    const current = gens[0].number;1138    const prev = gens[1].number;11391140    output.homeBackStart(ctx.machine.name, current, prev);1141    if (ctx.cfg.confirm and !output.confirm("")) return;1142    const code = try exec.homeManagerRollback(ctx.io, &ctx.machine, ctx.gpa);1143    if (code != 0) return error.BuildFailed;1144    output.homeBackDone(prev);1145}11461147fn homeApply(ctx: Ctx, mode: exec.HomeManagerMode) !void {1148    // NixOS/flake module: home config is rebuilt by nixos-rebuild — redirect.1149    if (mode == .module) {1150        output.homeModuleManaged();1151        return;1152    }1153    if (ctx.dry) {1154        output.homeApplyDry(ctx.machine.name);1155        const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa);1156        if (code != 0) return error.BuildFailed;1157        output.homeApplyDryDone();1158        return;1159    }11601161    output.homeApplyStart(ctx.machine.name);1162    const flake_ref = exec.homeFlakeRef(ctx.gpa, ctx.io, ctx.environ);1163    defer if (flake_ref) |r| ctx.gpa.free(r);1164    if (flake_ref) |ref| {1165        output.printSubstep("home-manager switch --flake {s}", .{ref});1166    } else {1167        output.printSubstep("home-manager switch", .{});1168    }11691170    const start = std.Io.Clock.awake.now(ctx.io);1171    const code = if (flake_ref) |ref|1172        try exec.homeManagerSwitchFlake(ctx.io, &ctx.machine, ctx.gpa, ref)1173    else1174        try exec.homeManagerSwitch(ctx.io, &ctx.machine, ctx.gpa);1175    if (code != 0) return error.BuildFailed;11761177    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());1178    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));1179    output.homeApplyDone(homeCurrentGen(ctx), elapsed);1180}11811182// --- Service commands ---11831184const service_help = [_][2][]const u8{1185    .{ "list", "list running services" },1186    .{ "logs <svc>", "show service logs" },1187    .{ "status <svc>", "service status" },1188    .{ "start <svc>", "start a service" },1189    .{ "stop <svc>", "stop a service" },1190    .{ "restart <svc>", "restart a service" },1191    .{ "enable <svc>", "enable at boot" },1192    .{ "disable <svc>", "disable at boot" },1193};11941195pub fn service(ctx: Ctx) !void {1196    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");1197    if (std.mem.eql(u8, ctx.sub, "list")) {1198        output.serviceListHeader(ctx.machine.name);1199        const svcs = exec.serviceList(ctx.gpa, ctx.io, &ctx.machine, ctx.user) catch &.{};1200        defer ctx.gpa.free(svcs);1201        for (svcs) |s| output.serviceRow(s);1202        return;1203    }1204    if (std.mem.eql(u8, ctx.sub, "logs")) {1205        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1206        const follow = ctx.args.len > 1 and std.mem.eql(u8, ctx.args[1], "-f");1207        output.serviceLogsHeader(name, ctx.last, ctx.machine.name);1208        _ = try exec.serviceLogs(ctx.io, &ctx.machine, ctx.gpa, name, ctx.last, follow, ctx.user);1209        return;1210    }1211    if (std.mem.eql(u8, ctx.sub, "status")) {1212        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1213        output.serviceVerb("status", name, ctx.machine.name);1214        _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, "status", name, ctx.user);1215        return;1216    }1217    // start/stop/restart/enable/disable1218    const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1219    if (ctx.cfg.confirm and (std.mem.eql(u8, ctx.sub, "stop") or std.mem.eql(u8, ctx.sub, "disable"))) {1220        if (!output.confirm("")) return;1221    }1222    output.serviceVerb(ctx.sub, name, ctx.machine.name);1223    _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, ctx.sub, name, ctx.user);1224    output.serviceDone();1225}12261227// --- Flake commands ---12281229const flake_help = [_][2][]const u8{1230    .{ "init", "create a new flake.nix" },1231    .{ "update", "update flake inputs" },1232    .{ "update <in>", "update a specific input" },1233    .{ "check", "validate the flake" },1234    .{ "show", "inspect flake outputs" },1235    .{ "lock", "regenerate flake.lock" },1236    .{ "clone <url>", "clone a flake repository" },1237};12381239pub fn flake(ctx: Ctx) !void {1240    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("flake", &flake_help, null);1241    if (std.mem.eql(u8, ctx.sub, "update")) {1242        output.flakeUpdateStart();1243        const input: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1244        _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1245        output.flakeLockWritten();1246        return;1247    }1248    if (std.mem.eql(u8, ctx.sub, "check")) {1249        output.flakeCheckStart();1250        const code = try exec.flakeCheck(ctx.io, &ctx.machine, ctx.gpa);1251        if (code == 0) output.flakeValid() else output.checkFailed("");1252        return;1253    }1254    if (std.mem.eql(u8, ctx.sub, "show")) {1255        const json_out = exec.flakeShow(ctx.gpa, ctx.io, &ctx.machine) catch null;1256        if (json_out) |j| {1257            defer ctx.gpa.free(j);1258            output.flakeShowHeader("flake outputs");1259            // Parse and display the flake outputs1260            const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, j, .{}) catch return;1261            defer parsed.deinit();1262            if (parsed.value == .object) {1263                var it = parsed.value.object.iterator();1264                while (it.next()) |entry| {1265                    if (entry.value_ptr.* == .object) {1266                        var inner = entry.value_ptr.object.iterator();1267                        while (inner.next()) |e2| {1268                            const desc = if (e2.value_ptr.* == .object)1269                                if (e2.value_ptr.object.get("description")) |d|1270                                    if (d == .string) d.string else ""1271                                else ""1272                            else "";1273                            output.flakeShowEntry(entry.key_ptr.*, e2.key_ptr.*, desc);1274                        }1275                    }1276                }1277            }1278        }1279        return;1280    }1281    if (std.mem.eql(u8, ctx.sub, "init")) {1282        _ = try exec.flakeInit(ctx.io, &ctx.machine, ctx.gpa);1283        return;1284    }1285    if (std.mem.eql(u8, ctx.sub, "lock")) {1286        _ = try exec.flakeLock(ctx.io, &ctx.machine, ctx.gpa);1287        return;1288    }1289    if (std.mem.eql(u8, ctx.sub, "clone")) {1290        const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1291        _ = try exec.flakeClone(ctx.io, &ctx.machine, ctx.gpa, url);1292        return;1293    }1294}12951296// --- Store commands ---12971298const store_help = [_][2][]const u8{1299    .{ "info", "store size and counts" },1300    .{ "path <attr>", "store path of a package" },1301    .{ "gc", "collect garbage" },1302    .{ "verify", "verify store integrity" },1303    .{ "repair", "repair corrupted paths" },1304};13051306pub fn store(ctx: Ctx) !void {1307    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("store", &store_help, null);1308    if (std.mem.eql(u8, ctx.sub, "gc")) {1309        _ = try exec.storeGc(ctx.io, &ctx.machine, ctx.gpa);1310        return;1311    }1312    if (std.mem.eql(u8, ctx.sub, "verify")) {1313        output.storeVerifyStart();1314        _ = try exec.storeVerify(ctx.io, &ctx.machine, ctx.gpa);1315        return;1316    }1317    if (std.mem.eql(u8, ctx.sub, "repair")) {1318        if (ctx.cfg.confirm and !output.confirm("")) return;1319        output.storeRepairStart();1320        _ = try exec.storeRepair(ctx.io, &ctx.machine, ctx.gpa);1321        return;1322    }1323    if (std.mem.eql(u8, ctx.sub, "info")) {1324        const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1325        output.storeInfo(si);1326        return;1327    }1328    if (std.mem.eql(u8, ctx.sub, "path")) {1329        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1330        const path = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, attr);1331        defer ctx.gpa.free(path);1332        output.storePath(path);1333        return;1334    }1335    // default: info1336    const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1337    output.storeInfo(si);1338}13391340// --- Channel commands ---13411342const channel_help = [_][2][]const u8{1343    .{ "list", "list channels" },1344    .{ "add <url> [name]", "add a channel" },1345    .{ "remove <name>", "remove a channel" },1346    .{ "update", "update all channels" },1347};13481349pub fn channel(ctx: Ctx) !void {1350    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("channel", &channel_help, null);1351    // On a flake-managed system, nix-channel operations generally don't apply.1352    if (flakeSystem(ctx)) output.flakeChannelNote();1353    if (std.mem.eql(u8, ctx.sub, "list")) {1354        output.channelListHeader(ctx.machine.name);1355        const chans = try exec.channelList(ctx.gpa, ctx.io, &ctx.machine);1356        defer ctx.gpa.free(chans);1357        for (chans) |ch| output.channelRow(ch);1358        return;1359    }1360    if (std.mem.eql(u8, ctx.sub, "add")) {1361        const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1362        const name = if (ctx.args.len > 1) ctx.args[1] else "";1363        _ = try exec.channelAdd(ctx.io, &ctx.machine, ctx.gpa, url, name);1364        output.channelDone();1365        return;1366    }1367    if (std.mem.eql(u8, ctx.sub, "remove")) {1368        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1369        _ = try exec.channelRemove(ctx.io, &ctx.machine, ctx.gpa, name);1370        output.channelDone();1371        return;1372    }1373    if (std.mem.eql(u8, ctx.sub, "update")) {1374        return channelUpdateCmd(ctx);1375    }1376}13771378// --- Profile commands ---13791380pub fn profile(ctx: Ctx) !void {1381    if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {1382        output.profileListHeader();1383        const out = exec.profileList(ctx.gpa, ctx.io, &ctx.machine) catch null;1384        if (out) |o| {1385            defer ctx.gpa.free(o);1386            var lines = std.mem.splitScalar(u8, o, '\n');1387            while (lines.next()) |line| {1388                const t = std.mem.trim(u8, line, " \t\r");1389                if (t.len == 0) continue;1390                output.profileRow(t, "", "");1391            }1392        }1393        return;1394    }1395    if (std.mem.eql(u8, ctx.sub, "install")) {1396        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1397        _ = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, attr);1398        output.done();1399        return;1400    }1401    if (std.mem.eql(u8, ctx.sub, "remove")) {1402        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1403        _ = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, attr);1404        output.done();1405        return;1406    }1407    if (std.mem.eql(u8, ctx.sub, "upgrade")) {1408        _ = try exec.profileUpgrade(ctx.io, &ctx.machine, ctx.gpa);1409        output.done();1410        return;1411    }1412}14131414// --- Pkg commands ---14151416const pkg_help = [_][2][]const u8{1417    .{ "why <pkg>", "what pulled it in" },1418    .{ "deps <pkg>", "direct dependencies" },1419    .{ "size <pkg>", "closure size" },1420    .{ "path <pkg>", "store path" },1421    .{ "closure <pkg>", "full closure" },1422};14231424pub fn pkg(ctx: Ctx) !void {1425    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("pkg", &pkg_help, null);1426    const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1427    if (std.mem.eql(u8, ctx.sub, "why")) {1428        _ = try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name);1429        return;1430    }1431    if (std.mem.eql(u8, ctx.sub, "deps")) {1432        _ = try exec.pkgDeps(ctx.io, &ctx.machine, ctx.gpa, name);1433        return;1434    }1435    if (std.mem.eql(u8, ctx.sub, "size")) {1436        const s = exec.pkgSize(ctx.gpa, ctx.io, &ctx.machine, name) catch null;1437        if (s) |sz| {1438            defer ctx.gpa.free(sz);1439            output.pkgResult("size", sz);1440        }1441        return;1442    }1443    if (std.mem.eql(u8, ctx.sub, "path")) {1444        const p = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, name);1445        defer ctx.gpa.free(p);1446        output.pkgResult("path", p);1447        return;1448    }1449    if (std.mem.eql(u8, ctx.sub, "closure")) {1450        _ = try exec.pkgClosure(ctx.io, &ctx.machine, ctx.gpa, name);1451        return;1452    }1453}14541455// Top-level alias for `nina pkg why <pkg>` — surfaces what pulled a package in1456// without the user needing to know about the `pkg` subgroup.1457pub fn why(ctx: Ctx) !void {1458    const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1459    _ = try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name);1460}14611462// --- Pin / Unpin ---14631464pub fn pin(ctx: Ctx) !void {1465    const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1466    const commit = if (ctx.args.len > 1) ctx.args[1] else return error.Internal;1467    exec.editFlakeLock(ctx.gpa, input, commit) catch return error.ProcessFailed;1468    output.pinDone(input, commit);1469}14701471pub fn unpin(ctx: Ctx) !void {1472    const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1473    _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1474    output.unpinDone(input);1475}14761477// --- Hash / Fetch ---14781479pub fn hash(ctx: Ctx) !void {1480    const path = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1481    const h = try exec.nixHash(ctx.gpa, ctx.io, &ctx.machine, path);1482    defer ctx.gpa.free(h);1483    output.hashResult(std.mem.trim(u8, h, " \t\n\r"));1484}14851486pub fn fetch(ctx: Ctx) !void {1487    const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1488    const h = try exec.nixFetch(ctx.gpa, ctx.io, &ctx.machine, url);1489    defer ctx.gpa.free(h);1490    output.fetchResult(std.mem.trim(u8, h, " \t\n\r"), url);1491}14921493// --- Build / Run ---14941495pub fn build(ctx: Ctx) !void {1496    const attr: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1497    output.buildStart(attr orelse "default");1498    const code = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, attr);1499    if (code != 0) return error.BuildFailed;1500    output.buildDone();1501}15021503pub fn runCmd(ctx: Ctx) !void {1504    const pkg_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1505    output.runStart(pkg_arg);1506    _ = try exec.nixRun(ctx.io, &ctx.machine, ctx.gpa, pkg_arg);1507}15081509// --- Hello ---15101511pub fn hello(ctx: Ctx) !void {1512    output.hello(ctx.cfg.machines);1513}15141515const ConfigKind = enum { flake, channel, none };15161517// Scan the conventional /etc/nixos for a flake.nix (flake-based) or a1518// configuration.nix (channel-based) to pre-fill the wizard's defaults.1519fn scanConfig(io: std.Io) ConfigKind {1520    if (exec.pathExists(io, "/etc/nixos/flake.nix")) return .flake;1521    if (exec.pathExists(io, "/etc/nixos/configuration.nix")) return .channel;1522    return .none;1523}15241525// Runs when the config is absent on first invocation (interactive TTY only).1526// Scans for an existing nixos config, detects flake vs channel, and offers a1527// smart default path — flake-ness is detected, never asked.1528pub fn firstRunWizard(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1529    output.firstRunBanner();1530    output.firstRunNoConfig();15311532    var name_buf: [256]u8 = undefined;1533    var path_buf: [256]u8 = undefined;15341535    const machine_name = output.firstRunPrompt("machine name", "my-machine", &name_buf);15361537    output.firstRunScanning();1538    const kind = scanConfig(io);1539    switch (kind) {1540        .flake => output.firstRunDetected("/etc/nixos/flake.nix", true),1541        .channel => output.firstRunDetected("/etc/nixos/configuration.nix", false),1542        .none => output.firstRunNoneFound(),1543    }15441545    // Detected systems default to /etc/nixos (press enter to confirm); when1546    // nothing was found, leave the default empty so the user must type a path.1547    const default_path: []const u8 = if (kind == .none) "" else "/etc/nixos";1548    const config_path = output.firstRunPromptDefault("config path", default_path, kind != .none, &path_buf);15491550    // Re-detect at the chosen path in case the user pointed elsewhere — flake.nix1551    // there means a flake system, recorded so channel commands warn appropriately.1552    const use_flakes = exec.dirHasFlake(gpa, io, config_path);15531554    const conf_path = try config.configPath(gpa, environ);1555    defer gpa.free(conf_path);1556    if (std.fs.path.dirname(conf_path)) |dir| exec.ensureDir(gpa, io, dir);15571558    // `flake` is a top-level config field, so it must precede the [machine] block.1559    const flake_line = if (use_flakes) "flake = true\n" else "";1560    var content_buf: [1024]u8 = undefined;1561    const content = try std.fmt.bufPrint(1562        &content_buf,1563        "{s}[machine]\nname = {s}\nconfig = {s}\nlocal = true\n",1564        .{ flake_line, machine_name, config_path },1565    );15661567    const file = std.Io.Dir.createFile(.cwd(), io, conf_path, .{}) catch {1568        errors.error_info.setMessage("could not write {s}", .{conf_path});1569        return error.Internal;1570    };1571    defer file.close(io);1572    file.writePositionalAll(io, content, 0) catch {1573        errors.error_info.setMessage("could not write {s}", .{conf_path});1574        return error.Internal;1575    };15761577    output.firstRunWritten(conf_path);1578}15791580pub fn setup(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1581    // Create the config first if it doesn't exist. This makes `nina setup`1582    // a complete onboarding command — not just a nix-features check. Any legacy1583    // ~/.nina.conf is migrated to the XDG path before we decide to run the wizard.1584    config.migrateLegacyConfig(gpa, io, environ);1585    if (config.configPath(gpa, environ)) |conf_path| {1586        defer gpa.free(conf_path);1587        if (std.Io.Dir.openFile(.cwd(), io, conf_path, .{})) |f| {1588            f.close(io);1589        } else |_| {1590            try firstRunWizard(gpa, io, environ);1591            errors.error_info.reset();1592        }1593    } else |_| {}15941595    output.setupCheck();1596    const status = exec.checkNixFeatures(gpa, io, environ);1597    output.setupFeatures(status.nix_command, status.flakes);15981599    if (status.allEnabled()) {1600        output.setupAllSet();1601        api.ensureRegistryPinned(gpa, io, environ);1602        return;1603    }16041605    // On NixOS the features belong in configuration.nix (the declarative,1606    // permanent home), not ~/.config/nix/nix.conf. Offer to add the one line;1607    // the user runs the rebuild. We don't pin the registry here because the1608    // features aren't live until that rebuild lands.1609    if (exec.isNixOS(io)) {1610        const conf_path = "/etc/nixos/configuration.nix";1611        if (exec.nixosConfigEnablesFeatures(gpa, io, conf_path)) {1612            output.setupNixosNeedsRebuild(conf_path);1613            return;1614        }1615        output.setupNixosOffer(exec.NIXOS_FEATURES_LINE, conf_path);1616        if (output.confirmDefaultNo("add it now?")) {1617            if (exec.appendFeaturesToNixosConfig(gpa, io, environ, conf_path)) |_| {1618                output.setupNixosWrote(conf_path);1619            } else |_| {1620                output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);1621            }1622        } else {1623            output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);1624        }1625        return;1626    }16271628    // Non-NixOS: a user-level nix.conf takes effect immediately, no sudo needed.1629    output.setupEnabling();1630    const path = try exec.enableNixFeatures(gpa, io, environ);1631    defer gpa.free(path);16321633    output.setupDone(path);1634    api.ensureRegistryPinned(gpa, io, environ);1635}16361637// --- Log helper ---16381639fn logAction(ctx: Ctx, action: []const u8, gen: u32) void {1640    var ts_buf: [32]u8 = undefined;1641    const ts = nowIso(ctx.io, &ts_buf);1642    var buf: [256]u8 = undefined;1643    const entry = std.fmt.bufPrint(&buf, "{{\"ts\":\"{s}\",\"machine\":\"{s}\",\"command\":\"{s}\",\"outcome\":\"success\",\"gen_before\":null,\"gen_after\":{d},\"duration_ms\":0}}\n", .{1644        ts, ctx.machine.name, action, gen,1645    }) catch return;1646    exec.appendNinaLog(ctx.io, ctx.environ, entry);1647}16481649// Wall-clock UTC as ISO-8601. Uses Io.Clock.real (the settable Unix-epoch clock);1650// Io.Clock.awake is monotonic and unsuitable for timestamps. Falls back to epoch 0.1651fn nowIso(io: std.Io, buf: []u8) []const u8 {1652    const fallback = "1970-01-01T00:00:00Z";1653    const ns = std.Io.Clock.real.now(io).toNanoseconds();1654    if (ns <= 0) return fallback;1655    const secs: u64 = @intCast(@divFloor(ns, 1_000_000_000));1656    const es = std.time.epoch.EpochSeconds{ .secs = secs };1657    const ed = es.getEpochDay();1658    const yd = ed.calculateYearDay();1659    const md = yd.calculateMonthDay();1660    const ds = es.getDaySeconds();1661    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", .{1662        yd.year, md.month.numeric(), @as(u32, md.day_index) + 1,1663        ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(),1664    }) catch return fallback;1665}