commands.zig

50.2 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        return;191    }192    statusRowFor(ctx, &ctx.machine);193}194195fn statusRowFor(ctx: Ctx, machine: *const types.Machine) void {196    // A failure to read the current generation means we couldn't reach or query197    // the machine — mark it unreachable rather than reporting a bogus gen 0.198    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, machine) catch {199        output.statusRow(machine.name, 0, "", "", false);200        return;201    };202    const st = exec.systemStatus(ctx.gpa, ctx.io, machine);203    defer ctx.gpa.free(st.size);204    defer ctx.gpa.free(st.age);205    output.statusRow(machine.name, gen, st.age, st.size, true);206}207208pub fn diff(ctx: Ctx) !void {209    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);210    defer ctx.gpa.free(gens);211    var current: u32 = 0;212    var prev: u32 = 0;213    for (gens) |g| {214        if (g.current) current = g.number;215        if (!g.current and g.number > prev and g.number < current) prev = g.number;216    }217    if (ctx.args.len >= 2) {218        const a = std.fmt.parseInt(u32, ctx.args[0], 10) catch current - 1;219        const b = std.fmt.parseInt(u32, ctx.args[1], 10) catch current;220        output.diffHeader(a, b, ctx.machine.name);221        if (try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, a, b) != 0) return error.ProcessFailed;222    } else {223        output.diffHeader(if (prev > 0) prev else current - 1, current, ctx.machine.name);224        if (try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, if (prev > 0) prev else current - 1, current) != 0) return error.ProcessFailed;225    }226}227228pub fn mood(ctx: Ctx) !void {229    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;230    const st = exec.systemStatus(ctx.gpa, ctx.io, &ctx.machine);231    defer ctx.gpa.free(st.size);232    defer ctx.gpa.free(st.age);233    const state = exec.systemRunningState(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");234    defer ctx.gpa.free(state);235    output.mood(ctx.machine.name, state, gen, st.age, st.size);236}237238pub fn doctor(ctx: Ctx) !void {239    output.doctorHeader(ctx.machine.name);240    const checks = try exec.runDoctorChecks(ctx.gpa, ctx.io, &ctx.machine);241    defer ctx.gpa.free(checks);242    var warnings: u32 = 0;243    var failures: u32 = 0;244    for (checks) |ch| {245        output.doctorRow(ch);246        if (ch.status == .warn) warnings += 1;247        if (ch.status == .fail) failures += 1;248    }249    output.doctorSummary(warnings, failures);250}251252// nina update — kepr self-update for the nina binary itself.253pub fn update(ctx: Ctx) !void {254    output.updateSelfStart();255256    if (comptime std.mem.eql(u8, version.PLATFORM, "unsupported")) {257        output.updateSelfNoPlatform(@tagName(builtin.cpu.arch) ++ "-" ++ @tagName(builtin.os.tag));258        return error.Internal;259    }260261    const env_url = ctx.environ.get("NINA_UPDATE_SOURCE");262    const source_url = env_url orelse UPDATE_URL;263264    const body = exec.fetchUrl(ctx.gpa, ctx.io, source_url) catch |e| switch (e) {265        error.NetworkError, error.HttpError => {266            output.updateSelfNetworkError();267            return;268        },269        else => return e,270    };271    defer ctx.gpa.free(body);272273    const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, body, .{}) catch {274        output.printWarning("could not parse release metadata");275        return;276    };277    defer parsed.deinit();278279    const root = parsed.value;280    if (root != .object) { output.printWarning("malformed release metadata"); return; }281282    const remote_ver = blk: {283        const v = root.object.get("version") orelse { output.printWarning("malformed release metadata"); return; };284        break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };285    };286287    if (std.mem.eql(u8, remote_ver, version.VERSION)) {288        output.updateSelfCurrent(version.VERSION);289        return;290    }291292    output.updateSelfAvailable(version.VERSION, remote_ver);293    if (ctx.check) return;294295    var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;296    const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {297        errors.error_info.setMessage("could not determine install path", .{});298        return error.Internal;299    };300301    // When running from the nix store, defer to nix profile upgrade so nix302    // manages the transition (the store is read-only; binary replacement fails).303    // A NixOS system install also resolves into the store but isn't a profile304    // element, so check the profile to avoid a no-op `upgrade` — it updates with305    // the next nixos-rebuild instead.306    if (std.mem.startsWith(u8, install_path, "/nix/store/")) {307        const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);308        defer {309            if (nina_element) |n| ctx.gpa.free(n);310        }311        if (nina_element == null) {312            output.updateSelfNotInProfile();313            return;314        }315        const element = nina_element.?;316        output.updateSelfNixManaged(remote_ver);317        if (ctx.cfg.confirm and !output.confirm("")) return;318        const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "upgrade", element }) catch {319            output.updateSelfNixFailed();320            return;321        };322        if (ec != 0) output.updateSelfNixFailed();323        return;324    }325326    const plat_info = blk: {327        const pv = root.object.get("platforms") orelse break :blk null;328        if (pv != .object) break :blk null;329        break :blk pv.object.get(version.PLATFORM);330    };331    if (plat_info == null) { output.updateSelfNoPlatform(version.PLATFORM); return; }332333    const dl_url = blk: {334        const v = plat_info.?.object.get("url") orelse { output.printWarning("malformed release metadata"); return; };335        break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };336    };337338    const raw_cksum = blk: {339        if (plat_info.?.object.get("blake3")) |v|340            break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };341        if (plat_info.?.object.get("checksum")) |v|342            break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };343        output.printWarning("missing checksum in release metadata");344        return;345    };346    const expected_hex = if (std.mem.startsWith(u8, raw_cksum, "blake3:")) raw_cksum["blake3:".len..] else raw_cksum;347348    if (ctx.cfg.confirm and !output.confirm("")) return;349350    output.updateSelfDownloading(remote_ver, version.PLATFORM);351    const tmp_path = exec.downloadToTemp(ctx.gpa, ctx.io, dl_url) catch {352        output.printWarning("download failed — check your connection and try again");353        return;354    };355    defer ctx.gpa.free(tmp_path);356357    output.updateSelfVerifying();358    exec.verifyAndInstall(ctx.gpa, ctx.io, tmp_path, expected_hex, install_path) catch |e| switch (e) {359        error.ChecksumMismatch => { output.updateSelfChecksumFailed(); return; },360        else => return e,361    };362363    output.updateSelfDone(version.VERSION, remote_ver);364}365366// nina goodbye — clean uninstall. Three install paths:367// - nix profile (binary in nix store with a profile element) → nix profile remove368// - koh build or source build (plain binary on PATH) → delete the file369pub fn goodbye(ctx: Ctx) !void {370    output.goodbyeStart();371372    var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;373    const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {374        errors.error_info.setMessage("could not determine install path", .{});375        return error.Internal;376    };377378    // A binary outside the nix store is a koh build or source build — delete it.379    if (!std.mem.startsWith(u8, install_path, "/nix/store/")) {380        output.goodbyeFile(install_path);381        if (ctx.cfg.confirm and !output.confirm("")) return;382        std.Io.Dir.deleteFileAbsolute(ctx.io, install_path) catch |e| {383            errors.error_info.setMessage("could not remove {s}", .{install_path});384            return e;385        };386        output.goodbyeDone();387        return;388    }389390    // Binary is in the nix store — find and remove the profile element.391    const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);392    defer {393        if (nina_element) |n| ctx.gpa.free(n);394    }395396    if (nina_element == null) {397        errors.error_info.setMessage("nina not found in nix profile — was it installed via 'nix profile add'?", .{});398        return error.Internal;399    }400401    output.goodbyeNix();402    if (ctx.cfg.confirm and !output.confirm("")) return;403    const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "remove", nina_element.? }) catch {404        output.goodbyeFailed("nix profile remove failed");405        return;406    };407    if (ec != 0) {408        output.goodbyeFailed("nix profile remove failed");409        return;410    }411    output.goodbyeDone();412}413414fn channelUpdateCmd(ctx: Ctx) !void {415    output.updateStart(ctx.machine.name);416    _ = try exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa);417    output.updateDone();418}419420pub fn upgrade(ctx: Ctx) !void {421    output.upgradeStart(ctx.machine.name);422    output.printSubstep("updating channels", .{});423    _ = exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa) catch {};424    output.printSubstep("rebuilding", .{});425    const start = std.Io.Clock.awake.now(ctx.io);426    const code = try exec.nixosRebuildSwitch(ctx.io, &ctx.machine, ctx.gpa);427    if (code != 0) {428        output.applyFailed("");429        return error.BuildFailed;430    }431    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());432    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));433    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;434    output.applyDone(gen, elapsed, false);435}436437pub fn log(ctx: Ctx) !void {438    output.logHeader(ctx.machine.name);439    const content = exec.readNinaLog(ctx.gpa, ctx.io, ctx.environ, ctx.last) catch {440        // No log yet — that's fine441        return;442    };443    defer ctx.gpa.free(content);444    var lines = std.mem.splitScalar(u8, content, '\n');445    while (lines.next()) |line| {446        const t = std.mem.trim(u8, line, " \t\r");447        if (t.len == 0) continue;448        if (t[0] == '{') {449            renderJsonLogLine(ctx.gpa, t);450        } else {451            // legacy tab-separated format452            var parts = std.mem.tokenizeScalar(u8, t, '\t');453            const date = parts.next() orelse continue;454            const time = parts.next() orelse "";455            const action = parts.next() orelse "";456            const detail = parts.next() orelse "";457            output.logRow(date, time, action, detail);458        }459    }460}461462// The on-disk log is JSON Lines: {"ts","machine","command","outcome","gen_after",...}.463// Render ts -> date/time columns, command -> action, outcome(+gen) -> detail.464fn renderJsonLogLine(gpa: std.mem.Allocator, line: []const u8) void {465    const parsed = std.json.parseFromSlice(std.json.Value, gpa, line, .{}) catch {466        output.logRow(line, "", "", ""); // unparseable — show raw rather than drop467        return;468    };469    defer parsed.deinit();470    if (parsed.value != .object) return;471    const o = parsed.value.object;472473    const ts = jsonStr(o, "ts");474    const date = if (ts.len >= 10) ts[0..10] else ts;475    const time = if (ts.len >= 16) ts[11..16] else "";476    const action = jsonStr(o, "command");477    const outcome = jsonStr(o, "outcome");478479    var buf: [160]u8 = undefined;480    var detail: []const u8 = outcome;481    if (o.get("gen_after")) |g| {482        if (g == .integer) {483            detail = std.fmt.bufPrint(&buf, "{s}   -> gen {d}", .{ outcome, g.integer }) catch outcome;484        }485    }486    output.logRow(date, time, action, detail);487}488489fn jsonStr(o: std.json.ObjectMap, key: []const u8) []const u8 {490    if (o.get(key)) |v| {491        if (v == .string) return v.string;492    }493    return "";494}495496pub fn edit(ctx: Ctx) !void {497    const hardware = ctx.args.len > 0 and std.mem.eql(u8, ctx.args[0], "hardware");498    const filename = if (hardware) "hardware-configuration.nix" else "configuration.nix";499    const path = try std.fmt.allocPrint(ctx.gpa, "{s}/{s}", .{ ctx.machine.config_path, filename });500    defer ctx.gpa.free(path);501    output.editOpen(path, ctx.cfg.editor);502    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);503}504505pub fn fmt(ctx: Ctx) !void {506    const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});507    defer ctx.gpa.free(path);508    if (ctx.check) {509        const code = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, true);510        if (code != 0) output.fmtNeedsFormat() else output.fmtDone();511        return;512    }513    output.fmtStart(path);514    _ = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, false);515    output.fmtDone();516}517518pub fn repl(ctx: Ctx) !void {519    output.replStart();520    _ = try exec.nixRepl(ctx.io, &ctx.machine, ctx.gpa);521}522523pub fn develop(ctx: Ctx) !void {524    if (std.mem.eql(u8, ctx.sub, "show")) {525        _ = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, null);526        return;527    }528    const run_cmd: ?[]const u8 = if (ctx.args.len > 0 and std.mem.eql(u8, ctx.sub, "run"))529        ctx.args[0]530    else531        null;532    output.developStart(&.{});533    _ = try exec.nixDevelopPs1(ctx.io, &ctx.machine, ctx.gpa, run_cmd, ctx.environ);534    output.developDone();535}536537pub fn info(ctx: Ctx) !void {538    output.infoHeader(ctx.machine.name);539    const nixos_ver = exec.systemInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");540    defer ctx.gpa.free(nixos_ver);541    output.infoRow("nixos", std.mem.trim(u8, nixos_ver, " \t\n\r"));542543    const kernel = exec.kernelInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");544    defer ctx.gpa.free(kernel);545    output.infoRow("kernel", std.mem.trim(u8, kernel, " \t\n\r"));546547    const uptime = exec.uptimeInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");548    defer ctx.gpa.free(uptime);549    output.infoRow("uptime", std.mem.trim(u8, uptime, " \t\n\r"));550}551552pub fn boot(ctx: Ctx) !void {553    output.bootHeader(ctx.machine.name);554    const entries = exec.bootEntries(ctx.gpa, ctx.io, &ctx.machine) catch &.{};555    defer ctx.gpa.free(entries);556    for (entries, 0..) |entry, i| output.bootEntry(entry, i);557}558559pub fn searchCmd(ctx: Ctx) !void {560    const query = if (ctx.args.len > 0) ctx.args[0] else "";561    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);562    const selected = try search_tui.run(ctx.gpa, ctx.io, query, .packages);563    if (selected) |npkg| try selectAndInstall(ctx, npkg);564}565566pub fn optionCmd(ctx: Ctx) !void {567    const query = if (ctx.args.len > 0) ctx.args[0] else "";568    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);569    _ = try search_tui.run(ctx.gpa, ctx.io, query, .options);570}571572pub fn install(ctx: Ctx) !void {573    const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;574575    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);576577    // Search for the package to get the attr578    const pkgs = api.searchPackages(ctx.gpa, ctx.io, pkg_name) catch {579        errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});580        errors.error_info.setSuggestion("nina search {s}", .{pkg_name});581        return error.PackageNotFound;582    };583584    if (pkgs.len == 0) {585        // No matches — likely a typo. Suggest the closest real package and offer it.586        if (closestPackage(ctx, pkg_name)) |sugg| {587            output.didYouMean(pkg_name, sugg.pname);588            if (output.confirm("")) try selectAndInstall(ctx, sugg);589            return;590        }591        errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});592        errors.error_info.setSuggestion("nina search {s}", .{pkg_name});593        return error.PackageNotFound;594    }595596    // Prefer an exact name match over the first search result — `install ripgrep`597    // must pick "ripgrep", not the alphabetically-first match like "repgrep".598    var found = pkgs[0];599    for (pkgs) |p| {600        if (std.mem.eql(u8, p.pname, pkg_name)) {601            found = p;602            break;603        }604    }605    try selectAndInstall(ctx, found);606}607608// Find the real package whose name is closest to a not-found query (typo help).609// Typos usually keep the leading characters, so gather candidates with a prefix610// search and rank by edit distance; return the best only if it's typo-close.611fn closestPackage(ctx: Ctx, query: []const u8) ?types.NixPackage {612    if (query.len < 2) return null;613    var candidates = api.searchPackages(ctx.gpa, ctx.io, query[0..@min(query.len, 4)]) catch &.{};614    if (candidates.len == 0 and query.len > 2) {615        candidates = api.searchPackages(ctx.gpa, ctx.io, query[0..2]) catch &.{};616    }617    if (candidates.len == 0) return null;618619    var best: ?types.NixPackage = null;620    var best_dist: usize = std.math.maxInt(usize);621    for (candidates) |p| {622        const d = editDistance(query, p.pname);623        if (d > 0 and d < best_dist) {624            best_dist = d;625            best = p;626        }627    }628    // Only suggest a genuinely close name, scaled to query length.629    const threshold = @max(@as(usize, 2), query.len / 3);630    return if (best_dist <= threshold) best else null;631}632633// Case-insensitive Levenshtein distance. Names longer than the row buffer are634// treated as far away (never suggested).635fn editDistance(a: []const u8, b: []const u8) usize {636    const n = b.len;637    if (a.len == 0) return n;638    if (n == 0) return a.len;639    if (n + 1 > 128) return std.math.maxInt(usize);640    var prev: [128]usize = undefined;641    var curr: [128]usize = undefined;642    var j: usize = 0;643    while (j <= n) : (j += 1) prev[j] = j;644    var i: usize = 1;645    while (i <= a.len) : (i += 1) {646        curr[0] = i;647        j = 1;648        while (j <= n) : (j += 1) {649            const cost: usize = if (std.ascii.toLower(a[i - 1]) == std.ascii.toLower(b[j - 1])) 0 else 1;650            curr[j] = @min(prev[j] + 1, @min(curr[j - 1] + 1, prev[j - 1] + cost));651        }652        @memcpy(prev[0 .. n + 1], curr[0 .. n + 1]);653    }654    return prev[n];655}656657test "editDistance is case-insensitive Levenshtein" {658    try std.testing.expectEqual(@as(usize, 1), editDistance("firefux", "firefox"));659    try std.testing.expectEqual(@as(usize, 0), editDistance("git", "GIT"));660    try std.testing.expectEqual(@as(usize, 2), editDistance("fierfox", "firefox"));661    try std.testing.expectEqual(@as(usize, 7), editDistance("", "firefox"));662}663664// Prompt for the install method (profile / system / try) and dispatch. Shared by665// `nina install <pkg>` and the search widget's Enter-to-select — the letter keys666// are read here, after the search widget's raw mode is gone, so they don't667// collide with typing a query.668fn selectAndInstall(ctx: Ctx, npkg: types.NixPackage) !void {669    output.installSelectPrompt(npkg.pname, npkg.version);670671    var choice_buf: [8]u8 = undefined;672    var choice_len: usize = 0;673    while (choice_len < choice_buf.len) {674        const n = std.posix.read(std.posix.STDIN_FILENO, choice_buf[choice_len .. choice_len + 1]) catch break;675        if (n == 0) break;676        if (choice_buf[choice_len] == '\n') break;677        choice_len += 1;678    }679    const choice = std.mem.trim(u8, choice_buf[0..choice_len], " \t");680681    if (choice.len == 0 or choice[0] == 'i' or choice[0] == 'I') {682        try profileInstallPkg(ctx, npkg);683    } else if (choice[0] == 's' or choice[0] == 'S') {684        try systemInstallPkg(ctx, npkg);685    } else if (choice[0] == 't' or choice[0] == 'T') {686        try tryPkg(ctx, npkg);687    }688}689690fn profileInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {691    output.installStart(npkg.pname, .profile);692    output.printSubstep("nix profile add nixpkgs#{s}", .{npkg.attr});693    output.printTeach(try std.fmt.allocPrint(ctx.gpa, "nix profile add nixpkgs#{s}", .{npkg.attr}));694    const code = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, npkg.attr);695    if (code != 0) return error.ProcessFailed;696    output.installDone(npkg.pname);697}698699fn systemInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {700    const config_path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});701    defer ctx.gpa.free(config_path);702    const line = api.findSystemPackagesLine(ctx.io, config_path) orelse 1;703    output.installEditorPrompt(npkg.pname, config_path, line, ctx.cfg.editor);704    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, config_path, line);705    if (ctx.cfg.confirm) {706        if (output.confirm("apply now? ")) {707            try apply(ctx);708        }709    }710}711712fn tryPkg(ctx: Ctx, npkg: types.NixPackage) !void {713    output.tryStart(npkg.pname);714    output.printSubstep("nix shell nixpkgs#{s}", .{npkg.attr});715    output.tryExitHint();716    _ = try exec.nixShellPs1(ctx.io, &ctx.machine, ctx.gpa, npkg.attr, ctx.environ);717    output.tryDone();718}719720pub fn remove(ctx: Ctx) !void {721    const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;722    output.removeStart(pkg_name);723    const code = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, pkg_name);724    if (code != 0) return error.ProcessFailed;725    output.done();726}727728pub fn list(ctx: Ctx) !void {729    output.listHeader(ctx.machine.name);730731    // Profile packages: parse `nix profile list --json` into clean name+version732    // rows instead of dumping nix's verbose multi-line "Name:/Flake attribute:"733    // blocks.734    if (exec.profileListJson(ctx.gpa, ctx.io, &ctx.machine) catch null) |json| {735        defer ctx.gpa.free(json);736        output.listSection("profile");737        renderProfileJson(ctx.gpa, json);738    }739740    // System packages: the references of /run/current-system/sw, each a741    // <hash>-<name>-<version> store path.742    if (exec.systemPackagePaths(ctx.gpa, ctx.io, &ctx.machine) catch null) |paths| {743        defer ctx.gpa.free(paths);744        output.blankLine();745        output.listSection("system");746        var lines = std.mem.splitScalar(u8, paths, '\n');747        while (lines.next()) |line| {748            const t = std.mem.trim(u8, line, " \t\r");749            if (t.len == 0) continue;750            const row = pkgFromStorePath(t);751            // Skip support paths with no parseable version (man pages, wrappers).752            if (row.version.len == 0) continue;753            output.listPkg(row.name, row.version);754        }755    }756}757758const PkgRow = struct { name: []const u8, version: []const u8 };759760// Split a nix store path basename (<hash>-<name>-<version>) into name + version.761// Version begins at the first '-' followed by a digit, which reliably lands on762// the name/version boundary since the 32-char hash and package names start with763// non-digits.764fn pkgFromStorePath(path: []const u8) PkgRow {765    const base = std.fs.path.basename(path);766    const after_hash = if (base.len > 33 and base[32] == '-') base[33..] else base;767    var i: usize = 0;768    while (i + 1 < after_hash.len) : (i += 1) {769        if (after_hash[i] == '-' and std.ascii.isDigit(after_hash[i + 1])) {770            return .{ .name = after_hash[0..i], .version = stripOutputSuffix(after_hash[i + 1 ..]) };771        }772    }773    return .{ .name = after_hash, .version = "" };774}775776// Multi-output derivations append the output name to the store path (e.g.777// curl-8.20.0-bin, less-692-man). Strip that suffix so the version column reads778// as just the version.779fn stripOutputSuffix(ver: []const u8) []const u8 {780    const suffixes = [_][]const u8{ "-bin", "-man", "-dev", "-doc", "-lib", "-info", "-out", "-static", "-devdoc" };781    for (suffixes) |s| {782        if (std.mem.endsWith(u8, ver, s)) return ver[0 .. ver.len - s.len];783    }784    return ver;785}786787test "pkgFromStorePath splits name and version at first dash-digit" {788    const a = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-ripgrep-15.1.0");789    try std.testing.expectEqualStrings("ripgrep", a.name);790    try std.testing.expectEqualStrings("15.1.0", a.version);791792    const b = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-helix-25.01");793    try std.testing.expectEqualStrings("helix", b.name);794    try std.testing.expectEqualStrings("25.01", b.version);795796    // multi-output store paths drop their output-name suffix797    const c = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-curl-8.20.0-bin");798    try std.testing.expectEqualStrings("curl", c.name);799    try std.testing.expectEqualStrings("8.20.0", c.version);800}801802fn firstStorePath(el: std.json.Value) ?[]const u8 {803    if (el != .object) return null;804    const sp = el.object.get("storePaths") orelse return null;805    if (sp != .array or sp.array.items.len == 0) return null;806    const first = sp.array.items[0];807    return if (first == .string) first.string else null;808}809810// `nix profile list --json` has two shapes across nix versions: newer keys each811// element by name (object), older lists them positionally (array). Handle both.812fn renderProfileJson(gpa: std.mem.Allocator, json: []const u8) void {813    const parsed = std.json.parseFromSlice(std.json.Value, gpa, json, .{}) catch return;814    defer parsed.deinit();815    if (parsed.value != .object) return;816    const elements = parsed.value.object.get("elements") orelse return;817    switch (elements) {818        .object => |obj| {819            var it = obj.iterator();820            while (it.next()) |entry| {821                const ver = if (firstStorePath(entry.value_ptr.*)) |p| pkgFromStorePath(p).version else "";822                output.listPkg(entry.key_ptr.*, ver);823            }824        },825        .array => |arr| {826            for (arr.items) |el| {827                const path = firstStorePath(el) orelse continue;828                const row = pkgFromStorePath(path);829                output.listPkg(row.name, row.version);830            }831        },832        else => {},833    }834}835836pub fn tryCmd(ctx: Ctx) !void {837    const pkg_name_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;838    const shell_pkg = types.NixPackage{ .attr = pkg_name_arg, .pname = pkg_name_arg, .version = "", .description = "" };839    try tryPkg(ctx, shell_pkg);840}841842// --- Service commands ---843844const service_help = [_][2][]const u8{845    .{ "list", "list running services" },846    .{ "logs <svc>", "show service logs" },847    .{ "status <svc>", "service status" },848    .{ "start <svc>", "start a service" },849    .{ "stop <svc>", "stop a service" },850    .{ "restart <svc>", "restart a service" },851    .{ "enable <svc>", "enable at boot" },852    .{ "disable <svc>", "disable at boot" },853};854855pub fn service(ctx: Ctx) !void {856    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");857    if (std.mem.eql(u8, ctx.sub, "list")) {858        output.serviceListHeader(ctx.machine.name);859        const svcs = exec.serviceList(ctx.gpa, ctx.io, &ctx.machine, ctx.user) catch &.{};860        defer ctx.gpa.free(svcs);861        for (svcs) |s| output.serviceRow(s);862        return;863    }864    if (std.mem.eql(u8, ctx.sub, "logs")) {865        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;866        const follow = ctx.args.len > 1 and std.mem.eql(u8, ctx.args[1], "-f");867        output.serviceLogsHeader(name, ctx.last, ctx.machine.name);868        _ = try exec.serviceLogs(ctx.io, &ctx.machine, ctx.gpa, name, ctx.last, follow, ctx.user);869        return;870    }871    if (std.mem.eql(u8, ctx.sub, "status")) {872        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;873        output.serviceVerb("status", name, ctx.machine.name);874        _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, "status", name, ctx.user);875        return;876    }877    // start/stop/restart/enable/disable878    const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;879    if (ctx.cfg.confirm and (std.mem.eql(u8, ctx.sub, "stop") or std.mem.eql(u8, ctx.sub, "disable"))) {880        if (!output.confirm("")) return;881    }882    output.serviceVerb(ctx.sub, name, ctx.machine.name);883    _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, ctx.sub, name, ctx.user);884    output.serviceDone();885}886887// --- Flake commands ---888889const flake_help = [_][2][]const u8{890    .{ "init", "create a new flake.nix" },891    .{ "update", "update flake inputs" },892    .{ "update <in>", "update a specific input" },893    .{ "check", "validate the flake" },894    .{ "show", "inspect flake outputs" },895    .{ "lock", "regenerate flake.lock" },896    .{ "clone <url>", "clone a flake repository" },897};898899pub fn flake(ctx: Ctx) !void {900    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("flake", &flake_help, null);901    if (std.mem.eql(u8, ctx.sub, "update")) {902        output.flakeUpdateStart();903        const input: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;904        _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);905        output.flakeLockWritten();906        return;907    }908    if (std.mem.eql(u8, ctx.sub, "check")) {909        output.flakeCheckStart();910        const code = try exec.flakeCheck(ctx.io, &ctx.machine, ctx.gpa);911        if (code == 0) output.flakeValid() else output.checkFailed("");912        return;913    }914    if (std.mem.eql(u8, ctx.sub, "show")) {915        const json_out = exec.flakeShow(ctx.gpa, ctx.io, &ctx.machine) catch null;916        if (json_out) |j| {917            defer ctx.gpa.free(j);918            output.flakeShowHeader("flake outputs");919            // Parse and display the flake outputs920            const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, j, .{}) catch return;921            defer parsed.deinit();922            if (parsed.value == .object) {923                var it = parsed.value.object.iterator();924                while (it.next()) |entry| {925                    if (entry.value_ptr.* == .object) {926                        var inner = entry.value_ptr.object.iterator();927                        while (inner.next()) |e2| {928                            const desc = if (e2.value_ptr.* == .object)929                                if (e2.value_ptr.object.get("description")) |d|930                                    if (d == .string) d.string else ""931                                else ""932                            else "";933                            output.flakeShowEntry(entry.key_ptr.*, e2.key_ptr.*, desc);934                        }935                    }936                }937            }938        }939        return;940    }941    if (std.mem.eql(u8, ctx.sub, "init")) {942        _ = try exec.flakeInit(ctx.io, &ctx.machine, ctx.gpa);943        return;944    }945    if (std.mem.eql(u8, ctx.sub, "lock")) {946        _ = try exec.flakeLock(ctx.io, &ctx.machine, ctx.gpa);947        return;948    }949    if (std.mem.eql(u8, ctx.sub, "clone")) {950        const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;951        _ = try exec.flakeClone(ctx.io, &ctx.machine, ctx.gpa, url);952        return;953    }954}955956// --- Store commands ---957958const store_help = [_][2][]const u8{959    .{ "info", "store size and counts" },960    .{ "path <attr>", "store path of a package" },961    .{ "gc", "collect garbage" },962    .{ "verify", "verify store integrity" },963    .{ "repair", "repair corrupted paths" },964};965966pub fn store(ctx: Ctx) !void {967    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("store", &store_help, null);968    if (std.mem.eql(u8, ctx.sub, "gc")) {969        _ = try exec.storeGc(ctx.io, &ctx.machine, ctx.gpa);970        return;971    }972    if (std.mem.eql(u8, ctx.sub, "verify")) {973        output.storeVerifyStart();974        _ = try exec.storeVerify(ctx.io, &ctx.machine, ctx.gpa);975        return;976    }977    if (std.mem.eql(u8, ctx.sub, "repair")) {978        if (ctx.cfg.confirm and !output.confirm("")) return;979        output.storeRepairStart();980        _ = try exec.storeRepair(ctx.io, &ctx.machine, ctx.gpa);981        return;982    }983    if (std.mem.eql(u8, ctx.sub, "info")) {984        const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);985        output.storeInfo(si);986        return;987    }988    if (std.mem.eql(u8, ctx.sub, "path")) {989        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;990        const path = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, attr);991        defer ctx.gpa.free(path);992        output.storePath(path);993        return;994    }995    // default: info996    const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);997    output.storeInfo(si);998}9991000// --- Channel commands ---10011002const channel_help = [_][2][]const u8{1003    .{ "list", "list channels" },1004    .{ "add <url> [name]", "add a channel" },1005    .{ "remove <name>", "remove a channel" },1006    .{ "update", "update all channels" },1007};10081009pub fn channel(ctx: Ctx) !void {1010    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("channel", &channel_help, null);1011    // On a flake-managed system, nix-channel operations generally don't apply.1012    if (flakeSystem(ctx)) output.flakeChannelNote();1013    if (std.mem.eql(u8, ctx.sub, "list")) {1014        output.channelListHeader(ctx.machine.name);1015        const chans = try exec.channelList(ctx.gpa, ctx.io, &ctx.machine);1016        defer ctx.gpa.free(chans);1017        for (chans) |ch| output.channelRow(ch);1018        return;1019    }1020    if (std.mem.eql(u8, ctx.sub, "add")) {1021        const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1022        const name = if (ctx.args.len > 1) ctx.args[1] else "";1023        _ = try exec.channelAdd(ctx.io, &ctx.machine, ctx.gpa, url, name);1024        output.channelDone();1025        return;1026    }1027    if (std.mem.eql(u8, ctx.sub, "remove")) {1028        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1029        _ = try exec.channelRemove(ctx.io, &ctx.machine, ctx.gpa, name);1030        output.channelDone();1031        return;1032    }1033    if (std.mem.eql(u8, ctx.sub, "update")) {1034        return channelUpdateCmd(ctx);1035    }1036}10371038// --- Profile commands ---10391040pub fn profile(ctx: Ctx) !void {1041    if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {1042        output.profileListHeader();1043        const out = exec.profileList(ctx.gpa, ctx.io, &ctx.machine) catch null;1044        if (out) |o| {1045            defer ctx.gpa.free(o);1046            var lines = std.mem.splitScalar(u8, o, '\n');1047            while (lines.next()) |line| {1048                const t = std.mem.trim(u8, line, " \t\r");1049                if (t.len == 0) continue;1050                output.profileRow(t, "", "");1051            }1052        }1053        return;1054    }1055    if (std.mem.eql(u8, ctx.sub, "install")) {1056        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1057        _ = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, attr);1058        output.done();1059        return;1060    }1061    if (std.mem.eql(u8, ctx.sub, "remove")) {1062        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1063        _ = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, attr);1064        output.done();1065        return;1066    }1067    if (std.mem.eql(u8, ctx.sub, "upgrade")) {1068        _ = try exec.profileUpgrade(ctx.io, &ctx.machine, ctx.gpa);1069        output.done();1070        return;1071    }1072}10731074// --- Pkg commands ---10751076const pkg_help = [_][2][]const u8{1077    .{ "why <pkg>", "what pulled it in" },1078    .{ "deps <pkg>", "direct dependencies" },1079    .{ "size <pkg>", "closure size" },1080    .{ "path <pkg>", "store path" },1081    .{ "closure <pkg>", "full closure" },1082};10831084pub fn pkg(ctx: Ctx) !void {1085    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("pkg", &pkg_help, null);1086    const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1087    if (std.mem.eql(u8, ctx.sub, "why")) {1088        _ = try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name);1089        return;1090    }1091    if (std.mem.eql(u8, ctx.sub, "deps")) {1092        _ = try exec.pkgDeps(ctx.io, &ctx.machine, ctx.gpa, name);1093        return;1094    }1095    if (std.mem.eql(u8, ctx.sub, "size")) {1096        const s = exec.pkgSize(ctx.gpa, ctx.io, &ctx.machine, name) catch null;1097        if (s) |sz| {1098            defer ctx.gpa.free(sz);1099            output.pkgResult("size", sz);1100        }1101        return;1102    }1103    if (std.mem.eql(u8, ctx.sub, "path")) {1104        const p = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, name);1105        defer ctx.gpa.free(p);1106        output.pkgResult("path", p);1107        return;1108    }1109    if (std.mem.eql(u8, ctx.sub, "closure")) {1110        _ = try exec.pkgClosure(ctx.io, &ctx.machine, ctx.gpa, name);1111        return;1112    }1113}11141115// Top-level alias for `nina pkg why <pkg>` — surfaces what pulled a package in1116// without the user needing to know about the `pkg` subgroup.1117pub fn why(ctx: Ctx) !void {1118    const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1119    _ = try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name);1120}11211122// --- Pin / Unpin ---11231124pub fn pin(ctx: Ctx) !void {1125    const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1126    const commit = if (ctx.args.len > 1) ctx.args[1] else return error.Internal;1127    exec.editFlakeLock(ctx.gpa, input, commit) catch return error.ProcessFailed;1128    output.pinDone(input, commit);1129}11301131pub fn unpin(ctx: Ctx) !void {1132    const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1133    _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1134    output.unpinDone(input);1135}11361137// --- Hash / Fetch ---11381139pub fn hash(ctx: Ctx) !void {1140    const path = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1141    const h = try exec.nixHash(ctx.gpa, ctx.io, &ctx.machine, path);1142    defer ctx.gpa.free(h);1143    output.hashResult(std.mem.trim(u8, h, " \t\n\r"));1144}11451146pub fn fetch(ctx: Ctx) !void {1147    const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1148    const h = try exec.nixFetch(ctx.gpa, ctx.io, &ctx.machine, url);1149    defer ctx.gpa.free(h);1150    output.fetchResult(std.mem.trim(u8, h, " \t\n\r"), url);1151}11521153// --- Build / Run ---11541155pub fn build(ctx: Ctx) !void {1156    const attr: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1157    output.buildStart(attr orelse "default");1158    const code = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, attr);1159    if (code != 0) return error.BuildFailed;1160    output.buildDone();1161}11621163pub fn runCmd(ctx: Ctx) !void {1164    const pkg_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1165    output.runStart(pkg_arg);1166    _ = try exec.nixRun(ctx.io, &ctx.machine, ctx.gpa, pkg_arg);1167}11681169// --- Hello ---11701171pub fn hello(ctx: Ctx) !void {1172    output.hello(ctx.cfg.machines);1173}11741175// Runs when ~/.nina.conf is absent on first invocation (interactive TTY only).1176// Prompts for machine name, config path, and local flag, then writes the file.1177pub fn firstRunWizard(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1178    output.firstRunBanner();1179    output.firstRunNoConfig();11801181    var name_buf: [256]u8 = undefined;1182    var path_buf: [256]u8 = undefined;1183    var local_buf: [256]u8 = undefined;11841185    const machine_name = output.firstRunPrompt("machine name", "my-machine", &name_buf);11861187    // Flake-based systems don't have a traditional /etc/nixos/configuration.nix —1188    // their config lives wherever flake.nix is. Ask, then prompt for the right1189    // path and record `flake = true` so channel commands can warn appropriately.1190    const use_flakes = output.firstRunManageType();1191    const config_path = if (use_flakes)1192        output.firstRunPrompt("flake directory", "~/nixos-config", &path_buf)1193    else1194        output.firstRunPrompt("config path", "/etc/nixos", &path_buf);1195    const local_str = output.firstRunPrompt("local", "true", &local_buf);11961197    const conf_path = try config.configPath(gpa, environ);1198    defer gpa.free(conf_path);1199    if (std.fs.path.dirname(conf_path)) |dir| exec.ensureDir(gpa, io, dir);12001201    // `flake` is a top-level config field, so it must precede the [machine] block.1202    const flake_line = if (use_flakes) "flake = true\n" else "";1203    var content_buf: [1024]u8 = undefined;1204    const content = try std.fmt.bufPrint(1205        &content_buf,1206        "{s}[machine]\nname = {s}\nconfig = {s}\nlocal = {s}\n",1207        .{ flake_line, machine_name, config_path, local_str },1208    );12091210    const file = std.Io.Dir.createFile(.cwd(), io, conf_path, .{}) catch {1211        errors.error_info.setMessage("could not write {s}", .{conf_path});1212        return error.Internal;1213    };1214    defer file.close(io);1215    file.writePositionalAll(io, content, 0) catch {1216        errors.error_info.setMessage("could not write {s}", .{conf_path});1217        return error.Internal;1218    };12191220    output.firstRunWritten(conf_path);1221}12221223pub fn setup(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1224    // Create the config first if it doesn't exist. This makes `nina setup`1225    // a complete onboarding command — not just a nix-features check. Any legacy1226    // ~/.nina.conf is migrated to the XDG path before we decide to run the wizard.1227    config.migrateLegacyConfig(gpa, io, environ);1228    if (config.configPath(gpa, environ)) |conf_path| {1229        defer gpa.free(conf_path);1230        if (std.Io.Dir.openFile(.cwd(), io, conf_path, .{})) |f| {1231            f.close(io);1232        } else |_| {1233            try firstRunWizard(gpa, io, environ);1234            errors.error_info.reset();1235        }1236    } else |_| {}12371238    output.setupCheck();1239    const status = exec.checkNixFeatures(gpa, io, environ);1240    output.setupFeatures(status.nix_command, status.flakes);12411242    if (status.allEnabled()) {1243        output.setupAllSet();1244        api.ensureRegistryPinned(gpa, io, environ);1245        return;1246    }12471248    // On NixOS the features belong in configuration.nix (the declarative,1249    // permanent home), not ~/.config/nix/nix.conf. Offer to add the one line;1250    // the user runs the rebuild. We don't pin the registry here because the1251    // features aren't live until that rebuild lands.1252    if (exec.isNixOS(io)) {1253        const conf_path = "/etc/nixos/configuration.nix";1254        if (exec.nixosConfigEnablesFeatures(gpa, io, conf_path)) {1255            output.setupNixosNeedsRebuild(conf_path);1256            return;1257        }1258        output.setupNixosOffer(exec.NIXOS_FEATURES_LINE, conf_path);1259        if (output.confirmDefaultNo("add it now?")) {1260            if (exec.appendFeaturesToNixosConfig(gpa, io, environ, conf_path)) |_| {1261                output.setupNixosWrote(conf_path);1262            } else |_| {1263                output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);1264            }1265        } else {1266            output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);1267        }1268        return;1269    }12701271    // Non-NixOS: a user-level nix.conf takes effect immediately, no sudo needed.1272    output.setupEnabling();1273    const path = try exec.enableNixFeatures(gpa, io, environ);1274    defer gpa.free(path);12751276    output.setupDone(path);1277    api.ensureRegistryPinned(gpa, io, environ);1278}12791280// --- Log helper ---12811282fn logAction(ctx: Ctx, action: []const u8, gen: u32) void {1283    var ts_buf: [32]u8 = undefined;1284    const ts = nowIso(ctx.io, &ts_buf);1285    var buf: [256]u8 = undefined;1286    const entry = std.fmt.bufPrint(&buf, "{{\"ts\":\"{s}\",\"machine\":\"{s}\",\"command\":\"{s}\",\"outcome\":\"success\",\"gen_before\":null,\"gen_after\":{d},\"duration_ms\":0}}\n", .{1287        ts, ctx.machine.name, action, gen,1288    }) catch return;1289    exec.appendNinaLog(ctx.io, ctx.environ, entry);1290}12911292// Wall-clock UTC as ISO-8601. Uses Io.Clock.real (the settable Unix-epoch clock);1293// Io.Clock.awake is monotonic and unsuitable for timestamps. Falls back to epoch 0.1294fn nowIso(io: std.Io, buf: []u8) []const u8 {1295    const fallback = "1970-01-01T00:00:00Z";1296    const ns = std.Io.Clock.real.now(io).toNanoseconds();1297    if (ns <= 0) return fallback;1298    const secs: u64 = @intCast(@divFloor(ns, 1_000_000_000));1299    const es = std.time.epoch.EpochSeconds{ .secs = secs };1300    const ed = es.getEpochDay();1301    const yd = ed.calculateYearDay();1302    const md = yd.calculateMonthDay();1303    const ds = es.getDaySeconds();1304    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", .{1305        yd.year, md.month.numeric(), @as(u32, md.day_index) + 1,1306        ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(),1307    }) catch return fallback;1308}