commands.zig

67.3 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}3940fn runPreHook(ctx: Ctx, hook_name: []const u8) !bool {41    const hook = try exec.runHook(ctx.gpa, ctx.io, ctx.environ, hook_name);42    defer ctx.gpa.free(hook.output);43    switch (hook.result) {44        .not_found, .ok => return true,45        .failed => {46            output.hookFailed(hook_name, hook.exit_code, hook.output);47            return output.confirmDefaultNo("continue anyway?");48        },49    }50}5152fn runPostHook(ctx: Ctx, hook_name: []const u8) void {53    const hook = exec.runHook(ctx.gpa, ctx.io, ctx.environ, hook_name) catch return;54    defer ctx.gpa.free(hook.output);55    if (hook.result == .failed) {56        output.hookWarning(hook_name, hook.exit_code, hook.output);57    }58}5960pub fn apply(ctx: Ctx) !void {61    if (ctx.dry) {62        output.applyDry(ctx.machine.name);63        const code = try exec.nixosRebuildDryActivate(ctx.io, &ctx.machine, ctx.gpa);64        if (code != 0) return error.BuildFailed;65        output.applyDryDone();66        return;67    }68    if (ctx.check) {69        return check(ctx);70    }7172    if (!try runPreHook(ctx, "pre-apply")) {73        output.aborted();74        return error.HookAborted;75    }7677    output.applyStart(ctx.machine.name);78    const start = std.Io.Clock.awake.now(ctx.io);7980    const code = exec.nixosRebuildSwitch(ctx.io, &ctx.machine, ctx.gpa) catch |e| {81        exec.markApplyFailed(ctx.io, ctx.environ);82        return e;83    };8485    if (code != 0) {86        exec.markApplyFailed(ctx.io, ctx.environ);87        return error.BuildFailed;88    }8990    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());91    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));92    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;93    const after_failure = exec.takeApplyFailed(ctx.io, ctx.environ);94    output.applyDone(gen, elapsed, after_failure);95    // Show any nix warnings collected during the build (dim yellow, after success line).96    const warnings = errors.extractWarnings(ctx.gpa, errors.getBuildStderr()) catch &.{};97    defer {98        for (warnings) |w| ctx.gpa.free(w);99        ctx.gpa.free(warnings);100    }101    if (warnings.len > 0) output.buildWarnings(warnings);102    runPostHook(ctx, "post-apply");103    logAction(ctx, "apply", gen);104}105106pub fn check(ctx: Ctx) !void {107    output.checkStart(ctx.machine.name);108    const code = try exec.nixosRebuildBuild(ctx.io, &ctx.machine, ctx.gpa);109    if (code != 0) return error.BuildFailed;110    output.checkOk();111}112113pub fn back(ctx: Ctx) !void {114    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);115    defer ctx.gpa.free(gens);116117    var current: u32 = 0;118    for (gens) |g| if (g.current) {119        current = g.number;120    };121122    // Newest generation older than current. If there is none, we're already at the123    // oldest — stop cleanly instead of letting rollback fail with 'build failed'.124    var prev: u32 = 0;125    var has_prev = false;126    for (gens) |g| {127        if (g.number < current and (!has_prev or g.number > prev)) {128            prev = g.number;129            has_prev = true;130        }131    }132    if (!has_prev) {133        output.alreadyOldest();134        return;135    }136137    if (!try runPreHook(ctx, "pre-back")) {138        output.aborted();139        return error.HookAborted;140    }141142    output.backStart(ctx.machine.name, current, prev);143    if (ctx.cfg.confirm and !output.confirm("")) return;144145    // Flake systems don't have <nixos-config> in the Nix search path, so146    // `nixos-rebuild --rollback` fails. Switch by generation number instead147    // (same path as `nina go N`), which works for both channel and flake.148    const code = if (flakeSystem(ctx))149        try exec.switchGeneration(ctx.io, &ctx.machine, ctx.gpa, prev)150    else151        try exec.rollback(ctx.io, &ctx.machine, ctx.gpa);152    if (code != 0) return error.BuildFailed;153    output.backDone(prev);154    runPostHook(ctx, "post-back");155}156157pub fn go(ctx: Ctx) !void {158    if (ctx.args.len == 0) return error.Internal;159    const target = std.fmt.parseInt(u32, ctx.args[0], 10) catch return error.Internal;160    const current = try exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine);161162    output.goStart(ctx.machine.name, current, target);163    if (ctx.cfg.confirm and !output.confirm("")) return;164165    const code = try exec.switchGeneration(ctx.io, &ctx.machine, ctx.gpa, target);166    if (code != 0) return error.ProcessFailed;167    output.generationDone(target);168}169170pub fn history(ctx: Ctx) !void {171    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);172    defer ctx.gpa.free(gens);173    output.historyHeader(ctx.machine.name);174    for (gens) |g| output.historyRow(g);175}176177const gen_help = [_][2][]const u8{178    .{ "list", "list generations" },179    .{ "current", "show current generation" },180    .{ "delete <n>", "delete generation n" },181    .{ "delete old", "delete old generations" },182};183184pub fn genCmd(ctx: Ctx) !void {185    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("gen", &gen_help, null);186    if (std.mem.eql(u8, ctx.sub, "list")) return history(ctx);187    if (std.mem.eql(u8, ctx.sub, "current")) {188        const n = try exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine);189        output.genCurrent(n);190        return;191    }192    if (std.mem.eql(u8, ctx.sub, "delete")) {193        if (ctx.args.len == 0) return error.Internal;194        if (std.mem.eql(u8, ctx.args[0], "old")) {195            if (ctx.cfg.confirm and !output.confirm("")) return;196            _ = try exec.deleteOldGenerations(ctx.io, &ctx.machine, ctx.gpa);197        } else {198            const n = std.fmt.parseInt(u32, ctx.args[0], 10) catch return error.Internal;199            if (ctx.cfg.confirm and !output.confirm("")) return;200            _ = try exec.deleteGeneration(ctx.io, &ctx.machine, ctx.gpa, n);201        }202        output.done();203        return;204    }205    return error.Internal;206}207208pub fn clean(ctx: Ctx) !void {209    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);210    defer ctx.gpa.free(gens);211    const all = ctx.all or std.mem.eql(u8, ctx.sub, "all");212    const total: u32 = @intCast(gens.len);213    // `clean all` keeps only the current generation; otherwise keep the configured214    // count. With nothing older than the keep limit, there's nothing to collect.215    const keep: u32 = if (all) 1 else ctx.cfg.generations;216    if (total <= keep) {217        output.cleanNothing(ctx.machine.name, total);218        return;219    }220    output.cleanStart(ctx.machine.name, keep, total);221    if (ctx.cfg.confirm and !output.confirm("removing — cannot be undone")) return;222    _ = try exec.collectGarbage(ctx.io, &ctx.machine, ctx.gpa, all, ctx.cfg.generations);223    output.cleanDone();224}225226pub fn statusCmd(ctx: Ctx) !void {227    output.statusHeader();228    // --all renders every configured machine; remotes route through the same SSH229    // path as exec.capture. An unreachable machine is shown in red, not fatal.230    if (ctx.all and ctx.cfg.machines.len > 0) {231        for (ctx.cfg.machines) |m| statusRowFor(ctx, &m);232    } else {233        statusRowFor(ctx, &ctx.machine);234    }235    homeStatusLine(ctx);236}237238// When standalone Home Manager is present, show its current generation as a dim239// line indented under the machine rows. Gated on standalone mode (the only mode240// where we can read a generation), so a machine without HM is unaffected.241fn homeStatusLine(ctx: Ctx) void {242    if (exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ) != .standalone) return;243    const out = exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine) catch return;244    defer ctx.gpa.free(out);245    const gens = parseHomeGenerations(ctx.gpa, out) catch return;246    defer freeHomeGens(ctx.gpa, gens);247    if (gens.len == 0) return;248    output.statusHomeRow(gens[0].number, gens[0].date);249}250251fn statusRowFor(ctx: Ctx, machine: *const types.Machine) void {252    // A failure to read the current generation means we couldn't reach or query253    // the machine — mark it unreachable rather than reporting a bogus gen 0.254    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, machine) catch {255        output.statusRow(machine.name, 0, "", "", false);256        return;257    };258    const st = exec.systemStatus(ctx.gpa, ctx.io, machine);259    defer ctx.gpa.free(st.size);260    defer ctx.gpa.free(st.age);261    output.statusRow(machine.name, gen, st.age, st.size, true);262}263264pub fn diff(ctx: Ctx) !void {265    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);266    defer ctx.gpa.free(gens);267    var current: u32 = 0;268    var prev: u32 = 0;269    for (gens) |g| {270        if (g.current) current = g.number;271        if (!g.current and g.number > prev and g.number < current) prev = g.number;272    }273    if (ctx.args.len >= 2) {274        const a = std.fmt.parseInt(u32, ctx.args[0], 10) catch current - 1;275        const b = std.fmt.parseInt(u32, ctx.args[1], 10) catch current;276        output.diffHeader(a, b, ctx.machine.name);277        if (try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, a, b) != 0) return error.ProcessFailed;278    } else {279        output.diffHeader(if (prev > 0) prev else current - 1, current, ctx.machine.name);280        if (try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, if (prev > 0) prev else current - 1, current) != 0) return error.ProcessFailed;281    }282}283284pub fn mood(ctx: Ctx) !void {285    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;286    const st = exec.systemStatus(ctx.gpa, ctx.io, &ctx.machine);287    defer ctx.gpa.free(st.size);288    defer ctx.gpa.free(st.age);289    const state = exec.systemRunningState(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");290    defer ctx.gpa.free(state);291    output.mood(ctx.machine.name, state, gen, st.age, st.size);292}293294pub fn doctor(ctx: Ctx) !void {295    output.doctorHeader(ctx.machine.name);296    const checks = try exec.runDoctorChecks(ctx.gpa, ctx.io, &ctx.machine);297    defer ctx.gpa.free(checks);298    var warnings: u32 = 0;299    var failures: u32 = 0;300    for (checks) |ch| {301        output.doctorRow(ch);302        if (ch.status == .warn) warnings += 1;303        if (ch.status == .fail) failures += 1;304    }305306    // Home Manager row only when present — absent on a machine without HM, so307    // doctor's table is unchanged there.308    const hm_mode = exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ);309    if (hm_mode != .none) {310        const note = homeDoctorNote(ctx, hm_mode);311        defer ctx.gpa.free(note);312        output.doctorRow(.{ .name = "home manager", .status = .ok, .note = note });313    }314315    output.doctorSummary(warnings, failures);316}317318// "standalone  gen 765" / "module" — the note shown in doctor's home manager row.319// Caller owns the returned slice.320fn homeDoctorNote(ctx: Ctx, mode: exec.HomeManagerMode) []const u8 {321    const label = switch (mode) {322        .standalone => "standalone",323        .module => "module",324        .none => "",325    };326    if (mode == .standalone) {327        const gen = homeCurrentGen(ctx);328        if (gen != 0)329            return std.fmt.allocPrint(ctx.gpa, "{s}  gen {d}", .{ label, gen }) catch330                (ctx.gpa.dupe(u8, label) catch "");331    }332    return ctx.gpa.dupe(u8, label) catch "";333}334335// nina update — kepr self-update for the nina binary itself.336pub fn update(ctx: Ctx) !void {337    output.updateSelfStart();338339    if (comptime std.mem.eql(u8, version.PLATFORM, "unsupported")) {340        output.updateSelfNoPlatform(@tagName(builtin.cpu.arch) ++ "-" ++ @tagName(builtin.os.tag));341        return error.Internal;342    }343344    const env_url = ctx.environ.get("NINA_UPDATE_SOURCE");345    const source_url = env_url orelse UPDATE_URL;346347    const body = exec.fetchUrl(ctx.gpa, ctx.io, source_url) catch |e| switch (e) {348        error.NetworkError, error.HttpError => {349            output.updateSelfNetworkError();350            return;351        },352        else => return e,353    };354    defer ctx.gpa.free(body);355356    const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, body, .{}) catch {357        output.printWarning("could not parse release metadata");358        return;359    };360    defer parsed.deinit();361362    const root = parsed.value;363    if (root != .object) {364        output.printWarning("malformed release metadata");365        return;366    }367368    const remote_ver = blk: {369        const v = root.object.get("version") orelse {370            output.printWarning("malformed release metadata");371            return;372        };373        break :blk switch (v) {374            .string => |s| s,375            else => {376                output.printWarning("malformed release metadata");377                return;378            },379        };380    };381    const release_notes = blk: {382        const v = root.object.get("release_notes") orelse break :blk "";383        break :blk switch (v) {384            .string => |s| s,385            else => "",386        };387    };388389    if (std.mem.eql(u8, remote_ver, version.VERSION)) {390        output.updateSelfCurrent(version.VERSION);391        return;392    }393394    output.updateSelfAvailable(version.VERSION, remote_ver);395    output.updateSelfReleaseNotes(release_notes);396    if (ctx.check) return;397398    var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;399    const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {400        errors.error_info.setMessage("could not determine install path", .{});401        return error.Internal;402    };403404    // When running from the nix store, defer to nix profile upgrade so nix405    // manages the transition (the store is read-only; binary replacement fails).406    // A NixOS system install also resolves into the store but isn't a profile407    // element, so check the profile to avoid a no-op `upgrade` — it updates with408    // the next nixos-rebuild instead.409    if (std.mem.startsWith(u8, install_path, "/nix/store/")) {410        const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);411        defer {412            if (nina_element) |n| ctx.gpa.free(n);413        }414        if (nina_element == null) {415            output.updateSelfNotInProfile();416            return;417        }418        const element = nina_element.?;419        output.updateSelfNixManaged(remote_ver);420        if (ctx.cfg.confirm and !output.confirm("")) return;421        const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "upgrade", element }) catch {422            output.updateSelfNixFailed();423            return;424        };425        if (ec != 0) {426            output.updateSelfNixFailed();427            return;428        }429        output.updateSelfDone(version.VERSION, remote_ver);430        return;431    }432433    const plat_info = blk: {434        const pv = root.object.get("platforms") orelse break :blk null;435        if (pv != .object) break :blk null;436        break :blk pv.object.get(version.PLATFORM);437    };438    if (plat_info == null) {439        output.updateSelfNoPlatform(version.PLATFORM);440        return;441    }442443    const dl_url = blk: {444        const v = plat_info.?.object.get("url") orelse {445            output.printWarning("malformed release metadata");446            return;447        };448        break :blk switch (v) {449            .string => |s| s,450            else => {451                output.printWarning("malformed release metadata");452                return;453            },454        };455    };456457    const raw_cksum = blk: {458        if (plat_info.?.object.get("blake3")) |v|459            break :blk switch (v) {460                .string => |s| s,461                else => {462                    output.printWarning("malformed release metadata");463                    return;464                },465            };466        if (plat_info.?.object.get("checksum")) |v|467            break :blk switch (v) {468                .string => |s| s,469                else => {470                    output.printWarning("malformed release metadata");471                    return;472                },473            };474        output.printWarning("missing checksum in release metadata");475        return;476    };477    const expected_hex = if (std.mem.startsWith(u8, raw_cksum, "blake3:")) raw_cksum["blake3:".len..] else raw_cksum;478479    if (ctx.cfg.confirm and !output.confirm("")) return;480481    output.updateSelfDownloading(remote_ver, version.PLATFORM);482    const tmp_path = exec.downloadToTemp(ctx.gpa, ctx.io, dl_url) catch {483        output.printWarning("download failed — check your connection and try again");484        return;485    };486    defer ctx.gpa.free(tmp_path);487488    output.updateSelfVerifying();489    exec.verifyAndInstall(ctx.gpa, ctx.io, tmp_path, expected_hex, install_path) catch |e| switch (e) {490        error.ChecksumMismatch => {491            output.updateSelfChecksumFailed();492            return;493        },494        else => return e,495    };496497    output.updateSelfDone(version.VERSION, remote_ver);498}499500// nina goodbye — clean uninstall. Three install paths:501// - nix profile (binary in nix store with a profile element) → nix profile remove502// - koh build or source build (plain binary on PATH) → delete the file503pub fn goodbye(ctx: Ctx) !void {504    output.goodbyeStart();505506    var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;507    const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {508        errors.error_info.setMessage("could not determine install path", .{});509        return error.Internal;510    };511512    // A binary outside the nix store is a koh build or source build — delete it.513    if (!std.mem.startsWith(u8, install_path, "/nix/store/")) {514        output.goodbyeFile(install_path);515        if (ctx.cfg.confirm and !output.confirm("")) return;516        std.Io.Dir.deleteFileAbsolute(ctx.io, install_path) catch |e| {517            errors.error_info.setMessage("could not remove {s}", .{install_path});518            return e;519        };520        output.goodbyeDone();521        return;522    }523524    // Binary is in the nix store — find and remove the profile element.525    const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);526    defer {527        if (nina_element) |n| ctx.gpa.free(n);528    }529530    if (nina_element == null) {531        errors.error_info.setMessage("nina not found in nix profile — was it installed via 'nix profile add'?", .{});532        return error.Internal;533    }534535    output.goodbyeNix();536    if (ctx.cfg.confirm and !output.confirm("")) return;537    const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "remove", nina_element.? }) catch {538        output.goodbyeFailed("nix profile remove failed");539        return;540    };541    if (ec != 0) {542        output.goodbyeFailed("nix profile remove failed");543        return;544    }545    output.goodbyeDone();546}547548fn channelUpdateCmd(ctx: Ctx) !void {549    output.updateStart(ctx.machine.name);550    _ = try exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa);551    output.updateDone();552}553554pub fn upgrade(ctx: Ctx) !void {555    if (!try runPreHook(ctx, "pre-upgrade")) {556        output.aborted();557        return error.HookAborted;558    }559560    output.upgradeStart(ctx.machine.name);561    // Flake systems update inputs (flake.lock); channel systems update channels.562    // Running nix-channel --update on a flake system is a no-op at best. The563    // rebuild below is already flake-aware via exec.nixosRebuildSwitch.564    if (flakeSystem(ctx)) {565        output.printSubstep("updating flake inputs", .{});566        _ = exec.flakeUpdateAt(ctx.io, &ctx.machine, ctx.gpa, ctx.machine.config_path) catch {};567    } else {568        output.printSubstep("updating channels", .{});569        _ = exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa) catch {};570    }571    output.printSubstep("rebuilding", .{});572    const start = std.Io.Clock.awake.now(ctx.io);573    const code = try exec.nixosRebuildSwitch(ctx.io, &ctx.machine, ctx.gpa);574    if (code != 0) {575        output.applyFailed("");576        return error.BuildFailed;577    }578    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());579    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));580    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;581    output.applyDone(gen, elapsed, false);582    runPostHook(ctx, "post-upgrade");583}584585pub fn log(ctx: Ctx) !void {586    output.logHeader(ctx.machine.name);587    const content = exec.readNinaLog(ctx.gpa, ctx.io, ctx.environ, ctx.last) catch {588        // No log yet — that's fine589        return;590    };591    defer ctx.gpa.free(content);592    var lines = std.mem.splitScalar(u8, content, '\n');593    while (lines.next()) |line| {594        const t = std.mem.trim(u8, line, " \t\r");595        if (t.len == 0) continue;596        if (t[0] == '{') {597            renderJsonLogLine(ctx.gpa, t);598        } else {599            // legacy tab-separated format600            var parts = std.mem.tokenizeScalar(u8, t, '\t');601            const date = parts.next() orelse continue;602            const time = parts.next() orelse "";603            const action = parts.next() orelse "";604            const detail = parts.next() orelse "";605            output.logRow(date, time, action, detail);606        }607    }608}609610// The on-disk log is JSON Lines: {"ts","machine","command","outcome","gen_after",...}.611// Render ts -> date/time columns, command -> action, outcome(+gen) -> detail.612fn renderJsonLogLine(gpa: std.mem.Allocator, line: []const u8) void {613    const parsed = std.json.parseFromSlice(std.json.Value, gpa, line, .{}) catch {614        output.logRow(line, "", "", ""); // unparseable — show raw rather than drop615        return;616    };617    defer parsed.deinit();618    if (parsed.value != .object) return;619    const o = parsed.value.object;620621    const ts = jsonStr(o, "ts");622    const date = if (ts.len >= 10) ts[0..10] else ts;623    const time = if (ts.len >= 16) ts[11..16] else "";624    const action = jsonStr(o, "command");625    const outcome = jsonStr(o, "outcome");626627    var buf: [160]u8 = undefined;628    var detail: []const u8 = outcome;629    if (o.get("gen_after")) |g| {630        if (g == .integer) {631            detail = std.fmt.bufPrint(&buf, "{s}   -> gen {d}", .{ outcome, g.integer }) catch outcome;632        }633    }634    output.logRow(date, time, action, detail);635}636637fn jsonStr(o: std.json.ObjectMap, key: []const u8) []const u8 {638    if (o.get(key)) |v| {639        if (v == .string) return v.string;640    }641    return "";642}643644pub fn edit(ctx: Ctx) !void {645    const hardware = ctx.args.len > 0 and std.mem.eql(u8, ctx.args[0], "hardware");646    const filename = if (hardware) "hardware-configuration.nix" else "configuration.nix";647    const path = try std.fmt.allocPrint(ctx.gpa, "{s}/{s}", .{ ctx.machine.config_path, filename });648    defer ctx.gpa.free(path);649    output.editOpen(path, ctx.cfg.editor);650    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);651}652653pub fn fmt(ctx: Ctx) !void {654    const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});655    defer ctx.gpa.free(path);656    if (ctx.check) {657        const code = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, true);658        if (code != 0) output.fmtNeedsFormat() else output.fmtDone();659        return;660    }661    output.fmtStart(path);662    _ = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, false);663    output.fmtDone();664}665666pub fn repl(ctx: Ctx) !void {667    output.replStart();668    _ = try exec.nixRepl(ctx.io, &ctx.machine, ctx.gpa);669}670671pub fn develop(ctx: Ctx) !void {672    if (std.mem.eql(u8, ctx.sub, "show")) {673        _ = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, null);674        return;675    }676    const run_cmd: ?[]const u8 = if (ctx.args.len > 0 and std.mem.eql(u8, ctx.sub, "run"))677        ctx.args[0]678    else679        null;680    output.developStart(&.{});681    _ = try exec.nixDevelopPs1(ctx.io, &ctx.machine, ctx.gpa, run_cmd, ctx.environ);682    output.developDone();683}684685pub fn info(ctx: Ctx) !void {686    output.infoHeader(ctx.machine.name);687    const nixos_ver = exec.systemInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");688    defer ctx.gpa.free(nixos_ver);689    output.infoRow("nixos", std.mem.trim(u8, nixos_ver, " \t\n\r"));690691    const kernel = exec.kernelInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");692    defer ctx.gpa.free(kernel);693    output.infoRow("kernel", std.mem.trim(u8, kernel, " \t\n\r"));694695    const uptime = exec.uptimeInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");696    defer ctx.gpa.free(uptime);697    output.infoRow("uptime", std.mem.trim(u8, uptime, " \t\n\r"));698}699700pub fn boot(ctx: Ctx) !void {701    output.bootHeader(ctx.machine.name);702    const entries = exec.bootEntries(ctx.gpa, ctx.io, &ctx.machine) catch &.{};703    defer ctx.gpa.free(entries);704    for (entries, 0..) |entry, i| output.bootEntry(entry, i);705}706707pub fn searchCmd(ctx: Ctx) !void {708    const query = if (ctx.args.len > 0) ctx.args[0] else "";709    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);710    const selected = try search_tui.run(ctx.gpa, ctx.io, query, .packages);711    if (selected) |npkg| try selectAndInstall(ctx, npkg);712}713714pub fn optionCmd(ctx: Ctx) !void {715    const query = if (ctx.args.len > 0) ctx.args[0] else "";716    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);717    _ = try search_tui.run(ctx.gpa, ctx.io, query, .options);718}719720pub fn install(ctx: Ctx) !void {721    const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;722723    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);724725    // Search for the package to get the attr726    const pkgs = api.searchPackages(ctx.gpa, ctx.io, pkg_name) catch {727        errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});728        errors.error_info.setSuggestion("nina search {s}", .{pkg_name});729        return error.PackageNotFound;730    };731732    if (pkgs.len == 0) {733        // No matches — likely a typo. Suggest the closest real package and offer it.734        if (closestPackage(ctx, pkg_name)) |sugg| {735            output.didYouMean(pkg_name, sugg.pname);736            if (output.confirm("")) try selectAndInstall(ctx, sugg);737            return;738        }739        errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});740        errors.error_info.setSuggestion("nina search {s}", .{pkg_name});741        return error.PackageNotFound;742    }743744    // Prefer an exact name match over the first search result — `install ripgrep`745    // must pick "ripgrep", not the alphabetically-first match like "repgrep".746    var found = pkgs[0];747    for (pkgs) |p| {748        if (std.mem.eql(u8, p.pname, pkg_name)) {749            found = p;750            break;751        }752    }753    try selectAndInstall(ctx, found);754}755756// Find the real package whose name is closest to a not-found query (typo help).757// Typos usually keep the leading characters, so gather candidates with a prefix758// search and rank by edit distance; return the best only if it's typo-close.759fn closestPackage(ctx: Ctx, query: []const u8) ?types.NixPackage {760    if (query.len < 2) return null;761    var candidates = api.searchPackages(ctx.gpa, ctx.io, query[0..@min(query.len, 4)]) catch &.{};762    if (candidates.len == 0 and query.len > 2) {763        candidates = api.searchPackages(ctx.gpa, ctx.io, query[0..2]) catch &.{};764    }765    if (candidates.len == 0) return null;766767    var best: ?types.NixPackage = null;768    var best_dist: usize = std.math.maxInt(usize);769    for (candidates) |p| {770        const d = editDistance(query, p.pname);771        if (d > 0 and d < best_dist) {772            best_dist = d;773            best = p;774        }775    }776    // Only suggest a genuinely close name, scaled to query length.777    const threshold = @max(@as(usize, 2), query.len / 3);778    return if (best_dist <= threshold) best else null;779}780781// Case-insensitive Levenshtein distance. Names longer than the row buffer are782// treated as far away (never suggested).783fn editDistance(a: []const u8, b: []const u8) usize {784    const n = b.len;785    if (a.len == 0) return n;786    if (n == 0) return a.len;787    if (n + 1 > 128) return std.math.maxInt(usize);788    var prev: [128]usize = undefined;789    var curr: [128]usize = undefined;790    var j: usize = 0;791    while (j <= n) : (j += 1) prev[j] = j;792    var i: usize = 1;793    while (i <= a.len) : (i += 1) {794        curr[0] = i;795        j = 1;796        while (j <= n) : (j += 1) {797            const cost: usize = if (std.ascii.toLower(a[i - 1]) == std.ascii.toLower(b[j - 1])) 0 else 1;798            curr[j] = @min(prev[j] + 1, @min(curr[j - 1] + 1, prev[j - 1] + cost));799        }800        @memcpy(prev[0 .. n + 1], curr[0 .. n + 1]);801    }802    return prev[n];803}804805test "editDistance is case-insensitive Levenshtein" {806    try std.testing.expectEqual(@as(usize, 1), editDistance("firefux", "firefox"));807    try std.testing.expectEqual(@as(usize, 0), editDistance("git", "GIT"));808    try std.testing.expectEqual(@as(usize, 2), editDistance("fierfox", "firefox"));809    try std.testing.expectEqual(@as(usize, 7), editDistance("", "firefox"));810}811812// Prompt for the install method (profile / system / try) and dispatch. Shared by813// `nina install <pkg>` and the search widget's Enter-to-select — the letter keys814// are read here, after the search widget's raw mode is gone, so they don't815// collide with typing a query.816fn selectAndInstall(ctx: Ctx, npkg: types.NixPackage) !void {817    output.installSelectPrompt(npkg.pname, npkg.version);818819    var choice_buf: [8]u8 = undefined;820    var choice_len: usize = 0;821    while (choice_len < choice_buf.len) {822        const n = std.posix.read(std.posix.STDIN_FILENO, choice_buf[choice_len .. choice_len + 1]) catch break;823        if (n == 0) break;824        if (choice_buf[choice_len] == '\n') break;825        choice_len += 1;826    }827    const choice = std.mem.trim(u8, choice_buf[0..choice_len], " \t");828829    if (choice.len == 0 or choice[0] == 'i' or choice[0] == 'I') {830        try profileInstallPkg(ctx, npkg);831    } else if (choice[0] == 's' or choice[0] == 'S') {832        try systemInstallPkg(ctx, npkg);833    } else if (choice[0] == 't' or choice[0] == 'T') {834        try tryPkg(ctx, npkg);835    }836}837838fn profileInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {839    output.installStart(npkg.pname, .profile);840    output.printSubstep("nix profile add nixpkgs#{s}", .{npkg.attr});841    output.printTeach(try std.fmt.allocPrint(ctx.gpa, "nix profile add nixpkgs#{s}", .{npkg.attr}));842    const code = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, npkg.attr);843    if (code != 0) return error.ProcessFailed;844    output.installDone(npkg.pname);845}846847fn systemInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {848    const config_path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});849    defer ctx.gpa.free(config_path);850    const line = api.findSystemPackagesLine(ctx.io, config_path) orelse 1;851    output.installEditorPrompt(npkg.pname, config_path, line, ctx.cfg.editor);852    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, config_path, line);853    if (ctx.cfg.confirm) {854        if (output.confirm("apply now? ")) {855            try apply(ctx);856        }857    }858}859860fn tryPkg(ctx: Ctx, npkg: types.NixPackage) !void {861    output.tryStart(npkg.pname);862    output.printSubstep("nix shell nixpkgs#{s}", .{npkg.attr});863    output.tryExitHint();864    _ = try exec.nixShellPs1(ctx.io, &ctx.machine, ctx.gpa, npkg.attr, ctx.environ);865    output.tryDone();866}867868pub fn remove(ctx: Ctx) !void {869    const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;870    output.removeStart(pkg_name);871    const code = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, pkg_name);872    if (code != 0) return error.ProcessFailed;873    output.done();874}875876pub fn list(ctx: Ctx) !void {877    output.listHeader(ctx.machine.name);878879    // Profile packages: parse `nix profile list --json` into clean name+version880    // rows instead of dumping nix's verbose multi-line "Name:/Flake attribute:"881    // blocks.882    if (exec.profileListJson(ctx.gpa, ctx.io, &ctx.machine) catch null) |json| {883        defer ctx.gpa.free(json);884        output.listSection("profile");885        renderProfileJson(ctx.gpa, json);886    }887888    // System packages: the references of /run/current-system/sw, each a889    // <hash>-<name>-<version> store path.890    if (exec.systemPackagePaths(ctx.gpa, ctx.io, &ctx.machine) catch null) |paths| {891        defer ctx.gpa.free(paths);892        output.blankLine();893        output.listSection("system");894        var lines = std.mem.splitScalar(u8, paths, '\n');895        while (lines.next()) |line| {896            const t = std.mem.trim(u8, line, " \t\r");897            if (t.len == 0) continue;898            const row = pkgFromStorePath(t);899            // Skip support paths with no parseable version (man pages, wrappers).900            if (row.version.len == 0) continue;901            output.listPkg(row.name, row.version);902        }903    }904}905906const PkgRow = struct { name: []const u8, version: []const u8 };907908// Split a nix store path basename (<hash>-<name>-<version>) into name + version.909// Version begins at the first '-' followed by a digit, which reliably lands on910// the name/version boundary since the 32-char hash and package names start with911// non-digits.912fn pkgFromStorePath(path: []const u8) PkgRow {913    const base = std.fs.path.basename(path);914    const after_hash = if (base.len > 33 and base[32] == '-') base[33..] else base;915    var i: usize = 0;916    while (i + 1 < after_hash.len) : (i += 1) {917        if (after_hash[i] == '-' and std.ascii.isDigit(after_hash[i + 1])) {918            return .{ .name = after_hash[0..i], .version = stripOutputSuffix(after_hash[i + 1 ..]) };919        }920    }921    return .{ .name = after_hash, .version = "" };922}923924// Multi-output derivations append the output name to the store path (e.g.925// curl-8.20.0-bin, less-692-man). Strip that suffix so the version column reads926// as just the version.927fn stripOutputSuffix(ver: []const u8) []const u8 {928    const suffixes = [_][]const u8{ "-bin", "-man", "-dev", "-doc", "-lib", "-info", "-out", "-static", "-devdoc" };929    for (suffixes) |s| {930        if (std.mem.endsWith(u8, ver, s)) return ver[0 .. ver.len - s.len];931    }932    return ver;933}934935test "pkgFromStorePath splits name and version at first dash-digit" {936    const a = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-ripgrep-15.1.0");937    try std.testing.expectEqualStrings("ripgrep", a.name);938    try std.testing.expectEqualStrings("15.1.0", a.version);939940    const b = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-helix-25.01");941    try std.testing.expectEqualStrings("helix", b.name);942    try std.testing.expectEqualStrings("25.01", b.version);943944    // multi-output store paths drop their output-name suffix945    const c = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-curl-8.20.0-bin");946    try std.testing.expectEqualStrings("curl", c.name);947    try std.testing.expectEqualStrings("8.20.0", c.version);948}949950fn firstStorePath(el: std.json.Value) ?[]const u8 {951    if (el != .object) return null;952    const sp = el.object.get("storePaths") orelse return null;953    if (sp != .array or sp.array.items.len == 0) return null;954    const first = sp.array.items[0];955    return if (first == .string) first.string else null;956}957958// `nix profile list --json` has two shapes across nix versions: newer keys each959// element by name (object), older lists them positionally (array). Handle both.960fn renderProfileJson(gpa: std.mem.Allocator, json: []const u8) void {961    const parsed = std.json.parseFromSlice(std.json.Value, gpa, json, .{}) catch return;962    defer parsed.deinit();963    if (parsed.value != .object) return;964    const elements = parsed.value.object.get("elements") orelse return;965    switch (elements) {966        .object => |obj| {967            var it = obj.iterator();968            while (it.next()) |entry| {969                const ver = if (firstStorePath(entry.value_ptr.*)) |p| pkgFromStorePath(p).version else "";970                output.listPkg(entry.key_ptr.*, ver);971            }972        },973        .array => |arr| {974            for (arr.items) |el| {975                const path = firstStorePath(el) orelse continue;976                const row = pkgFromStorePath(path);977                output.listPkg(row.name, row.version);978            }979        },980        else => {},981    }982}983984pub fn tryCmd(ctx: Ctx) !void {985    const pkg_name_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;986    const shell_pkg = types.NixPackage{ .attr = pkg_name_arg, .pname = pkg_name_arg, .version = "", .description = "" };987    try tryPkg(ctx, shell_pkg);988}989990// --- Home Manager commands ---991992const home_help = [_][2][]const u8{993    .{ "apply", "apply home-manager configuration" },994    .{ "apply --dry", "preview changes without activating" },995    .{ "back", "roll back one generation" },996    .{ "history", "list all generations" },997    .{ "edit", "open home.nix" },998    .{ "check", "validate without applying" },999    .{ "diff", "compare the latest two generations" },1000    .{ "packages", "list managed packages" },1001};10021003const HomeGen = struct {1004    number: u32,1005    date: []const u8,1006    time: []const u8,1007    path: []const u8,1008};10091010// `home-manager generations` lines read:1011//   2026-06-01 11:56 : id 765 -> /nix/store/<hash>-home-manager-generation1012// Newest first, so index 0 is the current generation.1013fn parseHomeGenerations(gpa: std.mem.Allocator, out_str: []const u8) ![]HomeGen {1014    var gens: std.ArrayList(HomeGen) = .empty;1015    var lines = std.mem.splitScalar(u8, out_str, '\n');1016    while (lines.next()) |line| {1017        const t = std.mem.trim(u8, line, " \t\r");1018        if (t.len == 0) continue;1019        var it = std.mem.tokenizeAny(u8, t, " \t");1020        const date = it.next() orelse continue;1021        const time = it.next() orelse continue;1022        var number: ?u32 = null;1023        var path: []const u8 = "";1024        while (it.next()) |tok| {1025            if (std.mem.eql(u8, tok, "id")) {1026                if (it.next()) |n| number = std.fmt.parseInt(u32, n, 10) catch null;1027            } else if (std.mem.startsWith(u8, tok, "/nix/store/")) {1028                path = tok;1029            }1030        }1031        const num = number orelse continue;1032        try gens.append(gpa, .{1033            .number = num,1034            .date = try gpa.dupe(u8, date),1035            .time = try gpa.dupe(u8, time),1036            .path = try gpa.dupe(u8, path),1037        });1038    }1039    return gens.toOwnedSlice(gpa);1040}10411042fn freeHomeGens(gpa: std.mem.Allocator, gens: []HomeGen) void {1043    for (gens) |g| {1044        gpa.free(g.date);1045        gpa.free(g.time);1046        gpa.free(g.path);1047    }1048    gpa.free(gens);1049}10501051test "parseHomeGenerations reads id, date and store path" {1052    const a = std.testing.allocator;1053    const sample =1054        \\2026-06-01 11:56 : id 765 -> /nix/store/aaaa-home-manager-generation1055        \\2026-05-31 10:29 : id 764 -> /nix/store/bbbb-home-manager-generation1056    ;1057    const gens = try parseHomeGenerations(a, sample);1058    defer freeHomeGens(a, gens);1059    try std.testing.expectEqual(@as(usize, 2), gens.len);1060    try std.testing.expectEqual(@as(u32, 765), gens[0].number);1061    try std.testing.expectEqualStrings("2026-06-01", gens[0].date);1062    try std.testing.expectEqualStrings("11:56", gens[0].time);1063    try std.testing.expectEqualStrings("/nix/store/aaaa-home-manager-generation", gens[0].path);1064    try std.testing.expectEqual(@as(u32, 764), gens[1].number);1065}10661067// Current (newest) home generation number, or 0 if unavailable.1068fn homeCurrentGen(ctx: Ctx) u32 {1069    const out = exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine) catch return 0;1070    defer ctx.gpa.free(out);1071    const gens = parseHomeGenerations(ctx.gpa, out) catch return 0;1072    defer freeHomeGens(ctx.gpa, gens);1073    return if (gens.len > 0) gens[0].number else 0;1074}10751076pub fn home(ctx: Ctx) !void {1077    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help"))1078        return output.subcommandHelp("home", &home_help, null);10791080    // Home Manager manages the local user's environment. Detection (which binary,1081    // ~/.config/home-manager, $HOME/$USER for the flake ref) all read the LOCAL1082    // host, while exec routes over SSH for a remote machine — so `home --on1083    // <remote>` would decide mode/flake-ref from the wrong box. Refuse it cleanly1084    // rather than acting on a mismatch.1085    if (!ctx.machine.local) {1086        output.homeLocalOnly(ctx.machine.name);1087        return;1088    }10891090    const mode = exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ);1091    if (mode == .none) {1092        output.homeNotInstalled();1093        return;1094    }10951096    // apply is the only command meaningful in module mode (it redirects to1097    // `nina apply`); everything else needs the standalone home-manager CLI.1098    if (std.mem.eql(u8, ctx.sub, "apply")) return homeApply(ctx, mode);1099    // edit just opens the local home.nix — fine in module mode too.1100    if (std.mem.eql(u8, ctx.sub, "edit")) return homeEdit(ctx);11011102    if (mode == .module) {1103        output.homeModuleManaged();1104        return;1105    }11061107    if (std.mem.eql(u8, ctx.sub, "back")) return homeBack(ctx);1108    if (std.mem.eql(u8, ctx.sub, "history")) return homeHistory(ctx);1109    if (std.mem.eql(u8, ctx.sub, "check")) return homeCheck(ctx);1110    if (std.mem.eql(u8, ctx.sub, "diff")) return homeDiff(ctx);1111    if (std.mem.eql(u8, ctx.sub, "packages")) return homePackages(ctx);11121113    return output.subcommandHelp("home", &home_help, null);1114}11151116fn homePackages(ctx: Ctx) !void {1117    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1118    defer ctx.gpa.free(out);1119    const gens = try parseHomeGenerations(ctx.gpa, out);1120    defer freeHomeGens(ctx.gpa, gens);11211122    output.homePackagesHeader(ctx.machine.name);1123    if (gens.len == 0 or gens[0].path.len == 0) return;11241125    // The generation's OWN references are home-manager's activation deps1126    // (bash, coreutils, ...), not what the user installed. The user's packages1127    // live one level down, in the `…-home-manager-path` env the generation1128    // references — descend into it and list ITS references. Fall back to the1129    // generation refs if that env isn't present (older home-manager layouts).1130    const gen_refs = exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, gens[0].path) catch return;1131    defer ctx.gpa.free(gen_refs);11321133    var refs = gen_refs;1134    var env_refs: ?[]u8 = null;1135    defer if (env_refs) |e| ctx.gpa.free(e);1136    if (findHomeManagerPath(gen_refs)) |pkg_path| {1137        if (exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, pkg_path)) |e| {1138            env_refs = e;1139            refs = e;1140        } else |_| {}1141    }11421143    // Dedup by name: multi-output derivations (jq, jq-lib, jq-doc) collapse to1144    // the same name after the output suffix is stripped. Keys are slices into1145    // `refs`, valid for this function's lifetime.1146    var seen = std.StringHashMap(void).init(ctx.gpa);1147    defer seen.deinit();1148    var lines = std.mem.splitScalar(u8, refs, '\n');1149    while (lines.next()) |line| {1150        const t = std.mem.trim(u8, line, " \t\r");1151        if (t.len == 0) continue;1152        const row = pkgFromStorePath(t);1153        if (row.version.len == 0) continue;1154        if (std.mem.indexOf(u8, row.name, "home-manager") != null) continue;1155        if (seen.contains(row.name)) continue;1156        seen.put(row.name, {}) catch {};1157        output.listPkg(row.name, row.version);1158    }1159}11601161// The `…-home-manager-path` env among a generation's references — the buildEnv1162// of the user's home.packages. Returns the full store-path line, or null.1163fn findHomeManagerPath(refs: []const u8) ?[]const u8 {1164    var lines = std.mem.splitScalar(u8, refs, '\n');1165    while (lines.next()) |line| {1166        const t = std.mem.trim(u8, line, " \t\r");1167        if (std.mem.indexOf(u8, t, "home-manager-path") != null) return t;1168    }1169    return null;1170}11711172test "findHomeManagerPath picks the env, not the generation or infra" {1173    const refs =1174        \\/nix/store/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-bash-5.31175        \\/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path1176        \\/nix/store/cccccccccccccccccccccccccccccccc-coreutils-9.111177    ;1178    try std.testing.expectEqualStrings(1179        "/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path",1180        findHomeManagerPath(refs).?,1181    );1182    try std.testing.expectEqual(@as(?[]const u8, null), findHomeManagerPath("/nix/store/x-bash-5.3\n"));1183}11841185fn homeDiff(ctx: Ctx) !void {1186    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1187    defer ctx.gpa.free(out);1188    const gens = try parseHomeGenerations(ctx.gpa, out);1189    defer freeHomeGens(ctx.gpa, gens);11901191    // Need two generations and both their store paths to diff their closures.1192    if (gens.len < 2 or gens[0].path.len == 0 or gens[1].path.len == 0) {1193        output.homeNothingToDiff();1194        return;1195    }1196    const newer = gens[0];1197    const older = gens[1];1198    output.homeDiffHeader(older.number, newer.number, ctx.machine.name);1199    if (try exec.diffClosuresPaths(ctx.io, &ctx.machine, ctx.gpa, older.path, newer.path) != 0)1200        return error.ProcessFailed;1201}12021203fn homeCheck(ctx: Ctx) !void {1204    output.homeCheckStart(ctx.machine.name);1205    const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa);1206    if (code != 0) return error.BuildFailed;1207    output.homeCheckOk();1208}12091210fn homeEdit(ctx: Ctx) !void {1211    // Standalone home config lives at ~/.config/home-manager/home.nix; the same1212    // path is what detection keys on for module mode, so it resolves for both.1213    const path = exec.homeNixPath(ctx.gpa, ctx.environ) orelse {1214        errors.error_info.setMessage("could not resolve ~/.config/home-manager/home.nix", .{});1215        return error.ConfigNotFound;1216    };1217    defer ctx.gpa.free(path);1218    output.homeEditOpen(path, ctx.cfg.editor);1219    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);1220}12211222fn homeHistory(ctx: Ctx) !void {1223    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1224    defer ctx.gpa.free(out);1225    const gens = try parseHomeGenerations(ctx.gpa, out);1226    defer freeHomeGens(ctx.gpa, gens);1227    output.homeHistoryHeader(ctx.machine.name);1228    // Newest-first from home-manager; the first row is the current generation.1229    for (gens, 0..) |g, i| output.homeHistoryRow(g.number, g.date, g.time, i == 0);1230}12311232fn homeBack(ctx: Ctx) !void {1233    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1234    defer ctx.gpa.free(out);1235    const gens = try parseHomeGenerations(ctx.gpa, out);1236    defer freeHomeGens(ctx.gpa, gens);12371238    // Newest-first: [0] is current, [1] is the generation to roll back to.1239    if (gens.len < 2) {1240        output.alreadyOldest();1241        return;1242    }1243    const current = gens[0].number;1244    const prev = gens[1].number;12451246    output.homeBackStart(ctx.machine.name, current, prev);1247    if (ctx.cfg.confirm and !output.confirm("")) return;1248    const code = try exec.homeManagerRollback(ctx.io, &ctx.machine, ctx.gpa);1249    if (code != 0) return error.BuildFailed;1250    output.homeBackDone(prev);1251}12521253fn homeApply(ctx: Ctx, mode: exec.HomeManagerMode) !void {1254    // NixOS/flake module: home config is rebuilt by nixos-rebuild — redirect.1255    if (mode == .module) {1256        output.homeModuleManaged();1257        return;1258    }1259    if (ctx.dry) {1260        output.homeApplyDry(ctx.machine.name);1261        const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa);1262        if (code != 0) return error.BuildFailed;1263        output.homeApplyDryDone();1264        return;1265    }12661267    if (!try runPreHook(ctx, "pre-home")) {1268        output.aborted();1269        return error.HookAborted;1270    }12711272    output.homeApplyStart(ctx.machine.name);1273    const flake_ref = exec.homeFlakeRef(ctx.gpa, ctx.io, ctx.environ);1274    defer if (flake_ref) |r| ctx.gpa.free(r);1275    if (flake_ref) |ref| {1276        output.printSubstep("home-manager switch --flake {s}", .{ref});1277    } else {1278        output.printSubstep("home-manager switch", .{});1279    }12801281    const start = std.Io.Clock.awake.now(ctx.io);1282    const code = if (flake_ref) |ref|1283        try exec.homeManagerSwitchFlake(ctx.io, &ctx.machine, ctx.gpa, ref)1284    else1285        try exec.homeManagerSwitch(ctx.io, &ctx.machine, ctx.gpa);1286    if (code != 0) return error.BuildFailed;12871288    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());1289    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));1290    output.homeApplyDone(homeCurrentGen(ctx), elapsed);1291    runPostHook(ctx, "post-home");1292}12931294// --- Service commands ---12951296const service_help = [_][2][]const u8{1297    .{ "list", "list running services" },1298    .{ "logs <svc>", "show service logs" },1299    .{ "status <svc>", "service status" },1300    .{ "start <svc>", "start a service" },1301    .{ "stop <svc>", "stop a service" },1302    .{ "restart <svc>", "restart a service" },1303    .{ "enable <svc>", "enable at boot" },1304    .{ "disable <svc>", "disable at boot" },1305};13061307pub fn service(ctx: Ctx) !void {1308    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");1309    if (std.mem.eql(u8, ctx.sub, "list")) {1310        output.serviceListHeader(ctx.machine.name);1311        const svcs = exec.serviceList(ctx.gpa, ctx.io, &ctx.machine, ctx.user) catch &.{};1312        defer ctx.gpa.free(svcs);1313        for (svcs) |s| output.serviceRow(s);1314        return;1315    }1316    if (std.mem.eql(u8, ctx.sub, "logs")) {1317        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1318        const follow = ctx.args.len > 1 and std.mem.eql(u8, ctx.args[1], "-f");1319        output.serviceLogsHeader(name, ctx.last, ctx.machine.name);1320        _ = try exec.serviceLogs(ctx.io, &ctx.machine, ctx.gpa, name, ctx.last, follow, ctx.user);1321        return;1322    }1323    if (std.mem.eql(u8, ctx.sub, "status")) {1324        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1325        output.serviceVerb("status", name, ctx.machine.name);1326        _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, "status", name, ctx.user);1327        return;1328    }1329    // start/stop/restart/enable/disable1330    const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1331    if (ctx.cfg.confirm and (std.mem.eql(u8, ctx.sub, "stop") or std.mem.eql(u8, ctx.sub, "disable"))) {1332        if (!output.confirm("")) return;1333    }1334    output.serviceVerb(ctx.sub, name, ctx.machine.name);1335    _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, ctx.sub, name, ctx.user);1336    output.serviceDone();1337}13381339// --- Flake commands ---13401341const flake_help = [_][2][]const u8{1342    .{ "init", "create a new flake.nix" },1343    .{ "update", "update flake inputs" },1344    .{ "update <in>", "update a specific input" },1345    .{ "check", "validate the flake" },1346    .{ "show", "inspect flake outputs" },1347    .{ "lock", "regenerate flake.lock" },1348    .{ "clone <url>", "clone a flake repository" },1349};13501351pub fn flake(ctx: Ctx) !void {1352    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("flake", &flake_help, null);1353    if (std.mem.eql(u8, ctx.sub, "update")) {1354        output.flakeUpdateStart();1355        const input: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1356        _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1357        output.flakeLockWritten();1358        return;1359    }1360    if (std.mem.eql(u8, ctx.sub, "check")) {1361        output.flakeCheckStart();1362        const code = try exec.flakeCheck(ctx.io, &ctx.machine, ctx.gpa);1363        if (code == 0) output.flakeValid() else output.checkFailed("");1364        return;1365    }1366    if (std.mem.eql(u8, ctx.sub, "show")) {1367        const json_out = exec.flakeShow(ctx.gpa, ctx.io, &ctx.machine) catch null;1368        if (json_out) |j| {1369            defer ctx.gpa.free(j);1370            output.flakeShowHeader("flake outputs");1371            // Parse and display the flake outputs1372            const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, j, .{}) catch return;1373            defer parsed.deinit();1374            if (parsed.value == .object) {1375                var it = parsed.value.object.iterator();1376                while (it.next()) |entry| {1377                    if (entry.value_ptr.* == .object) {1378                        var inner = entry.value_ptr.object.iterator();1379                        while (inner.next()) |e2| {1380                            const desc = if (e2.value_ptr.* == .object)1381                                if (e2.value_ptr.object.get("description")) |d|1382                                    if (d == .string) d.string else ""1383                                else1384                                    ""1385                            else1386                                "";1387                            output.flakeShowEntry(entry.key_ptr.*, e2.key_ptr.*, desc);1388                        }1389                    }1390                }1391            }1392        }1393        return;1394    }1395    if (std.mem.eql(u8, ctx.sub, "init")) {1396        _ = try exec.flakeInit(ctx.io, &ctx.machine, ctx.gpa);1397        return;1398    }1399    if (std.mem.eql(u8, ctx.sub, "lock")) {1400        _ = try exec.flakeLock(ctx.io, &ctx.machine, ctx.gpa);1401        return;1402    }1403    if (std.mem.eql(u8, ctx.sub, "clone")) {1404        const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1405        _ = try exec.flakeClone(ctx.io, &ctx.machine, ctx.gpa, url);1406        return;1407    }1408}14091410// --- Store commands ---14111412const store_help = [_][2][]const u8{1413    .{ "info", "store size and counts" },1414    .{ "path <attr>", "store path of a package" },1415    .{ "gc", "collect garbage" },1416    .{ "verify", "verify store integrity" },1417    .{ "repair", "repair corrupted paths" },1418};14191420pub fn store(ctx: Ctx) !void {1421    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("store", &store_help, null);1422    if (std.mem.eql(u8, ctx.sub, "gc")) {1423        _ = try exec.storeGc(ctx.io, &ctx.machine, ctx.gpa);1424        return;1425    }1426    if (std.mem.eql(u8, ctx.sub, "verify")) {1427        output.storeVerifyStart();1428        _ = try exec.storeVerify(ctx.io, &ctx.machine, ctx.gpa);1429        return;1430    }1431    if (std.mem.eql(u8, ctx.sub, "repair")) {1432        if (ctx.cfg.confirm and !output.confirm("")) return;1433        output.storeRepairStart();1434        _ = try exec.storeRepair(ctx.io, &ctx.machine, ctx.gpa);1435        return;1436    }1437    if (std.mem.eql(u8, ctx.sub, "info")) {1438        const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1439        output.storeInfo(si);1440        return;1441    }1442    if (std.mem.eql(u8, ctx.sub, "path")) {1443        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1444        const path = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, attr);1445        defer ctx.gpa.free(path);1446        output.storePath(path);1447        return;1448    }1449    // default: info1450    const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1451    output.storeInfo(si);1452}14531454// --- Channel commands ---14551456const channel_help = [_][2][]const u8{1457    .{ "list", "list channels" },1458    .{ "add <url> [name]", "add a channel" },1459    .{ "remove <name>", "remove a channel" },1460    .{ "update", "update all channels" },1461};14621463pub fn channel(ctx: Ctx) !void {1464    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("channel", &channel_help, null);1465    // On a flake-managed system, nix-channel operations generally don't apply.1466    if (flakeSystem(ctx)) output.flakeChannelNote();1467    if (std.mem.eql(u8, ctx.sub, "list")) {1468        output.channelListHeader(ctx.machine.name);1469        const chans = try exec.channelList(ctx.gpa, ctx.io, &ctx.machine);1470        defer ctx.gpa.free(chans);1471        for (chans) |ch| output.channelRow(ch);1472        return;1473    }1474    if (std.mem.eql(u8, ctx.sub, "add")) {1475        const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1476        const name = if (ctx.args.len > 1) ctx.args[1] else "";1477        _ = try exec.channelAdd(ctx.io, &ctx.machine, ctx.gpa, url, name);1478        output.channelDone();1479        return;1480    }1481    if (std.mem.eql(u8, ctx.sub, "remove")) {1482        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1483        _ = try exec.channelRemove(ctx.io, &ctx.machine, ctx.gpa, name);1484        output.channelDone();1485        return;1486    }1487    if (std.mem.eql(u8, ctx.sub, "update")) {1488        return channelUpdateCmd(ctx);1489    }1490}14911492// --- Profile commands ---14931494pub fn profile(ctx: Ctx) !void {1495    if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {1496        output.profileListHeader();1497        const out = exec.profileList(ctx.gpa, ctx.io, &ctx.machine) catch null;1498        if (out) |o| {1499            defer ctx.gpa.free(o);1500            var lines = std.mem.splitScalar(u8, o, '\n');1501            while (lines.next()) |line| {1502                const t = std.mem.trim(u8, line, " \t\r");1503                if (t.len == 0) continue;1504                output.profileRow(t, "", "");1505            }1506        }1507        return;1508    }1509    if (std.mem.eql(u8, ctx.sub, "install")) {1510        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1511        _ = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, attr);1512        output.done();1513        return;1514    }1515    if (std.mem.eql(u8, ctx.sub, "remove")) {1516        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1517        _ = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, attr);1518        output.done();1519        return;1520    }1521    if (std.mem.eql(u8, ctx.sub, "upgrade")) {1522        _ = try exec.profileUpgrade(ctx.io, &ctx.machine, ctx.gpa);1523        output.done();1524        return;1525    }1526}15271528// --- Pkg commands ---15291530const pkg_help = [_][2][]const u8{1531    .{ "why <pkg>", "what pulled it in" },1532    .{ "deps <pkg>", "direct dependencies" },1533    .{ "size <pkg>", "closure size" },1534    .{ "path <pkg>", "store path" },1535    .{ "closure <pkg>", "full closure" },1536};15371538pub fn pkg(ctx: Ctx) !void {1539    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("pkg", &pkg_help, null);1540    const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1541    if (std.mem.eql(u8, ctx.sub, "why")) {1542        if (try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1543        return;1544    }1545    if (std.mem.eql(u8, ctx.sub, "deps")) {1546        if (try exec.pkgDeps(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1547        return;1548    }1549    if (std.mem.eql(u8, ctx.sub, "size")) {1550        const s = try exec.pkgSize(ctx.gpa, ctx.io, &ctx.machine, name);1551        defer ctx.gpa.free(s);1552        output.pkgResult("size", s);1553        return;1554    }1555    if (std.mem.eql(u8, ctx.sub, "path")) {1556        const p = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, name);1557        defer ctx.gpa.free(p);1558        output.pkgResult("path", p);1559        return;1560    }1561    if (std.mem.eql(u8, ctx.sub, "closure")) {1562        if (try exec.pkgClosure(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1563        return;1564    }1565}15661567// Top-level alias for `nina pkg why <pkg>` — surfaces what pulled a package in1568// without the user needing to know about the `pkg` subgroup.1569pub fn why(ctx: Ctx) !void {1570    const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1571    if (try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1572}15731574// --- Pin / Unpin ---15751576pub fn pin(ctx: Ctx) !void {1577    const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1578    const commit = if (ctx.args.len > 1) ctx.args[1] else return error.Internal;1579    exec.editFlakeLock(ctx.gpa, input, commit) catch return error.ProcessFailed;1580    output.pinDone(input, commit);1581}15821583pub fn unpin(ctx: Ctx) !void {1584    const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1585    _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1586    output.unpinDone(input);1587}15881589// --- Hash / Fetch ---15901591pub fn hash(ctx: Ctx) !void {1592    const path = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1593    const h = try exec.nixHash(ctx.gpa, ctx.io, &ctx.machine, path);1594    defer ctx.gpa.free(h);1595    output.hashResult(std.mem.trim(u8, h, " \t\n\r"));1596}15971598pub fn fetch(ctx: Ctx) !void {1599    const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1600    const h = try exec.nixFetch(ctx.gpa, ctx.io, &ctx.machine, url);1601    defer ctx.gpa.free(h);1602    output.fetchResult(std.mem.trim(u8, h, " \t\n\r"), url);1603}16041605// --- Build / Run ---16061607pub fn build(ctx: Ctx) !void {1608    const attr: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1609    output.buildStart(attr orelse "default");1610    const code = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, attr);1611    if (code != 0) return error.BuildFailed;1612    output.buildDone();1613}16141615pub fn runCmd(ctx: Ctx) !void {1616    const pkg_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1617    output.runStart(pkg_arg);1618    _ = try exec.nixRun(ctx.io, &ctx.machine, ctx.gpa, pkg_arg);1619}16201621// --- Hello ---16221623pub fn hello(ctx: Ctx) !void {1624    output.hello(ctx.cfg.machines);1625}16261627const ConfigKind = enum { flake, channel, none };16281629// Scan the conventional /etc/nixos for a flake.nix (flake-based) or a1630// configuration.nix (channel-based) to pre-fill the wizard's defaults.1631fn scanConfig(io: std.Io) ConfigKind {1632    if (exec.pathExists(io, "/etc/nixos/flake.nix")) return .flake;1633    if (exec.pathExists(io, "/etc/nixos/configuration.nix")) return .channel;1634    return .none;1635}16361637// Runs when the config is absent on first invocation (interactive TTY only).1638// Scans for an existing nixos config, detects flake vs channel, and offers a1639// smart default path — flake-ness is detected, never asked.1640pub fn firstRunWizard(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1641    output.firstRunBanner();1642    output.firstRunNoConfig();16431644    var name_buf: [256]u8 = undefined;1645    var path_buf: [256]u8 = undefined;16461647    const machine_name = output.firstRunPrompt("machine name", "my-machine", &name_buf);16481649    output.firstRunScanning();1650    const kind = scanConfig(io);1651    switch (kind) {1652        .flake => output.firstRunDetected("/etc/nixos/flake.nix", true),1653        .channel => output.firstRunDetected("/etc/nixos/configuration.nix", false),1654        .none => output.firstRunNoneFound(),1655    }16561657    // Detected systems default to /etc/nixos (press enter to confirm); when1658    // nothing was found, leave the default empty so the user must type a path.1659    const default_path: []const u8 = if (kind == .none) "" else "/etc/nixos";1660    const config_path = output.firstRunPromptDefault("config path", default_path, kind != .none, &path_buf);16611662    // Re-detect at the chosen path in case the user pointed elsewhere — flake.nix1663    // there means a flake system, recorded so channel commands warn appropriately.1664    const use_flakes = exec.dirHasFlake(gpa, io, config_path);16651666    const conf_path = try config.configPath(gpa, environ);1667    defer gpa.free(conf_path);1668    if (std.fs.path.dirname(conf_path)) |dir| exec.ensureDir(gpa, io, dir);16691670    // `flake` is a top-level config field, so it must precede the [machine] block.1671    const flake_line = if (use_flakes) "flake = true\n" else "";1672    var content_buf: [1024]u8 = undefined;1673    const content = try std.fmt.bufPrint(1674        &content_buf,1675        "{s}[machine]\nname = {s}\nconfig = {s}\nlocal = true\n",1676        .{ flake_line, machine_name, config_path },1677    );16781679    const file = std.Io.Dir.createFile(.cwd(), io, conf_path, .{}) catch {1680        errors.error_info.setMessage("could not write {s}", .{conf_path});1681        return error.Internal;1682    };1683    defer file.close(io);1684    file.writePositionalAll(io, content, 0) catch {1685        errors.error_info.setMessage("could not write {s}", .{conf_path});1686        return error.Internal;1687    };16881689    output.firstRunWritten(conf_path);1690}16911692pub fn setup(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1693    // Create the config first if it doesn't exist. This makes `nina setup`1694    // a complete onboarding command — not just a nix-features check. Any legacy1695    // ~/.nina.conf is migrated to the XDG path before we decide to run the wizard.1696    config.migrateLegacyConfig(gpa, io, environ);1697    if (config.configPath(gpa, environ)) |conf_path| {1698        defer gpa.free(conf_path);1699        if (std.Io.Dir.openFile(.cwd(), io, conf_path, .{})) |f| {1700            f.close(io);1701        } else |_| {1702            try firstRunWizard(gpa, io, environ);1703            errors.error_info.reset();1704        }1705    } else |_| {}17061707    output.setupCheck();1708    const status = exec.checkNixFeatures(gpa, io, environ);1709    output.setupFeatures(status.nix_command, status.flakes);17101711    if (status.allEnabled()) {1712        output.setupAllSet();1713        api.ensureRegistryPinned(gpa, io, environ);1714        return;1715    }17161717    // On NixOS the features belong in configuration.nix (the declarative,1718    // permanent home), not ~/.config/nix/nix.conf. Offer to add the one line;1719    // the user runs the rebuild. We don't pin the registry here because the1720    // features aren't live until that rebuild lands.1721    if (exec.isNixOS(io)) {1722        const conf_path = "/etc/nixos/configuration.nix";1723        if (exec.nixosConfigEnablesFeatures(gpa, io, conf_path)) {1724            output.setupNixosNeedsRebuild(conf_path);1725            return;1726        }1727        output.setupNixosOffer(exec.NIXOS_FEATURES_LINE, conf_path);1728        if (output.confirmDefaultNo("add it now?")) {1729            if (exec.appendFeaturesToNixosConfig(gpa, io, environ, conf_path)) |_| {1730                output.setupNixosWrote(conf_path);1731            } else |_| {1732                output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);1733            }1734        } else {1735            output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);1736        }1737        return;1738    }17391740    // Non-NixOS: a user-level nix.conf takes effect immediately, no sudo needed.1741    output.setupEnabling();1742    const path = try exec.enableNixFeatures(gpa, io, environ);1743    defer gpa.free(path);17441745    output.setupDone(path);1746    api.ensureRegistryPinned(gpa, io, environ);1747}17481749// --- Log helper ---17501751fn logAction(ctx: Ctx, action: []const u8, gen: u32) void {1752    var ts_buf: [32]u8 = undefined;1753    const ts = nowIso(ctx.io, &ts_buf);1754    var buf: [256]u8 = undefined;1755    const entry = std.fmt.bufPrint(&buf, "{{\"ts\":\"{s}\",\"machine\":\"{s}\",\"command\":\"{s}\",\"outcome\":\"success\",\"gen_before\":null,\"gen_after\":{d},\"duration_ms\":0}}\n", .{1756        ts, ctx.machine.name, action, gen,1757    }) catch return;1758    exec.appendNinaLog(ctx.io, ctx.environ, entry);1759}17601761// Wall-clock UTC as ISO-8601. Uses Io.Clock.real (the settable Unix-epoch clock);1762// Io.Clock.awake is monotonic and unsuitable for timestamps. Falls back to epoch 0.1763fn nowIso(io: std.Io, buf: []u8) []const u8 {1764    const fallback = "1970-01-01T00:00:00Z";1765    const ns = std.Io.Clock.real.now(io).toNanoseconds();1766    if (ns <= 0) return fallback;1767    const secs: u64 = @intCast(@divFloor(ns, 1_000_000_000));1768    const es = std.time.epoch.EpochSeconds{ .secs = secs };1769    const ed = es.getEpochDay();1770    const yd = ed.calculateYearDay();1771    const md = yd.calculateMonthDay();1772    const ds = es.getDaySeconds();1773    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", .{1774        yd.year,              md.month.numeric(),      @as(u32, md.day_index) + 1,1775        ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(),1776    }) catch return fallback;1777}