commands.zig

60.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    }263    output.doctorSummary(warnings, failures);264}265266// nina update — kepr self-update for the nina binary itself.267pub fn update(ctx: Ctx) !void {268    output.updateSelfStart();269270    if (comptime std.mem.eql(u8, version.PLATFORM, "unsupported")) {271        output.updateSelfNoPlatform(@tagName(builtin.cpu.arch) ++ "-" ++ @tagName(builtin.os.tag));272        return error.Internal;273    }274275    const env_url = ctx.environ.get("NINA_UPDATE_SOURCE");276    const source_url = env_url orelse UPDATE_URL;277278    const body = exec.fetchUrl(ctx.gpa, ctx.io, source_url) catch |e| switch (e) {279        error.NetworkError, error.HttpError => {280            output.updateSelfNetworkError();281            return;282        },283        else => return e,284    };285    defer ctx.gpa.free(body);286287    const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, body, .{}) catch {288        output.printWarning("could not parse release metadata");289        return;290    };291    defer parsed.deinit();292293    const root = parsed.value;294    if (root != .object) { output.printWarning("malformed release metadata"); return; }295296    const remote_ver = blk: {297        const v = root.object.get("version") orelse { output.printWarning("malformed release metadata"); return; };298        break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };299    };300301    if (std.mem.eql(u8, remote_ver, version.VERSION)) {302        output.updateSelfCurrent(version.VERSION);303        return;304    }305306    output.updateSelfAvailable(version.VERSION, remote_ver);307    if (ctx.check) return;308309    var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;310    const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {311        errors.error_info.setMessage("could not determine install path", .{});312        return error.Internal;313    };314315    // When running from the nix store, defer to nix profile upgrade so nix316    // manages the transition (the store is read-only; binary replacement fails).317    // A NixOS system install also resolves into the store but isn't a profile318    // element, so check the profile to avoid a no-op `upgrade` — it updates with319    // the next nixos-rebuild instead.320    if (std.mem.startsWith(u8, install_path, "/nix/store/")) {321        const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);322        defer {323            if (nina_element) |n| ctx.gpa.free(n);324        }325        if (nina_element == null) {326            output.updateSelfNotInProfile();327            return;328        }329        const element = nina_element.?;330        output.updateSelfNixManaged(remote_ver);331        if (ctx.cfg.confirm and !output.confirm("")) return;332        const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "upgrade", element }) catch {333            output.updateSelfNixFailed();334            return;335        };336        if (ec != 0) output.updateSelfNixFailed();337        return;338    }339340    const plat_info = blk: {341        const pv = root.object.get("platforms") orelse break :blk null;342        if (pv != .object) break :blk null;343        break :blk pv.object.get(version.PLATFORM);344    };345    if (plat_info == null) { output.updateSelfNoPlatform(version.PLATFORM); return; }346347    const dl_url = blk: {348        const v = plat_info.?.object.get("url") orelse { output.printWarning("malformed release metadata"); return; };349        break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };350    };351352    const raw_cksum = blk: {353        if (plat_info.?.object.get("blake3")) |v|354            break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };355        if (plat_info.?.object.get("checksum")) |v|356            break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };357        output.printWarning("missing checksum in release metadata");358        return;359    };360    const expected_hex = if (std.mem.startsWith(u8, raw_cksum, "blake3:")) raw_cksum["blake3:".len..] else raw_cksum;361362    if (ctx.cfg.confirm and !output.confirm("")) return;363364    output.updateSelfDownloading(remote_ver, version.PLATFORM);365    const tmp_path = exec.downloadToTemp(ctx.gpa, ctx.io, dl_url) catch {366        output.printWarning("download failed — check your connection and try again");367        return;368    };369    defer ctx.gpa.free(tmp_path);370371    output.updateSelfVerifying();372    exec.verifyAndInstall(ctx.gpa, ctx.io, tmp_path, expected_hex, install_path) catch |e| switch (e) {373        error.ChecksumMismatch => { output.updateSelfChecksumFailed(); return; },374        else => return e,375    };376377    output.updateSelfDone(version.VERSION, remote_ver);378}379380// nina goodbye — clean uninstall. Three install paths:381// - nix profile (binary in nix store with a profile element) → nix profile remove382// - koh build or source build (plain binary on PATH) → delete the file383pub fn goodbye(ctx: Ctx) !void {384    output.goodbyeStart();385386    var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;387    const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {388        errors.error_info.setMessage("could not determine install path", .{});389        return error.Internal;390    };391392    // A binary outside the nix store is a koh build or source build — delete it.393    if (!std.mem.startsWith(u8, install_path, "/nix/store/")) {394        output.goodbyeFile(install_path);395        if (ctx.cfg.confirm and !output.confirm("")) return;396        std.Io.Dir.deleteFileAbsolute(ctx.io, install_path) catch |e| {397            errors.error_info.setMessage("could not remove {s}", .{install_path});398            return e;399        };400        output.goodbyeDone();401        return;402    }403404    // Binary is in the nix store — find and remove the profile element.405    const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);406    defer {407        if (nina_element) |n| ctx.gpa.free(n);408    }409410    if (nina_element == null) {411        errors.error_info.setMessage("nina not found in nix profile — was it installed via 'nix profile add'?", .{});412        return error.Internal;413    }414415    output.goodbyeNix();416    if (ctx.cfg.confirm and !output.confirm("")) return;417    const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "remove", nina_element.? }) catch {418        output.goodbyeFailed("nix profile remove failed");419        return;420    };421    if (ec != 0) {422        output.goodbyeFailed("nix profile remove failed");423        return;424    }425    output.goodbyeDone();426}427428fn channelUpdateCmd(ctx: Ctx) !void {429    output.updateStart(ctx.machine.name);430    _ = try exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa);431    output.updateDone();432}433434pub fn upgrade(ctx: Ctx) !void {435    output.upgradeStart(ctx.machine.name);436    output.printSubstep("updating channels", .{});437    _ = exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa) catch {};438    output.printSubstep("rebuilding", .{});439    const start = std.Io.Clock.awake.now(ctx.io);440    const code = try exec.nixosRebuildSwitch(ctx.io, &ctx.machine, ctx.gpa);441    if (code != 0) {442        output.applyFailed("");443        return error.BuildFailed;444    }445    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());446    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));447    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;448    output.applyDone(gen, elapsed, false);449}450451pub fn log(ctx: Ctx) !void {452    output.logHeader(ctx.machine.name);453    const content = exec.readNinaLog(ctx.gpa, ctx.io, ctx.environ, ctx.last) catch {454        // No log yet — that's fine455        return;456    };457    defer ctx.gpa.free(content);458    var lines = std.mem.splitScalar(u8, content, '\n');459    while (lines.next()) |line| {460        const t = std.mem.trim(u8, line, " \t\r");461        if (t.len == 0) continue;462        if (t[0] == '{') {463            renderJsonLogLine(ctx.gpa, t);464        } else {465            // legacy tab-separated format466            var parts = std.mem.tokenizeScalar(u8, t, '\t');467            const date = parts.next() orelse continue;468            const time = parts.next() orelse "";469            const action = parts.next() orelse "";470            const detail = parts.next() orelse "";471            output.logRow(date, time, action, detail);472        }473    }474}475476// The on-disk log is JSON Lines: {"ts","machine","command","outcome","gen_after",...}.477// Render ts -> date/time columns, command -> action, outcome(+gen) -> detail.478fn renderJsonLogLine(gpa: std.mem.Allocator, line: []const u8) void {479    const parsed = std.json.parseFromSlice(std.json.Value, gpa, line, .{}) catch {480        output.logRow(line, "", "", ""); // unparseable — show raw rather than drop481        return;482    };483    defer parsed.deinit();484    if (parsed.value != .object) return;485    const o = parsed.value.object;486487    const ts = jsonStr(o, "ts");488    const date = if (ts.len >= 10) ts[0..10] else ts;489    const time = if (ts.len >= 16) ts[11..16] else "";490    const action = jsonStr(o, "command");491    const outcome = jsonStr(o, "outcome");492493    var buf: [160]u8 = undefined;494    var detail: []const u8 = outcome;495    if (o.get("gen_after")) |g| {496        if (g == .integer) {497            detail = std.fmt.bufPrint(&buf, "{s}   -> gen {d}", .{ outcome, g.integer }) catch outcome;498        }499    }500    output.logRow(date, time, action, detail);501}502503fn jsonStr(o: std.json.ObjectMap, key: []const u8) []const u8 {504    if (o.get(key)) |v| {505        if (v == .string) return v.string;506    }507    return "";508}509510pub fn edit(ctx: Ctx) !void {511    const hardware = ctx.args.len > 0 and std.mem.eql(u8, ctx.args[0], "hardware");512    const filename = if (hardware) "hardware-configuration.nix" else "configuration.nix";513    const path = try std.fmt.allocPrint(ctx.gpa, "{s}/{s}", .{ ctx.machine.config_path, filename });514    defer ctx.gpa.free(path);515    output.editOpen(path, ctx.cfg.editor);516    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);517}518519pub fn fmt(ctx: Ctx) !void {520    const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});521    defer ctx.gpa.free(path);522    if (ctx.check) {523        const code = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, true);524        if (code != 0) output.fmtNeedsFormat() else output.fmtDone();525        return;526    }527    output.fmtStart(path);528    _ = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, false);529    output.fmtDone();530}531532pub fn repl(ctx: Ctx) !void {533    output.replStart();534    _ = try exec.nixRepl(ctx.io, &ctx.machine, ctx.gpa);535}536537pub fn develop(ctx: Ctx) !void {538    if (std.mem.eql(u8, ctx.sub, "show")) {539        _ = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, null);540        return;541    }542    const run_cmd: ?[]const u8 = if (ctx.args.len > 0 and std.mem.eql(u8, ctx.sub, "run"))543        ctx.args[0]544    else545        null;546    output.developStart(&.{});547    _ = try exec.nixDevelopPs1(ctx.io, &ctx.machine, ctx.gpa, run_cmd, ctx.environ);548    output.developDone();549}550551pub fn info(ctx: Ctx) !void {552    output.infoHeader(ctx.machine.name);553    const nixos_ver = exec.systemInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");554    defer ctx.gpa.free(nixos_ver);555    output.infoRow("nixos", std.mem.trim(u8, nixos_ver, " \t\n\r"));556557    const kernel = exec.kernelInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");558    defer ctx.gpa.free(kernel);559    output.infoRow("kernel", std.mem.trim(u8, kernel, " \t\n\r"));560561    const uptime = exec.uptimeInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");562    defer ctx.gpa.free(uptime);563    output.infoRow("uptime", std.mem.trim(u8, uptime, " \t\n\r"));564}565566pub fn boot(ctx: Ctx) !void {567    output.bootHeader(ctx.machine.name);568    const entries = exec.bootEntries(ctx.gpa, ctx.io, &ctx.machine) catch &.{};569    defer ctx.gpa.free(entries);570    for (entries, 0..) |entry, i| output.bootEntry(entry, i);571}572573pub fn searchCmd(ctx: Ctx) !void {574    const query = if (ctx.args.len > 0) ctx.args[0] else "";575    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);576    const selected = try search_tui.run(ctx.gpa, ctx.io, query, .packages);577    if (selected) |npkg| try selectAndInstall(ctx, npkg);578}579580pub fn optionCmd(ctx: Ctx) !void {581    const query = if (ctx.args.len > 0) ctx.args[0] else "";582    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);583    _ = try search_tui.run(ctx.gpa, ctx.io, query, .options);584}585586pub fn install(ctx: Ctx) !void {587    const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;588589    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);590591    // Search for the package to get the attr592    const pkgs = api.searchPackages(ctx.gpa, ctx.io, pkg_name) catch {593        errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});594        errors.error_info.setSuggestion("nina search {s}", .{pkg_name});595        return error.PackageNotFound;596    };597598    if (pkgs.len == 0) {599        // No matches — likely a typo. Suggest the closest real package and offer it.600        if (closestPackage(ctx, pkg_name)) |sugg| {601            output.didYouMean(pkg_name, sugg.pname);602            if (output.confirm("")) try selectAndInstall(ctx, sugg);603            return;604        }605        errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});606        errors.error_info.setSuggestion("nina search {s}", .{pkg_name});607        return error.PackageNotFound;608    }609610    // Prefer an exact name match over the first search result — `install ripgrep`611    // must pick "ripgrep", not the alphabetically-first match like "repgrep".612    var found = pkgs[0];613    for (pkgs) |p| {614        if (std.mem.eql(u8, p.pname, pkg_name)) {615            found = p;616            break;617        }618    }619    try selectAndInstall(ctx, found);620}621622// Find the real package whose name is closest to a not-found query (typo help).623// Typos usually keep the leading characters, so gather candidates with a prefix624// search and rank by edit distance; return the best only if it's typo-close.625fn closestPackage(ctx: Ctx, query: []const u8) ?types.NixPackage {626    if (query.len < 2) return null;627    var candidates = api.searchPackages(ctx.gpa, ctx.io, query[0..@min(query.len, 4)]) catch &.{};628    if (candidates.len == 0 and query.len > 2) {629        candidates = api.searchPackages(ctx.gpa, ctx.io, query[0..2]) catch &.{};630    }631    if (candidates.len == 0) return null;632633    var best: ?types.NixPackage = null;634    var best_dist: usize = std.math.maxInt(usize);635    for (candidates) |p| {636        const d = editDistance(query, p.pname);637        if (d > 0 and d < best_dist) {638            best_dist = d;639            best = p;640        }641    }642    // Only suggest a genuinely close name, scaled to query length.643    const threshold = @max(@as(usize, 2), query.len / 3);644    return if (best_dist <= threshold) best else null;645}646647// Case-insensitive Levenshtein distance. Names longer than the row buffer are648// treated as far away (never suggested).649fn editDistance(a: []const u8, b: []const u8) usize {650    const n = b.len;651    if (a.len == 0) return n;652    if (n == 0) return a.len;653    if (n + 1 > 128) return std.math.maxInt(usize);654    var prev: [128]usize = undefined;655    var curr: [128]usize = undefined;656    var j: usize = 0;657    while (j <= n) : (j += 1) prev[j] = j;658    var i: usize = 1;659    while (i <= a.len) : (i += 1) {660        curr[0] = i;661        j = 1;662        while (j <= n) : (j += 1) {663            const cost: usize = if (std.ascii.toLower(a[i - 1]) == std.ascii.toLower(b[j - 1])) 0 else 1;664            curr[j] = @min(prev[j] + 1, @min(curr[j - 1] + 1, prev[j - 1] + cost));665        }666        @memcpy(prev[0 .. n + 1], curr[0 .. n + 1]);667    }668    return prev[n];669}670671test "editDistance is case-insensitive Levenshtein" {672    try std.testing.expectEqual(@as(usize, 1), editDistance("firefux", "firefox"));673    try std.testing.expectEqual(@as(usize, 0), editDistance("git", "GIT"));674    try std.testing.expectEqual(@as(usize, 2), editDistance("fierfox", "firefox"));675    try std.testing.expectEqual(@as(usize, 7), editDistance("", "firefox"));676}677678// Prompt for the install method (profile / system / try) and dispatch. Shared by679// `nina install <pkg>` and the search widget's Enter-to-select — the letter keys680// are read here, after the search widget's raw mode is gone, so they don't681// collide with typing a query.682fn selectAndInstall(ctx: Ctx, npkg: types.NixPackage) !void {683    output.installSelectPrompt(npkg.pname, npkg.version);684685    var choice_buf: [8]u8 = undefined;686    var choice_len: usize = 0;687    while (choice_len < choice_buf.len) {688        const n = std.posix.read(std.posix.STDIN_FILENO, choice_buf[choice_len .. choice_len + 1]) catch break;689        if (n == 0) break;690        if (choice_buf[choice_len] == '\n') break;691        choice_len += 1;692    }693    const choice = std.mem.trim(u8, choice_buf[0..choice_len], " \t");694695    if (choice.len == 0 or choice[0] == 'i' or choice[0] == 'I') {696        try profileInstallPkg(ctx, npkg);697    } else if (choice[0] == 's' or choice[0] == 'S') {698        try systemInstallPkg(ctx, npkg);699    } else if (choice[0] == 't' or choice[0] == 'T') {700        try tryPkg(ctx, npkg);701    }702}703704fn profileInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {705    output.installStart(npkg.pname, .profile);706    output.printSubstep("nix profile add nixpkgs#{s}", .{npkg.attr});707    output.printTeach(try std.fmt.allocPrint(ctx.gpa, "nix profile add nixpkgs#{s}", .{npkg.attr}));708    const code = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, npkg.attr);709    if (code != 0) return error.ProcessFailed;710    output.installDone(npkg.pname);711}712713fn systemInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {714    const config_path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});715    defer ctx.gpa.free(config_path);716    const line = api.findSystemPackagesLine(ctx.io, config_path) orelse 1;717    output.installEditorPrompt(npkg.pname, config_path, line, ctx.cfg.editor);718    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, config_path, line);719    if (ctx.cfg.confirm) {720        if (output.confirm("apply now? ")) {721            try apply(ctx);722        }723    }724}725726fn tryPkg(ctx: Ctx, npkg: types.NixPackage) !void {727    output.tryStart(npkg.pname);728    output.printSubstep("nix shell nixpkgs#{s}", .{npkg.attr});729    output.tryExitHint();730    _ = try exec.nixShellPs1(ctx.io, &ctx.machine, ctx.gpa, npkg.attr, ctx.environ);731    output.tryDone();732}733734pub fn remove(ctx: Ctx) !void {735    const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;736    output.removeStart(pkg_name);737    const code = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, pkg_name);738    if (code != 0) return error.ProcessFailed;739    output.done();740}741742pub fn list(ctx: Ctx) !void {743    output.listHeader(ctx.machine.name);744745    // Profile packages: parse `nix profile list --json` into clean name+version746    // rows instead of dumping nix's verbose multi-line "Name:/Flake attribute:"747    // blocks.748    if (exec.profileListJson(ctx.gpa, ctx.io, &ctx.machine) catch null) |json| {749        defer ctx.gpa.free(json);750        output.listSection("profile");751        renderProfileJson(ctx.gpa, json);752    }753754    // System packages: the references of /run/current-system/sw, each a755    // <hash>-<name>-<version> store path.756    if (exec.systemPackagePaths(ctx.gpa, ctx.io, &ctx.machine) catch null) |paths| {757        defer ctx.gpa.free(paths);758        output.blankLine();759        output.listSection("system");760        var lines = std.mem.splitScalar(u8, paths, '\n');761        while (lines.next()) |line| {762            const t = std.mem.trim(u8, line, " \t\r");763            if (t.len == 0) continue;764            const row = pkgFromStorePath(t);765            // Skip support paths with no parseable version (man pages, wrappers).766            if (row.version.len == 0) continue;767            output.listPkg(row.name, row.version);768        }769    }770}771772const PkgRow = struct { name: []const u8, version: []const u8 };773774// Split a nix store path basename (<hash>-<name>-<version>) into name + version.775// Version begins at the first '-' followed by a digit, which reliably lands on776// the name/version boundary since the 32-char hash and package names start with777// non-digits.778fn pkgFromStorePath(path: []const u8) PkgRow {779    const base = std.fs.path.basename(path);780    const after_hash = if (base.len > 33 and base[32] == '-') base[33..] else base;781    var i: usize = 0;782    while (i + 1 < after_hash.len) : (i += 1) {783        if (after_hash[i] == '-' and std.ascii.isDigit(after_hash[i + 1])) {784            return .{ .name = after_hash[0..i], .version = stripOutputSuffix(after_hash[i + 1 ..]) };785        }786    }787    return .{ .name = after_hash, .version = "" };788}789790// Multi-output derivations append the output name to the store path (e.g.791// curl-8.20.0-bin, less-692-man). Strip that suffix so the version column reads792// as just the version.793fn stripOutputSuffix(ver: []const u8) []const u8 {794    const suffixes = [_][]const u8{ "-bin", "-man", "-dev", "-doc", "-lib", "-info", "-out", "-static", "-devdoc" };795    for (suffixes) |s| {796        if (std.mem.endsWith(u8, ver, s)) return ver[0 .. ver.len - s.len];797    }798    return ver;799}800801test "pkgFromStorePath splits name and version at first dash-digit" {802    const a = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-ripgrep-15.1.0");803    try std.testing.expectEqualStrings("ripgrep", a.name);804    try std.testing.expectEqualStrings("15.1.0", a.version);805806    const b = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-helix-25.01");807    try std.testing.expectEqualStrings("helix", b.name);808    try std.testing.expectEqualStrings("25.01", b.version);809810    // multi-output store paths drop their output-name suffix811    const c = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-curl-8.20.0-bin");812    try std.testing.expectEqualStrings("curl", c.name);813    try std.testing.expectEqualStrings("8.20.0", c.version);814}815816fn firstStorePath(el: std.json.Value) ?[]const u8 {817    if (el != .object) return null;818    const sp = el.object.get("storePaths") orelse return null;819    if (sp != .array or sp.array.items.len == 0) return null;820    const first = sp.array.items[0];821    return if (first == .string) first.string else null;822}823824// `nix profile list --json` has two shapes across nix versions: newer keys each825// element by name (object), older lists them positionally (array). Handle both.826fn renderProfileJson(gpa: std.mem.Allocator, json: []const u8) void {827    const parsed = std.json.parseFromSlice(std.json.Value, gpa, json, .{}) catch return;828    defer parsed.deinit();829    if (parsed.value != .object) return;830    const elements = parsed.value.object.get("elements") orelse return;831    switch (elements) {832        .object => |obj| {833            var it = obj.iterator();834            while (it.next()) |entry| {835                const ver = if (firstStorePath(entry.value_ptr.*)) |p| pkgFromStorePath(p).version else "";836                output.listPkg(entry.key_ptr.*, ver);837            }838        },839        .array => |arr| {840            for (arr.items) |el| {841                const path = firstStorePath(el) orelse continue;842                const row = pkgFromStorePath(path);843                output.listPkg(row.name, row.version);844            }845        },846        else => {},847    }848}849850pub fn tryCmd(ctx: Ctx) !void {851    const pkg_name_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;852    const shell_pkg = types.NixPackage{ .attr = pkg_name_arg, .pname = pkg_name_arg, .version = "", .description = "" };853    try tryPkg(ctx, shell_pkg);854}855856// --- Home Manager commands ---857858const home_help = [_][2][]const u8{859    .{ "apply", "apply home manager configuration" },860    .{ "apply --dry", "preview changes" },861    .{ "back", "roll back one generation" },862    .{ "history", "list all generations" },863    .{ "edit", "open home.nix" },864    .{ "check", "validate without applying" },865    .{ "diff", "changes between generations" },866    .{ "packages", "list managed packages" },867};868869const HomeGen = struct {870    number: u32,871    date: []const u8,872    time: []const u8,873    path: []const u8,874};875876// `home-manager generations` lines read:877//   2026-06-01 11:56 : id 765 -> /nix/store/<hash>-home-manager-generation878// Newest first, so index 0 is the current generation.879fn parseHomeGenerations(gpa: std.mem.Allocator, out_str: []const u8) ![]HomeGen {880    var gens: std.ArrayList(HomeGen) = .empty;881    var lines = std.mem.splitScalar(u8, out_str, '\n');882    while (lines.next()) |line| {883        const t = std.mem.trim(u8, line, " \t\r");884        if (t.len == 0) continue;885        var it = std.mem.tokenizeAny(u8, t, " \t");886        const date = it.next() orelse continue;887        const time = it.next() orelse continue;888        var number: ?u32 = null;889        var path: []const u8 = "";890        while (it.next()) |tok| {891            if (std.mem.eql(u8, tok, "id")) {892                if (it.next()) |n| number = std.fmt.parseInt(u32, n, 10) catch null;893            } else if (std.mem.startsWith(u8, tok, "/nix/store/")) {894                path = tok;895            }896        }897        const num = number orelse continue;898        try gens.append(gpa, .{899            .number = num,900            .date = try gpa.dupe(u8, date),901            .time = try gpa.dupe(u8, time),902            .path = try gpa.dupe(u8, path),903        });904    }905    return gens.toOwnedSlice(gpa);906}907908fn freeHomeGens(gpa: std.mem.Allocator, gens: []HomeGen) void {909    for (gens) |g| {910        gpa.free(g.date);911        gpa.free(g.time);912        gpa.free(g.path);913    }914    gpa.free(gens);915}916917test "parseHomeGenerations reads id, date and store path" {918    const a = std.testing.allocator;919    const sample =920        \\2026-06-01 11:56 : id 765 -> /nix/store/aaaa-home-manager-generation921        \\2026-05-31 10:29 : id 764 -> /nix/store/bbbb-home-manager-generation922    ;923    const gens = try parseHomeGenerations(a, sample);924    defer freeHomeGens(a, gens);925    try std.testing.expectEqual(@as(usize, 2), gens.len);926    try std.testing.expectEqual(@as(u32, 765), gens[0].number);927    try std.testing.expectEqualStrings("2026-06-01", gens[0].date);928    try std.testing.expectEqualStrings("11:56", gens[0].time);929    try std.testing.expectEqualStrings("/nix/store/aaaa-home-manager-generation", gens[0].path);930    try std.testing.expectEqual(@as(u32, 764), gens[1].number);931}932933// Current (newest) home generation number, or 0 if unavailable.934fn homeCurrentGen(ctx: Ctx) u32 {935    const out = exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine) catch return 0;936    defer ctx.gpa.free(out);937    const gens = parseHomeGenerations(ctx.gpa, out) catch return 0;938    defer freeHomeGens(ctx.gpa, gens);939    return if (gens.len > 0) gens[0].number else 0;940}941942pub fn home(ctx: Ctx) !void {943    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help"))944        return output.subcommandHelp("home", &home_help, null);945946    const mode = exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ);947    if (mode == .none) {948        output.homeNotInstalled();949        return;950    }951952    // apply is the only command meaningful in module mode (it redirects to953    // `nina apply`); everything else needs the standalone home-manager CLI.954    if (std.mem.eql(u8, ctx.sub, "apply")) return homeApply(ctx, mode);955    // edit just opens the local home.nix — fine in module mode too.956    if (std.mem.eql(u8, ctx.sub, "edit")) return homeEdit(ctx);957958    if (mode == .module) {959        output.homeModuleManaged();960        return;961    }962963    if (std.mem.eql(u8, ctx.sub, "back")) return homeBack(ctx);964    if (std.mem.eql(u8, ctx.sub, "history")) return homeHistory(ctx);965    if (std.mem.eql(u8, ctx.sub, "check")) return homeCheck(ctx);966    if (std.mem.eql(u8, ctx.sub, "diff")) return homeDiff(ctx);967    if (std.mem.eql(u8, ctx.sub, "packages")) return homePackages(ctx);968969    return output.subcommandHelp("home", &home_help, null);970}971972fn homePackages(ctx: Ctx) !void {973    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);974    defer ctx.gpa.free(out);975    const gens = try parseHomeGenerations(ctx.gpa, out);976    defer freeHomeGens(ctx.gpa, gens);977978    output.homePackagesHeader(ctx.machine.name);979    if (gens.len == 0 or gens[0].path.len == 0) return;980981    // The current generation's references are its managed packages (plus a few982    // home-manager scaffolding paths and versionless support outputs we skip).983    const refs = exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, gens[0].path) catch return;984    defer ctx.gpa.free(refs);985    var lines = std.mem.splitScalar(u8, refs, '\n');986    while (lines.next()) |line| {987        const t = std.mem.trim(u8, line, " \t\r");988        if (t.len == 0) continue;989        const row = pkgFromStorePath(t);990        if (row.version.len == 0) continue;991        if (std.mem.indexOf(u8, row.name, "home-manager") != null) continue;992        output.listPkg(row.name, row.version);993    }994}995996fn homeDiff(ctx: Ctx) !void {997    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);998    defer ctx.gpa.free(out);999    const gens = try parseHomeGenerations(ctx.gpa, out);1000    defer freeHomeGens(ctx.gpa, gens);10011002    // Need two generations and both their store paths to diff their closures.1003    if (gens.len < 2 or gens[0].path.len == 0 or gens[1].path.len == 0) {1004        output.homeNothingToDiff();1005        return;1006    }1007    const newer = gens[0];1008    const older = gens[1];1009    output.homeDiffHeader(older.number, newer.number, ctx.machine.name);1010    if (try exec.diffClosuresPaths(ctx.io, &ctx.machine, ctx.gpa, older.path, newer.path) != 0)1011        return error.ProcessFailed;1012}10131014fn homeCheck(ctx: Ctx) !void {1015    output.homeCheckStart(ctx.machine.name);1016    const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa);1017    if (code != 0) {1018        output.checkFailed("");1019        return error.BuildFailed;1020    }1021    output.homeCheckOk();1022}10231024fn homeEdit(ctx: Ctx) !void {1025    // Standalone home config lives at ~/.config/home-manager/home.nix; the same1026    // path is what detection keys on for module mode, so it resolves for both.1027    const path = exec.homeNixPath(ctx.gpa, ctx.environ) orelse {1028        errors.error_info.setMessage("could not resolve ~/.config/home-manager/home.nix", .{});1029        return error.ConfigNotFound;1030    };1031    defer ctx.gpa.free(path);1032    output.homeEditOpen(path, ctx.cfg.editor);1033    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);1034}10351036fn homeHistory(ctx: Ctx) !void {1037    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1038    defer ctx.gpa.free(out);1039    const gens = try parseHomeGenerations(ctx.gpa, out);1040    defer freeHomeGens(ctx.gpa, gens);1041    output.homeHistoryHeader(ctx.machine.name);1042    // Newest-first from home-manager; the first row is the current generation.1043    for (gens, 0..) |g, i| output.homeHistoryRow(g.number, g.date, g.time, i == 0);1044}10451046fn homeBack(ctx: Ctx) !void {1047    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1048    defer ctx.gpa.free(out);1049    const gens = try parseHomeGenerations(ctx.gpa, out);1050    defer freeHomeGens(ctx.gpa, gens);10511052    // Newest-first: [0] is current, [1] is the generation to roll back to.1053    if (gens.len < 2) {1054        output.alreadyOldest();1055        return;1056    }1057    const current = gens[0].number;1058    const prev = gens[1].number;10591060    output.homeBackStart(ctx.machine.name, current, prev);1061    if (ctx.cfg.confirm and !output.confirm("")) return;1062    const code = try exec.homeManagerRollback(ctx.io, &ctx.machine, ctx.gpa);1063    if (code != 0) return error.BuildFailed;1064    output.homeBackDone(prev);1065}10661067fn homeApply(ctx: Ctx, mode: exec.HomeManagerMode) !void {1068    // NixOS/flake module: home config is rebuilt by nixos-rebuild — redirect.1069    if (mode == .module) {1070        output.homeModuleManaged();1071        return;1072    }1073    if (ctx.dry) {1074        output.homeApplyDry(ctx.machine.name);1075        const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa);1076        if (code != 0) return error.BuildFailed;1077        output.homeApplyDryDone();1078        return;1079    }10801081    output.homeApplyStart(ctx.machine.name);1082    const flake_ref = exec.homeFlakeRef(ctx.gpa, ctx.io, ctx.environ);1083    defer if (flake_ref) |r| ctx.gpa.free(r);1084    if (flake_ref) |ref| {1085        output.printSubstep("home-manager switch --flake {s}", .{ref});1086    } else {1087        output.printSubstep("home-manager switch", .{});1088    }10891090    const start = std.Io.Clock.awake.now(ctx.io);1091    const code = if (flake_ref) |ref|1092        try exec.homeManagerSwitchFlake(ctx.io, &ctx.machine, ctx.gpa, ref)1093    else1094        try exec.homeManagerSwitch(ctx.io, &ctx.machine, ctx.gpa);1095    if (code != 0) return error.BuildFailed;10961097    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());1098    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));1099    output.homeApplyDone(homeCurrentGen(ctx), elapsed);1100}11011102// --- Service commands ---11031104const service_help = [_][2][]const u8{1105    .{ "list", "list running services" },1106    .{ "logs <svc>", "show service logs" },1107    .{ "status <svc>", "service status" },1108    .{ "start <svc>", "start a service" },1109    .{ "stop <svc>", "stop a service" },1110    .{ "restart <svc>", "restart a service" },1111    .{ "enable <svc>", "enable at boot" },1112    .{ "disable <svc>", "disable at boot" },1113};11141115pub fn service(ctx: Ctx) !void {1116    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");1117    if (std.mem.eql(u8, ctx.sub, "list")) {1118        output.serviceListHeader(ctx.machine.name);1119        const svcs = exec.serviceList(ctx.gpa, ctx.io, &ctx.machine, ctx.user) catch &.{};1120        defer ctx.gpa.free(svcs);1121        for (svcs) |s| output.serviceRow(s);1122        return;1123    }1124    if (std.mem.eql(u8, ctx.sub, "logs")) {1125        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1126        const follow = ctx.args.len > 1 and std.mem.eql(u8, ctx.args[1], "-f");1127        output.serviceLogsHeader(name, ctx.last, ctx.machine.name);1128        _ = try exec.serviceLogs(ctx.io, &ctx.machine, ctx.gpa, name, ctx.last, follow, ctx.user);1129        return;1130    }1131    if (std.mem.eql(u8, ctx.sub, "status")) {1132        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1133        output.serviceVerb("status", name, ctx.machine.name);1134        _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, "status", name, ctx.user);1135        return;1136    }1137    // start/stop/restart/enable/disable1138    const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1139    if (ctx.cfg.confirm and (std.mem.eql(u8, ctx.sub, "stop") or std.mem.eql(u8, ctx.sub, "disable"))) {1140        if (!output.confirm("")) return;1141    }1142    output.serviceVerb(ctx.sub, name, ctx.machine.name);1143    _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, ctx.sub, name, ctx.user);1144    output.serviceDone();1145}11461147// --- Flake commands ---11481149const flake_help = [_][2][]const u8{1150    .{ "init", "create a new flake.nix" },1151    .{ "update", "update flake inputs" },1152    .{ "update <in>", "update a specific input" },1153    .{ "check", "validate the flake" },1154    .{ "show", "inspect flake outputs" },1155    .{ "lock", "regenerate flake.lock" },1156    .{ "clone <url>", "clone a flake repository" },1157};11581159pub fn flake(ctx: Ctx) !void {1160    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("flake", &flake_help, null);1161    if (std.mem.eql(u8, ctx.sub, "update")) {1162        output.flakeUpdateStart();1163        const input: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1164        _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1165        output.flakeLockWritten();1166        return;1167    }1168    if (std.mem.eql(u8, ctx.sub, "check")) {1169        output.flakeCheckStart();1170        const code = try exec.flakeCheck(ctx.io, &ctx.machine, ctx.gpa);1171        if (code == 0) output.flakeValid() else output.checkFailed("");1172        return;1173    }1174    if (std.mem.eql(u8, ctx.sub, "show")) {1175        const json_out = exec.flakeShow(ctx.gpa, ctx.io, &ctx.machine) catch null;1176        if (json_out) |j| {1177            defer ctx.gpa.free(j);1178            output.flakeShowHeader("flake outputs");1179            // Parse and display the flake outputs1180            const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, j, .{}) catch return;1181            defer parsed.deinit();1182            if (parsed.value == .object) {1183                var it = parsed.value.object.iterator();1184                while (it.next()) |entry| {1185                    if (entry.value_ptr.* == .object) {1186                        var inner = entry.value_ptr.object.iterator();1187                        while (inner.next()) |e2| {1188                            const desc = if (e2.value_ptr.* == .object)1189                                if (e2.value_ptr.object.get("description")) |d|1190                                    if (d == .string) d.string else ""1191                                else ""1192                            else "";1193                            output.flakeShowEntry(entry.key_ptr.*, e2.key_ptr.*, desc);1194                        }1195                    }1196                }1197            }1198        }1199        return;1200    }1201    if (std.mem.eql(u8, ctx.sub, "init")) {1202        _ = try exec.flakeInit(ctx.io, &ctx.machine, ctx.gpa);1203        return;1204    }1205    if (std.mem.eql(u8, ctx.sub, "lock")) {1206        _ = try exec.flakeLock(ctx.io, &ctx.machine, ctx.gpa);1207        return;1208    }1209    if (std.mem.eql(u8, ctx.sub, "clone")) {1210        const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1211        _ = try exec.flakeClone(ctx.io, &ctx.machine, ctx.gpa, url);1212        return;1213    }1214}12151216// --- Store commands ---12171218const store_help = [_][2][]const u8{1219    .{ "info", "store size and counts" },1220    .{ "path <attr>", "store path of a package" },1221    .{ "gc", "collect garbage" },1222    .{ "verify", "verify store integrity" },1223    .{ "repair", "repair corrupted paths" },1224};12251226pub fn store(ctx: Ctx) !void {1227    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("store", &store_help, null);1228    if (std.mem.eql(u8, ctx.sub, "gc")) {1229        _ = try exec.storeGc(ctx.io, &ctx.machine, ctx.gpa);1230        return;1231    }1232    if (std.mem.eql(u8, ctx.sub, "verify")) {1233        output.storeVerifyStart();1234        _ = try exec.storeVerify(ctx.io, &ctx.machine, ctx.gpa);1235        return;1236    }1237    if (std.mem.eql(u8, ctx.sub, "repair")) {1238        if (ctx.cfg.confirm and !output.confirm("")) return;1239        output.storeRepairStart();1240        _ = try exec.storeRepair(ctx.io, &ctx.machine, ctx.gpa);1241        return;1242    }1243    if (std.mem.eql(u8, ctx.sub, "info")) {1244        const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1245        output.storeInfo(si);1246        return;1247    }1248    if (std.mem.eql(u8, ctx.sub, "path")) {1249        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1250        const path = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, attr);1251        defer ctx.gpa.free(path);1252        output.storePath(path);1253        return;1254    }1255    // default: info1256    const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1257    output.storeInfo(si);1258}12591260// --- Channel commands ---12611262const channel_help = [_][2][]const u8{1263    .{ "list", "list channels" },1264    .{ "add <url> [name]", "add a channel" },1265    .{ "remove <name>", "remove a channel" },1266    .{ "update", "update all channels" },1267};12681269pub fn channel(ctx: Ctx) !void {1270    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("channel", &channel_help, null);1271    // On a flake-managed system, nix-channel operations generally don't apply.1272    if (flakeSystem(ctx)) output.flakeChannelNote();1273    if (std.mem.eql(u8, ctx.sub, "list")) {1274        output.channelListHeader(ctx.machine.name);1275        const chans = try exec.channelList(ctx.gpa, ctx.io, &ctx.machine);1276        defer ctx.gpa.free(chans);1277        for (chans) |ch| output.channelRow(ch);1278        return;1279    }1280    if (std.mem.eql(u8, ctx.sub, "add")) {1281        const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1282        const name = if (ctx.args.len > 1) ctx.args[1] else "";1283        _ = try exec.channelAdd(ctx.io, &ctx.machine, ctx.gpa, url, name);1284        output.channelDone();1285        return;1286    }1287    if (std.mem.eql(u8, ctx.sub, "remove")) {1288        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1289        _ = try exec.channelRemove(ctx.io, &ctx.machine, ctx.gpa, name);1290        output.channelDone();1291        return;1292    }1293    if (std.mem.eql(u8, ctx.sub, "update")) {1294        return channelUpdateCmd(ctx);1295    }1296}12971298// --- Profile commands ---12991300pub fn profile(ctx: Ctx) !void {1301    if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {1302        output.profileListHeader();1303        const out = exec.profileList(ctx.gpa, ctx.io, &ctx.machine) catch null;1304        if (out) |o| {1305            defer ctx.gpa.free(o);1306            var lines = std.mem.splitScalar(u8, o, '\n');1307            while (lines.next()) |line| {1308                const t = std.mem.trim(u8, line, " \t\r");1309                if (t.len == 0) continue;1310                output.profileRow(t, "", "");1311            }1312        }1313        return;1314    }1315    if (std.mem.eql(u8, ctx.sub, "install")) {1316        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1317        _ = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, attr);1318        output.done();1319        return;1320    }1321    if (std.mem.eql(u8, ctx.sub, "remove")) {1322        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1323        _ = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, attr);1324        output.done();1325        return;1326    }1327    if (std.mem.eql(u8, ctx.sub, "upgrade")) {1328        _ = try exec.profileUpgrade(ctx.io, &ctx.machine, ctx.gpa);1329        output.done();1330        return;1331    }1332}13331334// --- Pkg commands ---13351336const pkg_help = [_][2][]const u8{1337    .{ "why <pkg>", "what pulled it in" },1338    .{ "deps <pkg>", "direct dependencies" },1339    .{ "size <pkg>", "closure size" },1340    .{ "path <pkg>", "store path" },1341    .{ "closure <pkg>", "full closure" },1342};13431344pub fn pkg(ctx: Ctx) !void {1345    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("pkg", &pkg_help, null);1346    const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1347    if (std.mem.eql(u8, ctx.sub, "why")) {1348        _ = try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name);1349        return;1350    }1351    if (std.mem.eql(u8, ctx.sub, "deps")) {1352        _ = try exec.pkgDeps(ctx.io, &ctx.machine, ctx.gpa, name);1353        return;1354    }1355    if (std.mem.eql(u8, ctx.sub, "size")) {1356        const s = exec.pkgSize(ctx.gpa, ctx.io, &ctx.machine, name) catch null;1357        if (s) |sz| {1358            defer ctx.gpa.free(sz);1359            output.pkgResult("size", sz);1360        }1361        return;1362    }1363    if (std.mem.eql(u8, ctx.sub, "path")) {1364        const p = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, name);1365        defer ctx.gpa.free(p);1366        output.pkgResult("path", p);1367        return;1368    }1369    if (std.mem.eql(u8, ctx.sub, "closure")) {1370        _ = try exec.pkgClosure(ctx.io, &ctx.machine, ctx.gpa, name);1371        return;1372    }1373}13741375// Top-level alias for `nina pkg why <pkg>` — surfaces what pulled a package in1376// without the user needing to know about the `pkg` subgroup.1377pub fn why(ctx: Ctx) !void {1378    const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1379    _ = try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name);1380}13811382// --- Pin / Unpin ---13831384pub fn pin(ctx: Ctx) !void {1385    const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1386    const commit = if (ctx.args.len > 1) ctx.args[1] else return error.Internal;1387    exec.editFlakeLock(ctx.gpa, input, commit) catch return error.ProcessFailed;1388    output.pinDone(input, commit);1389}13901391pub fn unpin(ctx: Ctx) !void {1392    const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1393    _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1394    output.unpinDone(input);1395}13961397// --- Hash / Fetch ---13981399pub fn hash(ctx: Ctx) !void {1400    const path = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1401    const h = try exec.nixHash(ctx.gpa, ctx.io, &ctx.machine, path);1402    defer ctx.gpa.free(h);1403    output.hashResult(std.mem.trim(u8, h, " \t\n\r"));1404}14051406pub fn fetch(ctx: Ctx) !void {1407    const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1408    const h = try exec.nixFetch(ctx.gpa, ctx.io, &ctx.machine, url);1409    defer ctx.gpa.free(h);1410    output.fetchResult(std.mem.trim(u8, h, " \t\n\r"), url);1411}14121413// --- Build / Run ---14141415pub fn build(ctx: Ctx) !void {1416    const attr: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1417    output.buildStart(attr orelse "default");1418    const code = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, attr);1419    if (code != 0) return error.BuildFailed;1420    output.buildDone();1421}14221423pub fn runCmd(ctx: Ctx) !void {1424    const pkg_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1425    output.runStart(pkg_arg);1426    _ = try exec.nixRun(ctx.io, &ctx.machine, ctx.gpa, pkg_arg);1427}14281429// --- Hello ---14301431pub fn hello(ctx: Ctx) !void {1432    output.hello(ctx.cfg.machines);1433}14341435// Runs when ~/.nina.conf is absent on first invocation (interactive TTY only).1436// Prompts for machine name, config path, and local flag, then writes the file.1437pub fn firstRunWizard(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1438    output.firstRunBanner();1439    output.firstRunNoConfig();14401441    var name_buf: [256]u8 = undefined;1442    var path_buf: [256]u8 = undefined;1443    var local_buf: [256]u8 = undefined;14441445    const machine_name = output.firstRunPrompt("machine name", "my-machine", &name_buf);14461447    // Flake-based systems don't have a traditional /etc/nixos/configuration.nix —1448    // their config lives wherever flake.nix is. Ask, then prompt for the right1449    // path and record `flake = true` so channel commands can warn appropriately.1450    const use_flakes = output.firstRunManageType();1451    const config_path = if (use_flakes)1452        output.firstRunPrompt("flake directory", "~/nixos-config", &path_buf)1453    else1454        output.firstRunPrompt("config path", "/etc/nixos", &path_buf);1455    const local_str = output.firstRunPrompt("local", "true", &local_buf);14561457    const conf_path = try config.configPath(gpa, environ);1458    defer gpa.free(conf_path);1459    if (std.fs.path.dirname(conf_path)) |dir| exec.ensureDir(gpa, io, dir);14601461    // `flake` is a top-level config field, so it must precede the [machine] block.1462    const flake_line = if (use_flakes) "flake = true\n" else "";1463    var content_buf: [1024]u8 = undefined;1464    const content = try std.fmt.bufPrint(1465        &content_buf,1466        "{s}[machine]\nname = {s}\nconfig = {s}\nlocal = {s}\n",1467        .{ flake_line, machine_name, config_path, local_str },1468    );14691470    const file = std.Io.Dir.createFile(.cwd(), io, conf_path, .{}) catch {1471        errors.error_info.setMessage("could not write {s}", .{conf_path});1472        return error.Internal;1473    };1474    defer file.close(io);1475    file.writePositionalAll(io, content, 0) catch {1476        errors.error_info.setMessage("could not write {s}", .{conf_path});1477        return error.Internal;1478    };14791480    output.firstRunWritten(conf_path);1481}14821483pub fn setup(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1484    // Create the config first if it doesn't exist. This makes `nina setup`1485    // a complete onboarding command — not just a nix-features check. Any legacy1486    // ~/.nina.conf is migrated to the XDG path before we decide to run the wizard.1487    config.migrateLegacyConfig(gpa, io, environ);1488    if (config.configPath(gpa, environ)) |conf_path| {1489        defer gpa.free(conf_path);1490        if (std.Io.Dir.openFile(.cwd(), io, conf_path, .{})) |f| {1491            f.close(io);1492        } else |_| {1493            try firstRunWizard(gpa, io, environ);1494            errors.error_info.reset();1495        }1496    } else |_| {}14971498    output.setupCheck();1499    const status = exec.checkNixFeatures(gpa, io, environ);1500    output.setupFeatures(status.nix_command, status.flakes);15011502    if (status.allEnabled()) {1503        output.setupAllSet();1504        api.ensureRegistryPinned(gpa, io, environ);1505        return;1506    }15071508    // On NixOS the features belong in configuration.nix (the declarative,1509    // permanent home), not ~/.config/nix/nix.conf. Offer to add the one line;1510    // the user runs the rebuild. We don't pin the registry here because the1511    // features aren't live until that rebuild lands.1512    if (exec.isNixOS(io)) {1513        const conf_path = "/etc/nixos/configuration.nix";1514        if (exec.nixosConfigEnablesFeatures(gpa, io, conf_path)) {1515            output.setupNixosNeedsRebuild(conf_path);1516            return;1517        }1518        output.setupNixosOffer(exec.NIXOS_FEATURES_LINE, conf_path);1519        if (output.confirmDefaultNo("add it now?")) {1520            if (exec.appendFeaturesToNixosConfig(gpa, io, environ, conf_path)) |_| {1521                output.setupNixosWrote(conf_path);1522            } else |_| {1523                output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);1524            }1525        } else {1526            output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);1527        }1528        return;1529    }15301531    // Non-NixOS: a user-level nix.conf takes effect immediately, no sudo needed.1532    output.setupEnabling();1533    const path = try exec.enableNixFeatures(gpa, io, environ);1534    defer gpa.free(path);15351536    output.setupDone(path);1537    api.ensureRegistryPinned(gpa, io, environ);1538}15391540// --- Log helper ---15411542fn logAction(ctx: Ctx, action: []const u8, gen: u32) void {1543    var ts_buf: [32]u8 = undefined;1544    const ts = nowIso(ctx.io, &ts_buf);1545    var buf: [256]u8 = undefined;1546    const entry = std.fmt.bufPrint(&buf, "{{\"ts\":\"{s}\",\"machine\":\"{s}\",\"command\":\"{s}\",\"outcome\":\"success\",\"gen_before\":null,\"gen_after\":{d},\"duration_ms\":0}}\n", .{1547        ts, ctx.machine.name, action, gen,1548    }) catch return;1549    exec.appendNinaLog(ctx.io, ctx.environ, entry);1550}15511552// Wall-clock UTC as ISO-8601. Uses Io.Clock.real (the settable Unix-epoch clock);1553// Io.Clock.awake is monotonic and unsuitable for timestamps. Falls back to epoch 0.1554fn nowIso(io: std.Io, buf: []u8) []const u8 {1555    const fallback = "1970-01-01T00:00:00Z";1556    const ns = std.Io.Clock.real.now(io).toNanoseconds();1557    if (ns <= 0) return fallback;1558    const secs: u64 = @intCast(@divFloor(ns, 1_000_000_000));1559    const es = std.time.epoch.EpochSeconds{ .secs = secs };1560    const ed = es.getEpochDay();1561    const yd = ed.calculateYearDay();1562    const md = yd.calculateMonthDay();1563    const ds = es.getDaySeconds();1564    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", .{1565        yd.year, md.month.numeric(), @as(u32, md.day_index) + 1,1566        ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(),1567    }) catch return fallback;1568}