commands.zig

61.4 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 current generation's references are its managed packages (plus a few1017    // home-manager scaffolding paths and versionless support outputs we skip).1018    const refs = exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, gens[0].path) catch return;1019    defer ctx.gpa.free(refs);1020    var lines = std.mem.splitScalar(u8, refs, '\n');1021    while (lines.next()) |line| {1022        const t = std.mem.trim(u8, line, " \t\r");1023        if (t.len == 0) continue;1024        const row = pkgFromStorePath(t);1025        if (row.version.len == 0) continue;1026        if (std.mem.indexOf(u8, row.name, "home-manager") != null) continue;1027        output.listPkg(row.name, row.version);1028    }1029}10301031fn homeDiff(ctx: Ctx) !void {1032    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1033    defer ctx.gpa.free(out);1034    const gens = try parseHomeGenerations(ctx.gpa, out);1035    defer freeHomeGens(ctx.gpa, gens);10361037    // Need two generations and both their store paths to diff their closures.1038    if (gens.len < 2 or gens[0].path.len == 0 or gens[1].path.len == 0) {1039        output.homeNothingToDiff();1040        return;1041    }1042    const newer = gens[0];1043    const older = gens[1];1044    output.homeDiffHeader(older.number, newer.number, ctx.machine.name);1045    if (try exec.diffClosuresPaths(ctx.io, &ctx.machine, ctx.gpa, older.path, newer.path) != 0)1046        return error.ProcessFailed;1047}10481049fn homeCheck(ctx: Ctx) !void {1050    output.homeCheckStart(ctx.machine.name);1051    const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa);1052    if (code != 0) {1053        output.checkFailed("");1054        return error.BuildFailed;1055    }1056    output.homeCheckOk();1057}10581059fn homeEdit(ctx: Ctx) !void {1060    // Standalone home config lives at ~/.config/home-manager/home.nix; the same1061    // path is what detection keys on for module mode, so it resolves for both.1062    const path = exec.homeNixPath(ctx.gpa, ctx.environ) orelse {1063        errors.error_info.setMessage("could not resolve ~/.config/home-manager/home.nix", .{});1064        return error.ConfigNotFound;1065    };1066    defer ctx.gpa.free(path);1067    output.homeEditOpen(path, ctx.cfg.editor);1068    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);1069}10701071fn homeHistory(ctx: Ctx) !void {1072    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1073    defer ctx.gpa.free(out);1074    const gens = try parseHomeGenerations(ctx.gpa, out);1075    defer freeHomeGens(ctx.gpa, gens);1076    output.homeHistoryHeader(ctx.machine.name);1077    // Newest-first from home-manager; the first row is the current generation.1078    for (gens, 0..) |g, i| output.homeHistoryRow(g.number, g.date, g.time, i == 0);1079}10801081fn homeBack(ctx: Ctx) !void {1082    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1083    defer ctx.gpa.free(out);1084    const gens = try parseHomeGenerations(ctx.gpa, out);1085    defer freeHomeGens(ctx.gpa, gens);10861087    // Newest-first: [0] is current, [1] is the generation to roll back to.1088    if (gens.len < 2) {1089        output.alreadyOldest();1090        return;1091    }1092    const current = gens[0].number;1093    const prev = gens[1].number;10941095    output.homeBackStart(ctx.machine.name, current, prev);1096    if (ctx.cfg.confirm and !output.confirm("")) return;1097    const code = try exec.homeManagerRollback(ctx.io, &ctx.machine, ctx.gpa);1098    if (code != 0) return error.BuildFailed;1099    output.homeBackDone(prev);1100}11011102fn homeApply(ctx: Ctx, mode: exec.HomeManagerMode) !void {1103    // NixOS/flake module: home config is rebuilt by nixos-rebuild — redirect.1104    if (mode == .module) {1105        output.homeModuleManaged();1106        return;1107    }1108    if (ctx.dry) {1109        output.homeApplyDry(ctx.machine.name);1110        const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa);1111        if (code != 0) return error.BuildFailed;1112        output.homeApplyDryDone();1113        return;1114    }11151116    output.homeApplyStart(ctx.machine.name);1117    const flake_ref = exec.homeFlakeRef(ctx.gpa, ctx.io, ctx.environ);1118    defer if (flake_ref) |r| ctx.gpa.free(r);1119    if (flake_ref) |ref| {1120        output.printSubstep("home-manager switch --flake {s}", .{ref});1121    } else {1122        output.printSubstep("home-manager switch", .{});1123    }11241125    const start = std.Io.Clock.awake.now(ctx.io);1126    const code = if (flake_ref) |ref|1127        try exec.homeManagerSwitchFlake(ctx.io, &ctx.machine, ctx.gpa, ref)1128    else1129        try exec.homeManagerSwitch(ctx.io, &ctx.machine, ctx.gpa);1130    if (code != 0) return error.BuildFailed;11311132    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());1133    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));1134    output.homeApplyDone(homeCurrentGen(ctx), elapsed);1135}11361137// --- Service commands ---11381139const service_help = [_][2][]const u8{1140    .{ "list", "list running services" },1141    .{ "logs <svc>", "show service logs" },1142    .{ "status <svc>", "service status" },1143    .{ "start <svc>", "start a service" },1144    .{ "stop <svc>", "stop a service" },1145    .{ "restart <svc>", "restart a service" },1146    .{ "enable <svc>", "enable at boot" },1147    .{ "disable <svc>", "disable at boot" },1148};11491150pub fn service(ctx: Ctx) !void {1151    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");1152    if (std.mem.eql(u8, ctx.sub, "list")) {1153        output.serviceListHeader(ctx.machine.name);1154        const svcs = exec.serviceList(ctx.gpa, ctx.io, &ctx.machine, ctx.user) catch &.{};1155        defer ctx.gpa.free(svcs);1156        for (svcs) |s| output.serviceRow(s);1157        return;1158    }1159    if (std.mem.eql(u8, ctx.sub, "logs")) {1160        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1161        const follow = ctx.args.len > 1 and std.mem.eql(u8, ctx.args[1], "-f");1162        output.serviceLogsHeader(name, ctx.last, ctx.machine.name);1163        _ = try exec.serviceLogs(ctx.io, &ctx.machine, ctx.gpa, name, ctx.last, follow, ctx.user);1164        return;1165    }1166    if (std.mem.eql(u8, ctx.sub, "status")) {1167        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1168        output.serviceVerb("status", name, ctx.machine.name);1169        _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, "status", name, ctx.user);1170        return;1171    }1172    // start/stop/restart/enable/disable1173    const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1174    if (ctx.cfg.confirm and (std.mem.eql(u8, ctx.sub, "stop") or std.mem.eql(u8, ctx.sub, "disable"))) {1175        if (!output.confirm("")) return;1176    }1177    output.serviceVerb(ctx.sub, name, ctx.machine.name);1178    _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, ctx.sub, name, ctx.user);1179    output.serviceDone();1180}11811182// --- Flake commands ---11831184const flake_help = [_][2][]const u8{1185    .{ "init", "create a new flake.nix" },1186    .{ "update", "update flake inputs" },1187    .{ "update <in>", "update a specific input" },1188    .{ "check", "validate the flake" },1189    .{ "show", "inspect flake outputs" },1190    .{ "lock", "regenerate flake.lock" },1191    .{ "clone <url>", "clone a flake repository" },1192};11931194pub fn flake(ctx: Ctx) !void {1195    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("flake", &flake_help, null);1196    if (std.mem.eql(u8, ctx.sub, "update")) {1197        output.flakeUpdateStart();1198        const input: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1199        _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1200        output.flakeLockWritten();1201        return;1202    }1203    if (std.mem.eql(u8, ctx.sub, "check")) {1204        output.flakeCheckStart();1205        const code = try exec.flakeCheck(ctx.io, &ctx.machine, ctx.gpa);1206        if (code == 0) output.flakeValid() else output.checkFailed("");1207        return;1208    }1209    if (std.mem.eql(u8, ctx.sub, "show")) {1210        const json_out = exec.flakeShow(ctx.gpa, ctx.io, &ctx.machine) catch null;1211        if (json_out) |j| {1212            defer ctx.gpa.free(j);1213            output.flakeShowHeader("flake outputs");1214            // Parse and display the flake outputs1215            const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, j, .{}) catch return;1216            defer parsed.deinit();1217            if (parsed.value == .object) {1218                var it = parsed.value.object.iterator();1219                while (it.next()) |entry| {1220                    if (entry.value_ptr.* == .object) {1221                        var inner = entry.value_ptr.object.iterator();1222                        while (inner.next()) |e2| {1223                            const desc = if (e2.value_ptr.* == .object)1224                                if (e2.value_ptr.object.get("description")) |d|1225                                    if (d == .string) d.string else ""1226                                else ""1227                            else "";1228                            output.flakeShowEntry(entry.key_ptr.*, e2.key_ptr.*, desc);1229                        }1230                    }1231                }1232            }1233        }1234        return;1235    }1236    if (std.mem.eql(u8, ctx.sub, "init")) {1237        _ = try exec.flakeInit(ctx.io, &ctx.machine, ctx.gpa);1238        return;1239    }1240    if (std.mem.eql(u8, ctx.sub, "lock")) {1241        _ = try exec.flakeLock(ctx.io, &ctx.machine, ctx.gpa);1242        return;1243    }1244    if (std.mem.eql(u8, ctx.sub, "clone")) {1245        const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1246        _ = try exec.flakeClone(ctx.io, &ctx.machine, ctx.gpa, url);1247        return;1248    }1249}12501251// --- Store commands ---12521253const store_help = [_][2][]const u8{1254    .{ "info", "store size and counts" },1255    .{ "path <attr>", "store path of a package" },1256    .{ "gc", "collect garbage" },1257    .{ "verify", "verify store integrity" },1258    .{ "repair", "repair corrupted paths" },1259};12601261pub fn store(ctx: Ctx) !void {1262    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("store", &store_help, null);1263    if (std.mem.eql(u8, ctx.sub, "gc")) {1264        _ = try exec.storeGc(ctx.io, &ctx.machine, ctx.gpa);1265        return;1266    }1267    if (std.mem.eql(u8, ctx.sub, "verify")) {1268        output.storeVerifyStart();1269        _ = try exec.storeVerify(ctx.io, &ctx.machine, ctx.gpa);1270        return;1271    }1272    if (std.mem.eql(u8, ctx.sub, "repair")) {1273        if (ctx.cfg.confirm and !output.confirm("")) return;1274        output.storeRepairStart();1275        _ = try exec.storeRepair(ctx.io, &ctx.machine, ctx.gpa);1276        return;1277    }1278    if (std.mem.eql(u8, ctx.sub, "info")) {1279        const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1280        output.storeInfo(si);1281        return;1282    }1283    if (std.mem.eql(u8, ctx.sub, "path")) {1284        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1285        const path = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, attr);1286        defer ctx.gpa.free(path);1287        output.storePath(path);1288        return;1289    }1290    // default: info1291    const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1292    output.storeInfo(si);1293}12941295// --- Channel commands ---12961297const channel_help = [_][2][]const u8{1298    .{ "list", "list channels" },1299    .{ "add <url> [name]", "add a channel" },1300    .{ "remove <name>", "remove a channel" },1301    .{ "update", "update all channels" },1302};13031304pub fn channel(ctx: Ctx) !void {1305    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("channel", &channel_help, null);1306    // On a flake-managed system, nix-channel operations generally don't apply.1307    if (flakeSystem(ctx)) output.flakeChannelNote();1308    if (std.mem.eql(u8, ctx.sub, "list")) {1309        output.channelListHeader(ctx.machine.name);1310        const chans = try exec.channelList(ctx.gpa, ctx.io, &ctx.machine);1311        defer ctx.gpa.free(chans);1312        for (chans) |ch| output.channelRow(ch);1313        return;1314    }1315    if (std.mem.eql(u8, ctx.sub, "add")) {1316        const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1317        const name = if (ctx.args.len > 1) ctx.args[1] else "";1318        _ = try exec.channelAdd(ctx.io, &ctx.machine, ctx.gpa, url, name);1319        output.channelDone();1320        return;1321    }1322    if (std.mem.eql(u8, ctx.sub, "remove")) {1323        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1324        _ = try exec.channelRemove(ctx.io, &ctx.machine, ctx.gpa, name);1325        output.channelDone();1326        return;1327    }1328    if (std.mem.eql(u8, ctx.sub, "update")) {1329        return channelUpdateCmd(ctx);1330    }1331}13321333// --- Profile commands ---13341335pub fn profile(ctx: Ctx) !void {1336    if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {1337        output.profileListHeader();1338        const out = exec.profileList(ctx.gpa, ctx.io, &ctx.machine) catch null;1339        if (out) |o| {1340            defer ctx.gpa.free(o);1341            var lines = std.mem.splitScalar(u8, o, '\n');1342            while (lines.next()) |line| {1343                const t = std.mem.trim(u8, line, " \t\r");1344                if (t.len == 0) continue;1345                output.profileRow(t, "", "");1346            }1347        }1348        return;1349    }1350    if (std.mem.eql(u8, ctx.sub, "install")) {1351        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1352        _ = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, attr);1353        output.done();1354        return;1355    }1356    if (std.mem.eql(u8, ctx.sub, "remove")) {1357        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1358        _ = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, attr);1359        output.done();1360        return;1361    }1362    if (std.mem.eql(u8, ctx.sub, "upgrade")) {1363        _ = try exec.profileUpgrade(ctx.io, &ctx.machine, ctx.gpa);1364        output.done();1365        return;1366    }1367}13681369// --- Pkg commands ---13701371const pkg_help = [_][2][]const u8{1372    .{ "why <pkg>", "what pulled it in" },1373    .{ "deps <pkg>", "direct dependencies" },1374    .{ "size <pkg>", "closure size" },1375    .{ "path <pkg>", "store path" },1376    .{ "closure <pkg>", "full closure" },1377};13781379pub fn pkg(ctx: Ctx) !void {1380    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("pkg", &pkg_help, null);1381    const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1382    if (std.mem.eql(u8, ctx.sub, "why")) {1383        _ = try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name);1384        return;1385    }1386    if (std.mem.eql(u8, ctx.sub, "deps")) {1387        _ = try exec.pkgDeps(ctx.io, &ctx.machine, ctx.gpa, name);1388        return;1389    }1390    if (std.mem.eql(u8, ctx.sub, "size")) {1391        const s = exec.pkgSize(ctx.gpa, ctx.io, &ctx.machine, name) catch null;1392        if (s) |sz| {1393            defer ctx.gpa.free(sz);1394            output.pkgResult("size", sz);1395        }1396        return;1397    }1398    if (std.mem.eql(u8, ctx.sub, "path")) {1399        const p = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, name);1400        defer ctx.gpa.free(p);1401        output.pkgResult("path", p);1402        return;1403    }1404    if (std.mem.eql(u8, ctx.sub, "closure")) {1405        _ = try exec.pkgClosure(ctx.io, &ctx.machine, ctx.gpa, name);1406        return;1407    }1408}14091410// Top-level alias for `nina pkg why <pkg>` — surfaces what pulled a package in1411// without the user needing to know about the `pkg` subgroup.1412pub fn why(ctx: Ctx) !void {1413    const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1414    _ = try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name);1415}14161417// --- Pin / Unpin ---14181419pub fn pin(ctx: Ctx) !void {1420    const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1421    const commit = if (ctx.args.len > 1) ctx.args[1] else return error.Internal;1422    exec.editFlakeLock(ctx.gpa, input, commit) catch return error.ProcessFailed;1423    output.pinDone(input, commit);1424}14251426pub fn unpin(ctx: Ctx) !void {1427    const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1428    _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1429    output.unpinDone(input);1430}14311432// --- Hash / Fetch ---14331434pub fn hash(ctx: Ctx) !void {1435    const path = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1436    const h = try exec.nixHash(ctx.gpa, ctx.io, &ctx.machine, path);1437    defer ctx.gpa.free(h);1438    output.hashResult(std.mem.trim(u8, h, " \t\n\r"));1439}14401441pub fn fetch(ctx: Ctx) !void {1442    const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1443    const h = try exec.nixFetch(ctx.gpa, ctx.io, &ctx.machine, url);1444    defer ctx.gpa.free(h);1445    output.fetchResult(std.mem.trim(u8, h, " \t\n\r"), url);1446}14471448// --- Build / Run ---14491450pub fn build(ctx: Ctx) !void {1451    const attr: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1452    output.buildStart(attr orelse "default");1453    const code = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, attr);1454    if (code != 0) return error.BuildFailed;1455    output.buildDone();1456}14571458pub fn runCmd(ctx: Ctx) !void {1459    const pkg_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1460    output.runStart(pkg_arg);1461    _ = try exec.nixRun(ctx.io, &ctx.machine, ctx.gpa, pkg_arg);1462}14631464// --- Hello ---14651466pub fn hello(ctx: Ctx) !void {1467    output.hello(ctx.cfg.machines);1468}14691470// Runs when ~/.nina.conf is absent on first invocation (interactive TTY only).1471// Prompts for machine name, config path, and local flag, then writes the file.1472pub fn firstRunWizard(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1473    output.firstRunBanner();1474    output.firstRunNoConfig();14751476    var name_buf: [256]u8 = undefined;1477    var path_buf: [256]u8 = undefined;1478    var local_buf: [256]u8 = undefined;14791480    const machine_name = output.firstRunPrompt("machine name", "my-machine", &name_buf);14811482    // Flake-based systems don't have a traditional /etc/nixos/configuration.nix —1483    // their config lives wherever flake.nix is. Ask, then prompt for the right1484    // path and record `flake = true` so channel commands can warn appropriately.1485    const use_flakes = output.firstRunManageType();1486    const config_path = if (use_flakes)1487        output.firstRunPrompt("flake directory", "~/nixos-config", &path_buf)1488    else1489        output.firstRunPrompt("config path", "/etc/nixos", &path_buf);1490    const local_str = output.firstRunPrompt("local", "true", &local_buf);14911492    const conf_path = try config.configPath(gpa, environ);1493    defer gpa.free(conf_path);1494    if (std.fs.path.dirname(conf_path)) |dir| exec.ensureDir(gpa, io, dir);14951496    // `flake` is a top-level config field, so it must precede the [machine] block.1497    const flake_line = if (use_flakes) "flake = true\n" else "";1498    var content_buf: [1024]u8 = undefined;1499    const content = try std.fmt.bufPrint(1500        &content_buf,1501        "{s}[machine]\nname = {s}\nconfig = {s}\nlocal = {s}\n",1502        .{ flake_line, machine_name, config_path, local_str },1503    );15041505    const file = std.Io.Dir.createFile(.cwd(), io, conf_path, .{}) catch {1506        errors.error_info.setMessage("could not write {s}", .{conf_path});1507        return error.Internal;1508    };1509    defer file.close(io);1510    file.writePositionalAll(io, content, 0) catch {1511        errors.error_info.setMessage("could not write {s}", .{conf_path});1512        return error.Internal;1513    };15141515    output.firstRunWritten(conf_path);1516}15171518pub fn setup(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1519    // Create the config first if it doesn't exist. This makes `nina setup`1520    // a complete onboarding command — not just a nix-features check. Any legacy1521    // ~/.nina.conf is migrated to the XDG path before we decide to run the wizard.1522    config.migrateLegacyConfig(gpa, io, environ);1523    if (config.configPath(gpa, environ)) |conf_path| {1524        defer gpa.free(conf_path);1525        if (std.Io.Dir.openFile(.cwd(), io, conf_path, .{})) |f| {1526            f.close(io);1527        } else |_| {1528            try firstRunWizard(gpa, io, environ);1529            errors.error_info.reset();1530        }1531    } else |_| {}15321533    output.setupCheck();1534    const status = exec.checkNixFeatures(gpa, io, environ);1535    output.setupFeatures(status.nix_command, status.flakes);15361537    if (status.allEnabled()) {1538        output.setupAllSet();1539        api.ensureRegistryPinned(gpa, io, environ);1540        return;1541    }15421543    // On NixOS the features belong in configuration.nix (the declarative,1544    // permanent home), not ~/.config/nix/nix.conf. Offer to add the one line;1545    // the user runs the rebuild. We don't pin the registry here because the1546    // features aren't live until that rebuild lands.1547    if (exec.isNixOS(io)) {1548        const conf_path = "/etc/nixos/configuration.nix";1549        if (exec.nixosConfigEnablesFeatures(gpa, io, conf_path)) {1550            output.setupNixosNeedsRebuild(conf_path);1551            return;1552        }1553        output.setupNixosOffer(exec.NIXOS_FEATURES_LINE, conf_path);1554        if (output.confirmDefaultNo("add it now?")) {1555            if (exec.appendFeaturesToNixosConfig(gpa, io, environ, conf_path)) |_| {1556                output.setupNixosWrote(conf_path);1557            } else |_| {1558                output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);1559            }1560        } else {1561            output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);1562        }1563        return;1564    }15651566    // Non-NixOS: a user-level nix.conf takes effect immediately, no sudo needed.1567    output.setupEnabling();1568    const path = try exec.enableNixFeatures(gpa, io, environ);1569    defer gpa.free(path);15701571    output.setupDone(path);1572    api.ensureRegistryPinned(gpa, io, environ);1573}15741575// --- Log helper ---15761577fn logAction(ctx: Ctx, action: []const u8, gen: u32) void {1578    var ts_buf: [32]u8 = undefined;1579    const ts = nowIso(ctx.io, &ts_buf);1580    var buf: [256]u8 = undefined;1581    const entry = std.fmt.bufPrint(&buf, "{{\"ts\":\"{s}\",\"machine\":\"{s}\",\"command\":\"{s}\",\"outcome\":\"success\",\"gen_before\":null,\"gen_after\":{d},\"duration_ms\":0}}\n", .{1582        ts, ctx.machine.name, action, gen,1583    }) catch return;1584    exec.appendNinaLog(ctx.io, ctx.environ, entry);1585}15861587// Wall-clock UTC as ISO-8601. Uses Io.Clock.real (the settable Unix-epoch clock);1588// Io.Clock.awake is monotonic and unsuitable for timestamps. Falls back to epoch 0.1589fn nowIso(io: std.Io, buf: []u8) []const u8 {1590    const fallback = "1970-01-01T00:00:00Z";1591    const ns = std.Io.Clock.real.now(io).toNanoseconds();1592    if (ns <= 0) return fallback;1593    const secs: u64 = @intCast(@divFloor(ns, 1_000_000_000));1594    const es = std.time.epoch.EpochSeconds{ .secs = secs };1595    const ed = es.getEpochDay();1596    const yd = ed.calculateYearDay();1597    const md = yd.calculateMonthDay();1598    const ds = es.getDaySeconds();1599    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", .{1600        yd.year, md.month.numeric(), @as(u32, md.day_index) + 1,1601        ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(),1602    }) catch return fallback;1603}