commands.zig

46.5 KB · raw

1// commands.zig — all command handlers2// Orchestrates exec/api/output. Zero direct stdout writes.3const std = @import("std");4const builtin = @import("builtin");5const types = @import("types.zig");6const errors = @import("errors.zig");7const config = @import("config.zig");8const output = @import("output.zig");9const exec = @import("exec.zig");10const api = @import("api.zig");11const search_tui = @import("search.zig");12const version = @import("version.zig");1314const UPDATE_URL = "https://kepr.uk/api/nina/releases/latest";1516pub const Ctx = struct {17    gpa: std.mem.Allocator,18    io: std.Io,19    environ: *const std.process.Environ.Map,20    machine: types.Machine,21    cfg: types.NinaConfig,22    args: []const []const u8,   // positional args after subcommand23    sub: []const u8,            // subcommand (e.g. "list" in "service list")24    dry: bool,25    check: bool,26    no_apply: bool,27    all: bool,28    last: u32,29    json: bool,30};3132pub fn apply(ctx: Ctx) !void {33    if (ctx.dry) {34        output.applyDry(ctx.machine.name);35        const code = try exec.nixosRebuildDryActivate(ctx.io, &ctx.machine, ctx.gpa);36        if (code != 0) return error.BuildFailed;37        output.applyDryDone();38        return;39    }40    if (ctx.check) {41        return check(ctx);42    }4344    output.applyStart(ctx.machine.name);45    const start = std.Io.Clock.awake.now(ctx.io);4647    const code = exec.nixosRebuildSwitch(ctx.io, &ctx.machine, ctx.gpa) catch |e| {48        exec.markApplyFailed(ctx.io, ctx.environ);49        output.applyFailed("");50        return e;51    };5253    if (code != 0) {54        exec.markApplyFailed(ctx.io, ctx.environ);55        output.applyFailed("");56        return error.BuildFailed;57    }5859    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());60    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));61    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;62    const after_failure = exec.takeApplyFailed(ctx.io, ctx.environ);63    output.applyDone(gen, elapsed, after_failure);64    logAction(ctx, "apply", gen);65}6667pub fn check(ctx: Ctx) !void {68    output.checkStart(ctx.machine.name);69    const code = try exec.nixosRebuildBuild(ctx.io, &ctx.machine, ctx.gpa);70    if (code != 0) {71        output.checkFailed("");72        return error.BuildFailed;73    }74    output.checkOk();75}7677pub fn back(ctx: Ctx) !void {78    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);79    defer ctx.gpa.free(gens);8081    var current: u32 = 0;82    for (gens) |g| if (g.current) { current = g.number; };8384    // Newest generation older than current. If there is none, we're already at the85    // oldest — stop cleanly instead of letting rollback fail with 'build failed'.86    var prev: u32 = 0;87    var has_prev = false;88    for (gens) |g| {89        if (g.number < current and (!has_prev or g.number > prev)) {90            prev = g.number;91            has_prev = true;92        }93    }94    if (!has_prev) {95        output.alreadyOldest();96        return;97    }9899    output.backStart(ctx.machine.name, current, prev);100    if (ctx.cfg.confirm and !output.confirm("")) return;101102    const code = try exec.rollback(ctx.io, &ctx.machine, ctx.gpa);103    if (code != 0) return error.BuildFailed;104    output.backDone(prev);105}106107pub fn go(ctx: Ctx) !void {108    if (ctx.args.len == 0) return error.Internal;109    const target = std.fmt.parseInt(u32, ctx.args[0], 10) catch return error.Internal;110    const current = try exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine);111112    output.goStart(ctx.machine.name, current, target);113    if (ctx.cfg.confirm and !output.confirm("")) return;114115    const code = try exec.switchGeneration(ctx.io, &ctx.machine, ctx.gpa, target);116    if (code != 0) return error.ProcessFailed;117    output.generationDone(target);118}119120pub fn history(ctx: Ctx) !void {121    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);122    defer ctx.gpa.free(gens);123    output.historyHeader(ctx.machine.name);124    for (gens) |g| output.historyRow(g);125}126127pub fn genCmd(ctx: Ctx) !void {128    if (std.mem.eql(u8, ctx.sub, "list")) return history(ctx);129    if (std.mem.eql(u8, ctx.sub, "current")) {130        const n = try exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine);131        output.genCurrent(n);132        return;133    }134    if (std.mem.eql(u8, ctx.sub, "delete")) {135        if (ctx.args.len == 0) return error.Internal;136        if (std.mem.eql(u8, ctx.args[0], "old")) {137            if (ctx.cfg.confirm and !output.confirm("")) return;138            _ = try exec.deleteOldGenerations(ctx.io, &ctx.machine, ctx.gpa);139        } else {140            const n = std.fmt.parseInt(u32, ctx.args[0], 10) catch return error.Internal;141            if (ctx.cfg.confirm and !output.confirm("")) return;142            _ = try exec.deleteGeneration(ctx.io, &ctx.machine, ctx.gpa, n);143        }144        output.done();145        return;146    }147    return error.Internal;148}149150pub fn clean(ctx: Ctx) !void {151    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);152    defer ctx.gpa.free(gens);153    const all = ctx.all or std.mem.eql(u8, ctx.sub, "all");154    const total: u32 = @intCast(gens.len);155    // `clean all` keeps only the current generation; otherwise keep the configured156    // count. With nothing older than the keep limit, there's nothing to collect.157    const keep: u32 = if (all) 1 else ctx.cfg.generations;158    if (total <= keep) {159        output.cleanNothing(ctx.machine.name, total);160        return;161    }162    output.cleanStart(ctx.machine.name, keep, total);163    if (ctx.cfg.confirm and !output.confirm("removing — cannot be undone")) return;164    _ = try exec.collectGarbage(ctx.io, &ctx.machine, ctx.gpa, all, ctx.cfg.generations);165    output.cleanDone();166}167168pub fn statusCmd(ctx: Ctx) !void {169    output.statusHeader();170    // --all renders every configured machine; remotes route through the same SSH171    // path as exec.capture. An unreachable machine is shown in red, not fatal.172    if (ctx.all and ctx.cfg.machines.len > 0) {173        for (ctx.cfg.machines) |m| statusRowFor(ctx, &m);174        return;175    }176    statusRowFor(ctx, &ctx.machine);177}178179fn statusRowFor(ctx: Ctx, machine: *const types.Machine) void {180    // A failure to read the current generation means we couldn't reach or query181    // the machine — mark it unreachable rather than reporting a bogus gen 0.182    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, machine) catch {183        output.statusRow(machine.name, 0, "", "", false);184        return;185    };186    const st = exec.systemStatus(ctx.gpa, ctx.io, machine);187    defer ctx.gpa.free(st.size);188    defer ctx.gpa.free(st.age);189    output.statusRow(machine.name, gen, st.age, st.size, true);190}191192pub fn diff(ctx: Ctx) !void {193    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);194    defer ctx.gpa.free(gens);195    var current: u32 = 0;196    var prev: u32 = 0;197    for (gens) |g| {198        if (g.current) current = g.number;199        if (!g.current and g.number > prev and g.number < current) prev = g.number;200    }201    if (ctx.args.len >= 2) {202        const a = std.fmt.parseInt(u32, ctx.args[0], 10) catch current - 1;203        const b = std.fmt.parseInt(u32, ctx.args[1], 10) catch current;204        output.diffHeader(a, b, ctx.machine.name);205        if (try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, a, b) != 0) return error.ProcessFailed;206    } else {207        output.diffHeader(if (prev > 0) prev else current - 1, current, ctx.machine.name);208        if (try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, if (prev > 0) prev else current - 1, current) != 0) return error.ProcessFailed;209    }210}211212pub fn mood(ctx: Ctx) !void {213    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;214    const st = exec.systemStatus(ctx.gpa, ctx.io, &ctx.machine);215    defer ctx.gpa.free(st.size);216    defer ctx.gpa.free(st.age);217    const state = exec.systemRunningState(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");218    defer ctx.gpa.free(state);219    output.mood(ctx.machine.name, state, gen, st.age, st.size);220}221222pub fn doctor(ctx: Ctx) !void {223    output.doctorHeader(ctx.machine.name);224    const checks = try exec.runDoctorChecks(ctx.gpa, ctx.io, &ctx.machine);225    defer ctx.gpa.free(checks);226    var warnings: u32 = 0;227    var failures: u32 = 0;228    for (checks) |ch| {229        output.doctorRow(ch);230        if (ch.status == .warn) warnings += 1;231        if (ch.status == .fail) failures += 1;232    }233    output.doctorSummary(warnings, failures);234}235236// nina update — kepr self-update for the nina binary itself.237pub fn update(ctx: Ctx) !void {238    output.updateSelfStart();239240    if (comptime std.mem.eql(u8, version.PLATFORM, "unsupported")) {241        output.updateSelfNoPlatform(@tagName(builtin.cpu.arch) ++ "-" ++ @tagName(builtin.os.tag));242        return error.Internal;243    }244245    const env_url = ctx.environ.get("NINA_UPDATE_SOURCE");246    const source_url = env_url orelse UPDATE_URL;247248    const body = exec.fetchUrl(ctx.gpa, ctx.io, source_url) catch |e| switch (e) {249        error.NetworkError, error.HttpError => {250            output.updateSelfNetworkError();251            return;252        },253        else => return e,254    };255    defer ctx.gpa.free(body);256257    const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, body, .{}) catch {258        output.printWarning("could not parse release metadata");259        return;260    };261    defer parsed.deinit();262263    const root = parsed.value;264    if (root != .object) { output.printWarning("malformed release metadata"); return; }265266    const remote_ver = blk: {267        const v = root.object.get("version") orelse { output.printWarning("malformed release metadata"); return; };268        break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };269    };270271    if (std.mem.eql(u8, remote_ver, version.VERSION)) {272        output.updateSelfCurrent(version.VERSION);273        return;274    }275276    output.updateSelfAvailable(version.VERSION, remote_ver);277    if (ctx.check) return;278279    var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;280    const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {281        errors.error_info.setMessage("could not determine install path", .{});282        return error.Internal;283    };284285    // When running from the nix store, defer to nix profile upgrade so nix286    // manages the transition (the store is read-only; binary replacement fails).287    // A NixOS system install also resolves into the store but isn't a profile288    // element, so check the profile to avoid a no-op `upgrade` — it updates with289    // the next nixos-rebuild instead.290    if (std.mem.startsWith(u8, install_path, "/nix/store/")) {291        const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);292        defer {293            if (nina_element) |n| ctx.gpa.free(n);294        }295        if (nina_element == null) {296            output.updateSelfNotInProfile();297            return;298        }299        const element = nina_element.?;300        output.updateSelfNixManaged(remote_ver);301        if (ctx.cfg.confirm and !output.confirm("")) return;302        const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "upgrade", element }) catch {303            output.updateSelfNixFailed();304            return;305        };306        if (ec != 0) output.updateSelfNixFailed();307        return;308    }309310    const plat_info = blk: {311        const pv = root.object.get("platforms") orelse break :blk null;312        if (pv != .object) break :blk null;313        break :blk pv.object.get(version.PLATFORM);314    };315    if (plat_info == null) { output.updateSelfNoPlatform(version.PLATFORM); return; }316317    const dl_url = blk: {318        const v = plat_info.?.object.get("url") orelse { output.printWarning("malformed release metadata"); return; };319        break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };320    };321322    const raw_cksum = blk: {323        if (plat_info.?.object.get("blake3")) |v|324            break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };325        if (plat_info.?.object.get("checksum")) |v|326            break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };327        output.printWarning("missing checksum in release metadata");328        return;329    };330    const expected_hex = if (std.mem.startsWith(u8, raw_cksum, "blake3:")) raw_cksum["blake3:".len..] else raw_cksum;331332    if (ctx.cfg.confirm and !output.confirm("")) return;333334    output.updateSelfDownloading(remote_ver, version.PLATFORM);335    const tmp_path = exec.downloadToTemp(ctx.gpa, ctx.io, dl_url) catch {336        output.printWarning("download failed — check your connection and try again");337        return;338    };339    defer ctx.gpa.free(tmp_path);340341    output.updateSelfVerifying();342    exec.verifyAndInstall(ctx.gpa, ctx.io, tmp_path, expected_hex, install_path) catch |e| switch (e) {343        error.ChecksumMismatch => { output.updateSelfChecksumFailed(); return; },344        else => return e,345    };346347    output.updateSelfDone(version.VERSION, remote_ver);348}349350// nina goodbye — clean uninstall. Three install paths:351// - nix profile (binary in nix store with a profile element) → nix profile remove352// - koh build or source build (plain binary on PATH) → delete the file353pub fn goodbye(ctx: Ctx) !void {354    output.goodbyeStart();355356    var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;357    const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {358        errors.error_info.setMessage("could not determine install path", .{});359        return error.Internal;360    };361362    // A binary outside the nix store is a koh build or source build — delete it.363    if (!std.mem.startsWith(u8, install_path, "/nix/store/")) {364        output.goodbyeFile(install_path);365        if (ctx.cfg.confirm and !output.confirm("")) return;366        std.Io.Dir.deleteFileAbsolute(ctx.io, install_path) catch |e| {367            errors.error_info.setMessage("could not remove {s}", .{install_path});368            return e;369        };370        output.goodbyeDone();371        return;372    }373374    // Binary is in the nix store — find and remove the profile element.375    const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);376    defer {377        if (nina_element) |n| ctx.gpa.free(n);378    }379380    if (nina_element == null) {381        errors.error_info.setMessage("nina not found in nix profile — was it installed via 'nix profile add'?", .{});382        return error.Internal;383    }384385    output.goodbyeNix();386    if (ctx.cfg.confirm and !output.confirm("")) return;387    const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "remove", nina_element.? }) catch {388        output.goodbyeFailed("nix profile remove failed");389        return;390    };391    if (ec != 0) {392        output.goodbyeFailed("nix profile remove failed");393        return;394    }395    output.goodbyeDone();396}397398fn channelUpdateCmd(ctx: Ctx) !void {399    output.updateStart(ctx.machine.name);400    _ = try exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa);401    output.updateDone();402}403404pub fn upgrade(ctx: Ctx) !void {405    output.upgradeStart(ctx.machine.name);406    output.printSubstep("updating channels", .{});407    _ = exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa) catch {};408    output.printSubstep("rebuilding", .{});409    const start = std.Io.Clock.awake.now(ctx.io);410    const code = try exec.nixosRebuildSwitch(ctx.io, &ctx.machine, ctx.gpa);411    if (code != 0) {412        output.applyFailed("");413        return error.BuildFailed;414    }415    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());416    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));417    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;418    output.applyDone(gen, elapsed, false);419}420421pub fn log(ctx: Ctx) !void {422    output.logHeader(ctx.machine.name);423    const content = exec.readNinaLog(ctx.gpa, ctx.io, ctx.environ, ctx.last) catch {424        // No log yet — that's fine425        return;426    };427    defer ctx.gpa.free(content);428    var lines = std.mem.splitScalar(u8, content, '\n');429    while (lines.next()) |line| {430        const t = std.mem.trim(u8, line, " \t\r");431        if (t.len == 0) continue;432        if (t[0] == '{') {433            renderJsonLogLine(ctx.gpa, t);434        } else {435            // legacy tab-separated format436            var parts = std.mem.tokenizeScalar(u8, t, '\t');437            const date = parts.next() orelse continue;438            const time = parts.next() orelse "";439            const action = parts.next() orelse "";440            const detail = parts.next() orelse "";441            output.logRow(date, time, action, detail);442        }443    }444}445446// The on-disk log is JSON Lines: {"ts","machine","command","outcome","gen_after",...}.447// Render ts -> date/time columns, command -> action, outcome(+gen) -> detail.448fn renderJsonLogLine(gpa: std.mem.Allocator, line: []const u8) void {449    const parsed = std.json.parseFromSlice(std.json.Value, gpa, line, .{}) catch {450        output.logRow(line, "", "", ""); // unparseable — show raw rather than drop451        return;452    };453    defer parsed.deinit();454    if (parsed.value != .object) return;455    const o = parsed.value.object;456457    const ts = jsonStr(o, "ts");458    const date = if (ts.len >= 10) ts[0..10] else ts;459    const time = if (ts.len >= 16) ts[11..16] else "";460    const action = jsonStr(o, "command");461    const outcome = jsonStr(o, "outcome");462463    var buf: [160]u8 = undefined;464    var detail: []const u8 = outcome;465    if (o.get("gen_after")) |g| {466        if (g == .integer) {467            detail = std.fmt.bufPrint(&buf, "{s}   -> gen {d}", .{ outcome, g.integer }) catch outcome;468        }469    }470    output.logRow(date, time, action, detail);471}472473fn jsonStr(o: std.json.ObjectMap, key: []const u8) []const u8 {474    if (o.get(key)) |v| {475        if (v == .string) return v.string;476    }477    return "";478}479480pub fn edit(ctx: Ctx) !void {481    const hardware = ctx.args.len > 0 and std.mem.eql(u8, ctx.args[0], "hardware");482    const filename = if (hardware) "hardware-configuration.nix" else "configuration.nix";483    const path = try std.fmt.allocPrint(ctx.gpa, "{s}/{s}", .{ ctx.machine.config_path, filename });484    defer ctx.gpa.free(path);485    output.editOpen(path, ctx.cfg.editor);486    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);487}488489pub fn fmt(ctx: Ctx) !void {490    const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});491    defer ctx.gpa.free(path);492    if (ctx.check) {493        const code = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, true);494        if (code != 0) output.fmtNeedsFormat() else output.fmtDone();495        return;496    }497    output.fmtStart(path);498    _ = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, false);499    output.fmtDone();500}501502pub fn repl(ctx: Ctx) !void {503    output.replStart();504    _ = try exec.nixRepl(ctx.io, &ctx.machine, ctx.gpa);505}506507pub fn develop(ctx: Ctx) !void {508    if (std.mem.eql(u8, ctx.sub, "show")) {509        _ = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, null);510        return;511    }512    const run_cmd: ?[]const u8 = if (ctx.args.len > 0 and std.mem.eql(u8, ctx.sub, "run"))513        ctx.args[0]514    else515        null;516    output.developStart(&.{});517    _ = try exec.nixDevelopPs1(ctx.io, &ctx.machine, ctx.gpa, run_cmd, ctx.environ);518    output.developDone();519}520521pub fn info(ctx: Ctx) !void {522    output.infoHeader(ctx.machine.name);523    const nixos_ver = exec.systemInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");524    defer ctx.gpa.free(nixos_ver);525    output.infoRow("nixos", std.mem.trim(u8, nixos_ver, " \t\n\r"));526527    const kernel = exec.kernelInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");528    defer ctx.gpa.free(kernel);529    output.infoRow("kernel", std.mem.trim(u8, kernel, " \t\n\r"));530531    const uptime = exec.uptimeInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");532    defer ctx.gpa.free(uptime);533    output.infoRow("uptime", std.mem.trim(u8, uptime, " \t\n\r"));534}535536pub fn boot(ctx: Ctx) !void {537    output.bootHeader(ctx.machine.name);538    const entries = exec.bootEntries(ctx.gpa, ctx.io, &ctx.machine) catch &.{};539    defer ctx.gpa.free(entries);540    for (entries, 0..) |entry, i| output.bootEntry(entry, i);541}542543pub fn searchCmd(ctx: Ctx) !void {544    const query = if (ctx.args.len > 0) ctx.args[0] else "";545    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);546    const selected = try search_tui.run(ctx.gpa, ctx.io, query, .packages);547    if (selected) |npkg| try selectAndInstall(ctx, npkg);548}549550pub fn optionCmd(ctx: Ctx) !void {551    const query = if (ctx.args.len > 0) ctx.args[0] else "";552    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);553    _ = try search_tui.run(ctx.gpa, ctx.io, query, .options);554}555556pub fn install(ctx: Ctx) !void {557    const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;558559    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);560561    // Search for the package to get the attr562    const pkgs = api.searchPackages(ctx.gpa, ctx.io, pkg_name) catch {563        errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});564        errors.error_info.setSuggestion("nina search {s}", .{pkg_name});565        return error.PackageNotFound;566    };567568    if (pkgs.len == 0) {569        // No matches — likely a typo. Suggest the closest real package and offer it.570        if (closestPackage(ctx, pkg_name)) |sugg| {571            output.didYouMean(pkg_name, sugg.pname);572            if (output.confirm("")) try selectAndInstall(ctx, sugg);573            return;574        }575        errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});576        errors.error_info.setSuggestion("nina search {s}", .{pkg_name});577        return error.PackageNotFound;578    }579580    // Prefer an exact name match over the first search result — `install ripgrep`581    // must pick "ripgrep", not the alphabetically-first match like "repgrep".582    var found = pkgs[0];583    for (pkgs) |p| {584        if (std.mem.eql(u8, p.pname, pkg_name)) {585            found = p;586            break;587        }588    }589    try selectAndInstall(ctx, found);590}591592// Find the real package whose name is closest to a not-found query (typo help).593// Typos usually keep the leading characters, so gather candidates with a prefix594// search and rank by edit distance; return the best only if it's typo-close.595fn closestPackage(ctx: Ctx, query: []const u8) ?types.NixPackage {596    if (query.len < 2) return null;597    var candidates = api.searchPackages(ctx.gpa, ctx.io, query[0..@min(query.len, 4)]) catch &.{};598    if (candidates.len == 0 and query.len > 2) {599        candidates = api.searchPackages(ctx.gpa, ctx.io, query[0..2]) catch &.{};600    }601    if (candidates.len == 0) return null;602603    var best: ?types.NixPackage = null;604    var best_dist: usize = std.math.maxInt(usize);605    for (candidates) |p| {606        const d = editDistance(query, p.pname);607        if (d > 0 and d < best_dist) {608            best_dist = d;609            best = p;610        }611    }612    // Only suggest a genuinely close name, scaled to query length.613    const threshold = @max(@as(usize, 2), query.len / 3);614    return if (best_dist <= threshold) best else null;615}616617// Case-insensitive Levenshtein distance. Names longer than the row buffer are618// treated as far away (never suggested).619fn editDistance(a: []const u8, b: []const u8) usize {620    const n = b.len;621    if (a.len == 0) return n;622    if (n == 0) return a.len;623    if (n + 1 > 128) return std.math.maxInt(usize);624    var prev: [128]usize = undefined;625    var curr: [128]usize = undefined;626    var j: usize = 0;627    while (j <= n) : (j += 1) prev[j] = j;628    var i: usize = 1;629    while (i <= a.len) : (i += 1) {630        curr[0] = i;631        j = 1;632        while (j <= n) : (j += 1) {633            const cost: usize = if (std.ascii.toLower(a[i - 1]) == std.ascii.toLower(b[j - 1])) 0 else 1;634            curr[j] = @min(prev[j] + 1, @min(curr[j - 1] + 1, prev[j - 1] + cost));635        }636        @memcpy(prev[0 .. n + 1], curr[0 .. n + 1]);637    }638    return prev[n];639}640641test "editDistance is case-insensitive Levenshtein" {642    try std.testing.expectEqual(@as(usize, 1), editDistance("firefux", "firefox"));643    try std.testing.expectEqual(@as(usize, 0), editDistance("git", "GIT"));644    try std.testing.expectEqual(@as(usize, 2), editDistance("fierfox", "firefox"));645    try std.testing.expectEqual(@as(usize, 7), editDistance("", "firefox"));646}647648// Prompt for the install method (profile / system / try) and dispatch. Shared by649// `nina install <pkg>` and the search widget's Enter-to-select — the letter keys650// are read here, after the search widget's raw mode is gone, so they don't651// collide with typing a query.652fn selectAndInstall(ctx: Ctx, npkg: types.NixPackage) !void {653    output.installSelectPrompt(npkg.pname, npkg.version);654655    var choice_buf: [8]u8 = undefined;656    var choice_len: usize = 0;657    while (choice_len < choice_buf.len) {658        const n = std.posix.read(std.posix.STDIN_FILENO, choice_buf[choice_len .. choice_len + 1]) catch break;659        if (n == 0) break;660        if (choice_buf[choice_len] == '\n') break;661        choice_len += 1;662    }663    const choice = std.mem.trim(u8, choice_buf[0..choice_len], " \t");664665    if (choice.len == 0 or choice[0] == 'i' or choice[0] == 'I') {666        try profileInstallPkg(ctx, npkg);667    } else if (choice[0] == 's' or choice[0] == 'S') {668        try systemInstallPkg(ctx, npkg);669    } else if (choice[0] == 't' or choice[0] == 'T') {670        try tryPkg(ctx, npkg);671    }672}673674fn profileInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {675    output.installStart(npkg.pname, .profile);676    output.printSubstep("nix profile add nixpkgs#{s}", .{npkg.attr});677    output.printTeach(try std.fmt.allocPrint(ctx.gpa, "nix profile add nixpkgs#{s}", .{npkg.attr}));678    const code = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, npkg.attr);679    if (code != 0) return error.ProcessFailed;680    output.installDone(npkg.pname);681}682683fn systemInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {684    const config_path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});685    defer ctx.gpa.free(config_path);686    const line = api.findSystemPackagesLine(ctx.io, config_path) orelse 1;687    output.installEditorPrompt(npkg.pname, config_path, line, ctx.cfg.editor);688    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, config_path, line);689    if (ctx.cfg.confirm) {690        if (output.confirm("apply now? ")) {691            try apply(ctx);692        }693    }694}695696fn tryPkg(ctx: Ctx, npkg: types.NixPackage) !void {697    output.tryStart(npkg.pname);698    output.printSubstep("nix shell nixpkgs#{s}", .{npkg.attr});699    output.tryExitHint();700    _ = try exec.nixShellPs1(ctx.io, &ctx.machine, ctx.gpa, npkg.attr, ctx.environ);701    output.tryDone();702}703704pub fn remove(ctx: Ctx) !void {705    const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;706    output.removeStart(pkg_name);707    const code = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, pkg_name);708    if (code != 0) return error.ProcessFailed;709    output.done();710}711712pub fn list(ctx: Ctx) !void {713    output.listHeader(ctx.machine.name);714715    // Profile packages: parse `nix profile list --json` into clean name+version716    // rows instead of dumping nix's verbose multi-line "Name:/Flake attribute:"717    // blocks.718    if (exec.profileListJson(ctx.gpa, ctx.io, &ctx.machine) catch null) |json| {719        defer ctx.gpa.free(json);720        output.listSection("profile");721        renderProfileJson(ctx.gpa, json);722    }723724    // System packages: the references of /run/current-system/sw, each a725    // <hash>-<name>-<version> store path.726    if (exec.systemPackagePaths(ctx.gpa, ctx.io, &ctx.machine) catch null) |paths| {727        defer ctx.gpa.free(paths);728        output.blankLine();729        output.listSection("system");730        var lines = std.mem.splitScalar(u8, paths, '\n');731        while (lines.next()) |line| {732            const t = std.mem.trim(u8, line, " \t\r");733            if (t.len == 0) continue;734            const row = pkgFromStorePath(t);735            // Skip support paths with no parseable version (man pages, wrappers).736            if (row.version.len == 0) continue;737            output.listPkg(row.name, row.version);738        }739    }740}741742const PkgRow = struct { name: []const u8, version: []const u8 };743744// Split a nix store path basename (<hash>-<name>-<version>) into name + version.745// Version begins at the first '-' followed by a digit, which reliably lands on746// the name/version boundary since the 32-char hash and package names start with747// non-digits.748fn pkgFromStorePath(path: []const u8) PkgRow {749    const base = std.fs.path.basename(path);750    const after_hash = if (base.len > 33 and base[32] == '-') base[33..] else base;751    var i: usize = 0;752    while (i + 1 < after_hash.len) : (i += 1) {753        if (after_hash[i] == '-' and std.ascii.isDigit(after_hash[i + 1])) {754            return .{ .name = after_hash[0..i], .version = stripOutputSuffix(after_hash[i + 1 ..]) };755        }756    }757    return .{ .name = after_hash, .version = "" };758}759760// Multi-output derivations append the output name to the store path (e.g.761// curl-8.20.0-bin, less-692-man). Strip that suffix so the version column reads762// as just the version.763fn stripOutputSuffix(ver: []const u8) []const u8 {764    const suffixes = [_][]const u8{ "-bin", "-man", "-dev", "-doc", "-lib", "-info", "-out", "-static", "-devdoc" };765    for (suffixes) |s| {766        if (std.mem.endsWith(u8, ver, s)) return ver[0 .. ver.len - s.len];767    }768    return ver;769}770771test "pkgFromStorePath splits name and version at first dash-digit" {772    const a = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-ripgrep-15.1.0");773    try std.testing.expectEqualStrings("ripgrep", a.name);774    try std.testing.expectEqualStrings("15.1.0", a.version);775776    const b = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-helix-25.01");777    try std.testing.expectEqualStrings("helix", b.name);778    try std.testing.expectEqualStrings("25.01", b.version);779780    // multi-output store paths drop their output-name suffix781    const c = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-curl-8.20.0-bin");782    try std.testing.expectEqualStrings("curl", c.name);783    try std.testing.expectEqualStrings("8.20.0", c.version);784}785786fn firstStorePath(el: std.json.Value) ?[]const u8 {787    if (el != .object) return null;788    const sp = el.object.get("storePaths") orelse return null;789    if (sp != .array or sp.array.items.len == 0) return null;790    const first = sp.array.items[0];791    return if (first == .string) first.string else null;792}793794// `nix profile list --json` has two shapes across nix versions: newer keys each795// element by name (object), older lists them positionally (array). Handle both.796fn renderProfileJson(gpa: std.mem.Allocator, json: []const u8) void {797    const parsed = std.json.parseFromSlice(std.json.Value, gpa, json, .{}) catch return;798    defer parsed.deinit();799    if (parsed.value != .object) return;800    const elements = parsed.value.object.get("elements") orelse return;801    switch (elements) {802        .object => |obj| {803            var it = obj.iterator();804            while (it.next()) |entry| {805                const ver = if (firstStorePath(entry.value_ptr.*)) |p| pkgFromStorePath(p).version else "";806                output.listPkg(entry.key_ptr.*, ver);807            }808        },809        .array => |arr| {810            for (arr.items) |el| {811                const path = firstStorePath(el) orelse continue;812                const row = pkgFromStorePath(path);813                output.listPkg(row.name, row.version);814            }815        },816        else => {},817    }818}819820pub fn tryCmd(ctx: Ctx) !void {821    const pkg_name_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;822    const shell_pkg = types.NixPackage{ .attr = pkg_name_arg, .pname = pkg_name_arg, .version = "", .description = "" };823    try tryPkg(ctx, shell_pkg);824}825826// --- Service commands ---827828pub fn service(ctx: Ctx) !void {829    if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {830        output.serviceListHeader(ctx.machine.name);831        const svcs = exec.serviceList(ctx.gpa, ctx.io, &ctx.machine) catch &.{};832        defer ctx.gpa.free(svcs);833        for (svcs) |s| output.serviceRow(s);834        return;835    }836    if (std.mem.eql(u8, ctx.sub, "logs")) {837        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;838        const follow = ctx.args.len > 1 and std.mem.eql(u8, ctx.args[1], "-f");839        output.serviceLogsHeader(name, ctx.last, ctx.machine.name);840        _ = try exec.serviceLogs(ctx.io, &ctx.machine, ctx.gpa, name, ctx.last, follow);841        return;842    }843    if (std.mem.eql(u8, ctx.sub, "status")) {844        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;845        output.serviceVerb("status", name, ctx.machine.name);846        _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, "status", name);847        return;848    }849    // start/stop/restart/enable/disable850    const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;851    if (ctx.cfg.confirm and (std.mem.eql(u8, ctx.sub, "stop") or std.mem.eql(u8, ctx.sub, "disable"))) {852        if (!output.confirm("")) return;853    }854    output.serviceVerb(ctx.sub, name, ctx.machine.name);855    _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, ctx.sub, name);856    output.serviceDone();857}858859// --- Flake commands ---860861pub fn flake(ctx: Ctx) !void {862    if (std.mem.eql(u8, ctx.sub, "update")) {863        output.flakeUpdateStart();864        const input: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;865        _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);866        output.flakeLockWritten();867        return;868    }869    if (std.mem.eql(u8, ctx.sub, "check")) {870        output.flakeCheckStart();871        const code = try exec.flakeCheck(ctx.io, &ctx.machine, ctx.gpa);872        if (code == 0) output.flakeValid() else output.checkFailed("");873        return;874    }875    if (std.mem.eql(u8, ctx.sub, "show")) {876        const json_out = exec.flakeShow(ctx.gpa, ctx.io, &ctx.machine) catch null;877        if (json_out) |j| {878            defer ctx.gpa.free(j);879            output.flakeShowHeader("flake outputs");880            // Parse and display the flake outputs881            const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, j, .{}) catch return;882            defer parsed.deinit();883            if (parsed.value == .object) {884                var it = parsed.value.object.iterator();885                while (it.next()) |entry| {886                    if (entry.value_ptr.* == .object) {887                        var inner = entry.value_ptr.object.iterator();888                        while (inner.next()) |e2| {889                            const desc = if (e2.value_ptr.* == .object)890                                if (e2.value_ptr.object.get("description")) |d|891                                    if (d == .string) d.string else ""892                                else ""893                            else "";894                            output.flakeShowEntry(entry.key_ptr.*, e2.key_ptr.*, desc);895                        }896                    }897                }898            }899        }900        return;901    }902    if (std.mem.eql(u8, ctx.sub, "init")) {903        _ = try exec.flakeInit(ctx.io, &ctx.machine, ctx.gpa);904        return;905    }906    if (std.mem.eql(u8, ctx.sub, "lock")) {907        _ = try exec.flakeLock(ctx.io, &ctx.machine, ctx.gpa);908        return;909    }910    if (std.mem.eql(u8, ctx.sub, "clone")) {911        const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;912        _ = try exec.flakeClone(ctx.io, &ctx.machine, ctx.gpa, url);913        return;914    }915}916917// --- Store commands ---918919pub fn store(ctx: Ctx) !void {920    if (std.mem.eql(u8, ctx.sub, "gc")) {921        _ = try exec.storeGc(ctx.io, &ctx.machine, ctx.gpa);922        return;923    }924    if (std.mem.eql(u8, ctx.sub, "verify")) {925        output.storeVerifyStart();926        _ = try exec.storeVerify(ctx.io, &ctx.machine, ctx.gpa);927        return;928    }929    if (std.mem.eql(u8, ctx.sub, "repair")) {930        if (ctx.cfg.confirm and !output.confirm("")) return;931        output.storeRepairStart();932        _ = try exec.storeRepair(ctx.io, &ctx.machine, ctx.gpa);933        return;934    }935    if (std.mem.eql(u8, ctx.sub, "info")) {936        const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);937        output.storeInfo(si);938        return;939    }940    if (std.mem.eql(u8, ctx.sub, "path")) {941        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;942        const path = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, attr);943        defer ctx.gpa.free(path);944        output.storePath(path);945        return;946    }947    // default: info948    const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);949    output.storeInfo(si);950}951952// --- Channel commands ---953954pub fn channel(ctx: Ctx) !void {955    if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {956        output.channelListHeader(ctx.machine.name);957        const chans = try exec.channelList(ctx.gpa, ctx.io, &ctx.machine);958        defer ctx.gpa.free(chans);959        for (chans) |ch| output.channelRow(ch);960        return;961    }962    if (std.mem.eql(u8, ctx.sub, "add")) {963        const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;964        const name = if (ctx.args.len > 1) ctx.args[1] else "";965        _ = try exec.channelAdd(ctx.io, &ctx.machine, ctx.gpa, url, name);966        output.channelDone();967        return;968    }969    if (std.mem.eql(u8, ctx.sub, "remove")) {970        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;971        _ = try exec.channelRemove(ctx.io, &ctx.machine, ctx.gpa, name);972        output.channelDone();973        return;974    }975    if (std.mem.eql(u8, ctx.sub, "update")) {976        return channelUpdateCmd(ctx);977    }978}979980// --- Profile commands ---981982pub fn profile(ctx: Ctx) !void {983    if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {984        output.profileListHeader();985        const out = exec.profileList(ctx.gpa, ctx.io, &ctx.machine) catch null;986        if (out) |o| {987            defer ctx.gpa.free(o);988            var lines = std.mem.splitScalar(u8, o, '\n');989            while (lines.next()) |line| {990                const t = std.mem.trim(u8, line, " \t\r");991                if (t.len == 0) continue;992                output.profileRow(t, "", "");993            }994        }995        return;996    }997    if (std.mem.eql(u8, ctx.sub, "install")) {998        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;999        _ = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, attr);1000        output.done();1001        return;1002    }1003    if (std.mem.eql(u8, ctx.sub, "remove")) {1004        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1005        _ = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, attr);1006        output.done();1007        return;1008    }1009    if (std.mem.eql(u8, ctx.sub, "upgrade")) {1010        _ = try exec.profileUpgrade(ctx.io, &ctx.machine, ctx.gpa);1011        output.done();1012        return;1013    }1014}10151016// --- Pkg commands ---10171018pub fn pkg(ctx: Ctx) !void {1019    const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1020    if (std.mem.eql(u8, ctx.sub, "why")) {1021        _ = try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name);1022        return;1023    }1024    if (std.mem.eql(u8, ctx.sub, "deps")) {1025        _ = try exec.pkgDeps(ctx.io, &ctx.machine, ctx.gpa, name);1026        return;1027    }1028    if (std.mem.eql(u8, ctx.sub, "size")) {1029        const s = exec.pkgSize(ctx.gpa, ctx.io, &ctx.machine, name) catch null;1030        if (s) |sz| {1031            defer ctx.gpa.free(sz);1032            output.pkgResult("size", sz);1033        }1034        return;1035    }1036    if (std.mem.eql(u8, ctx.sub, "path")) {1037        const p = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, name);1038        defer ctx.gpa.free(p);1039        output.pkgResult("path", p);1040        return;1041    }1042    if (std.mem.eql(u8, ctx.sub, "closure")) {1043        _ = try exec.pkgClosure(ctx.io, &ctx.machine, ctx.gpa, name);1044        return;1045    }1046}10471048// --- Pin / Unpin ---10491050pub fn pin(ctx: Ctx) !void {1051    const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1052    const commit = if (ctx.args.len > 1) ctx.args[1] else return error.Internal;1053    exec.editFlakeLock(ctx.gpa, input, commit) catch return error.ProcessFailed;1054    output.pinDone(input, commit);1055}10561057pub fn unpin(ctx: Ctx) !void {1058    const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1059    _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1060    output.unpinDone(input);1061}10621063// --- Hash / Fetch ---10641065pub fn hash(ctx: Ctx) !void {1066    const path = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1067    const h = try exec.nixHash(ctx.gpa, ctx.io, &ctx.machine, path);1068    defer ctx.gpa.free(h);1069    output.hashResult(std.mem.trim(u8, h, " \t\n\r"));1070}10711072pub fn fetch(ctx: Ctx) !void {1073    const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1074    const h = try exec.nixFetch(ctx.gpa, ctx.io, &ctx.machine, url);1075    defer ctx.gpa.free(h);1076    output.fetchResult(std.mem.trim(u8, h, " \t\n\r"), url);1077}10781079// --- Build / Run ---10801081pub fn build(ctx: Ctx) !void {1082    const attr: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1083    output.buildStart(attr orelse "default");1084    const code = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, attr);1085    if (code != 0) return error.BuildFailed;1086    output.buildDone();1087}10881089pub fn runCmd(ctx: Ctx) !void {1090    const pkg_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1091    output.runStart(pkg_arg);1092    _ = try exec.nixRun(ctx.io, &ctx.machine, ctx.gpa, pkg_arg);1093}10941095// --- Hello ---10961097pub fn hello(ctx: Ctx) !void {1098    output.hello(ctx.cfg.machines);1099}11001101// Runs when ~/.nina.conf is absent on first invocation (interactive TTY only).1102// Prompts for machine name, config path, and local flag, then writes the file.1103pub fn firstRunWizard(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1104    const home = environ.get("HOME") orelse {1105        errors.error_info.setSuggestion("set HOME environment variable", .{});1106        return error.ConfigNotFound;1107    };11081109    output.firstRunBanner();1110    output.firstRunNoConfig();11111112    var name_buf: [256]u8 = undefined;1113    var path_buf: [256]u8 = undefined;1114    var local_buf: [256]u8 = undefined;11151116    const machine_name = output.firstRunPrompt("machine name", "my-machine", &name_buf);1117    const config_path = output.firstRunPrompt("config path", "/etc/nixos", &path_buf);1118    const local_str = output.firstRunPrompt("local", "true", &local_buf);11191120    const conf_path = try std.fmt.allocPrint(gpa, "{s}/.nina.conf", .{home});1121    defer gpa.free(conf_path);11221123    var content_buf: [1024]u8 = undefined;1124    const content = try std.fmt.bufPrint(&content_buf,1125        \\[machine]1126        \\name = {s}1127        \\config = {s}1128        \\local = {s}1129        \\1130    , .{ machine_name, config_path, local_str });11311132    const file = std.Io.Dir.createFile(.cwd(), io, conf_path, .{}) catch {1133        errors.error_info.setMessage("could not write {s}", .{conf_path});1134        return error.Internal;1135    };1136    defer file.close(io);1137    file.writePositionalAll(io, content, 0) catch {1138        errors.error_info.setMessage("could not write {s}", .{conf_path});1139        return error.Internal;1140    };11411142    output.firstRunWritten(conf_path);1143}11441145pub fn setup(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1146    // Create ~/.nina.conf first if it doesn't exist. This makes `nina setup`1147    // a complete onboarding command — not just a nix-features check.1148    if (environ.get("HOME")) |home| {1149        var path_buf: [512]u8 = undefined;1150        if (std.fmt.bufPrint(&path_buf, "{s}/.nina.conf", .{home})) |conf_path| {1151            if (std.Io.Dir.openFile(.cwd(), io, conf_path, .{})) |f| {1152                f.close(io);1153            } else |_| {1154                try firstRunWizard(gpa, io, environ);1155                errors.error_info.reset();1156            }1157        } else |_| {}1158    }11591160    output.setupCheck();1161    const status = exec.checkNixFeatures(gpa, io, environ);1162    output.setupFeatures(status.nix_command, status.flakes);11631164    if (status.allEnabled()) {1165        output.setupAllSet();1166        api.ensureRegistryPinned(gpa, io, environ);1167        return;1168    }11691170    // On NixOS the features belong in configuration.nix (the declarative,1171    // permanent home), not ~/.config/nix/nix.conf. Offer to add the one line;1172    // the user runs the rebuild. We don't pin the registry here because the1173    // features aren't live until that rebuild lands.1174    if (exec.isNixOS(io)) {1175        const conf_path = "/etc/nixos/configuration.nix";1176        if (exec.nixosConfigEnablesFeatures(gpa, io, conf_path)) {1177            output.setupNixosNeedsRebuild(conf_path);1178            return;1179        }1180        output.setupNixosOffer(exec.NIXOS_FEATURES_LINE, conf_path);1181        if (output.confirmDefaultNo("add it now?")) {1182            if (exec.appendFeaturesToNixosConfig(gpa, io, environ, conf_path)) |_| {1183                output.setupNixosWrote(conf_path);1184            } else |_| {1185                output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);1186            }1187        } else {1188            output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);1189        }1190        return;1191    }11921193    // Non-NixOS: a user-level nix.conf takes effect immediately, no sudo needed.1194    output.setupEnabling();1195    const path = try exec.enableNixFeatures(gpa, io, environ);1196    defer gpa.free(path);11971198    output.setupDone(path);1199    api.ensureRegistryPinned(gpa, io, environ);1200}12011202// --- Log helper ---12031204fn logAction(ctx: Ctx, action: []const u8, gen: u32) void {1205    var ts_buf: [32]u8 = undefined;1206    const ts = nowIso(ctx.io, &ts_buf);1207    var buf: [256]u8 = undefined;1208    const entry = std.fmt.bufPrint(&buf, "{{\"ts\":\"{s}\",\"machine\":\"{s}\",\"command\":\"{s}\",\"outcome\":\"success\",\"gen_before\":null,\"gen_after\":{d},\"duration_ms\":0}}\n", .{1209        ts, ctx.machine.name, action, gen,1210    }) catch return;1211    exec.appendNinaLog(ctx.io, ctx.environ, entry);1212}12131214// Wall-clock UTC as ISO-8601. Uses Io.Clock.real (the settable Unix-epoch clock);1215// Io.Clock.awake is monotonic and unsuitable for timestamps. Falls back to epoch 0.1216fn nowIso(io: std.Io, buf: []u8) []const u8 {1217    const fallback = "1970-01-01T00:00:00Z";1218    const ns = std.Io.Clock.real.now(io).toNanoseconds();1219    if (ns <= 0) return fallback;1220    const secs: u64 = @intCast(@divFloor(ns, 1_000_000_000));1221    const es = std.time.epoch.EpochSeconds{ .secs = secs };1222    const ed = es.getEpochDay();1223    const yd = ed.calculateYearDay();1224    const md = yd.calculateMonthDay();1225    const ds = es.getDaySeconds();1226    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", .{1227        yd.year, md.month.numeric(), @as(u32, md.day_index) + 1,1228        ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(),1229    }) catch return fallback;1230}