commands.zig

74.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";1516const Semver = struct {17    major: u32,18    minor: u32,19    patch: u32,20};2122pub const Ctx = struct {23    gpa: std.mem.Allocator,24    io: std.Io,25    environ: *const std.process.Environ.Map,26    machine: types.Machine,27    cfg: types.NinaConfig,28    args: []const []const u8, // positional args after subcommand29    sub: []const u8, // subcommand (e.g. "list" in "service list")30    dry: bool,31    check: bool,32    no_apply: bool,33    all: bool,34    last: u32,35    json: bool,36    user: bool, // --user: operate on user (vs system) services37};3839// A system is flake-managed when the config says so OR a flake.nix is present in40// the config dir. Detection means a fresh channel user who points nina at a flake41// dir gets the right behavior without editing config first.42fn flakeSystem(ctx: Ctx) bool {43    return ctx.cfg.flake or exec.configHasFlake(ctx.gpa, ctx.io, &ctx.machine);44}4546fn runPreHook(ctx: Ctx, hook_name: []const u8) !bool {47    const hook = try exec.runHook(ctx.gpa, ctx.io, ctx.environ, hook_name);48    defer ctx.gpa.free(hook.output);49    switch (hook.result) {50        .not_found, .ok => return true,51        .failed => {52            output.hookFailed(hook_name, hook.exit_code, hook.output);53            return output.confirmDefaultNo("continue anyway?");54        },55    }56}5758fn runPostHook(ctx: Ctx, hook_name: []const u8) void {59    const hook = exec.runHook(ctx.gpa, ctx.io, ctx.environ, hook_name) catch return;60    defer ctx.gpa.free(hook.output);61    if (hook.result == .failed) {62        output.hookWarning(hook_name, hook.exit_code, hook.output);63    }64}6566pub fn apply(ctx: Ctx) !void {67    if (ctx.dry) {68        output.applyDry(ctx.machine.name);69        const code = try exec.nixosRebuildDryActivate(ctx.io, &ctx.machine, ctx.gpa);70        if (code != 0) return error.BuildFailed;71        output.applyDryDone();72        return;73    }74    if (ctx.check) {75        return check(ctx);76    }7778    if (!try runPreHook(ctx, "pre-apply")) {79        output.aborted();80        return error.HookAborted;81    }8283    output.applyStart(ctx.machine.name);84    output.buildPanelInit();85    const start = std.Io.Clock.awake.now(ctx.io);8687    var panel = output.BuildPanel{};88    const code = exec.nixosRebuildSwitchWithPanel(ctx.io, &ctx.machine, ctx.gpa, &panel) catch |e| {89        output.buildPanelClear();90        exec.markApplyFailed(ctx.io, ctx.environ);91        return e;92    };93    output.buildPanelClear();9495    if (code != 0) {96        exec.markApplyFailed(ctx.io, ctx.environ);97        return error.BuildFailed;98    }99100    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());101    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));102    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;103    const after_failure = exec.takeApplyFailed(ctx.io, ctx.environ);104    output.applyDone(gen, elapsed, after_failure);105    // Show any nix warnings collected during the build (dim yellow, after success line).106    const warnings = errors.extractWarnings(ctx.gpa, errors.getBuildStderr()) catch &.{};107    defer {108        for (warnings) |w| ctx.gpa.free(w);109        ctx.gpa.free(warnings);110    }111    if (warnings.len > 0) output.buildWarnings(warnings);112    runPostHook(ctx, "post-apply");113    logAction(ctx, "apply", gen);114}115116pub fn check(ctx: Ctx) !void {117    output.checkStart(ctx.machine.name);118    const code = try exec.nixosRebuildBuild(ctx.io, &ctx.machine, ctx.gpa);119    if (code != 0) return error.BuildFailed;120    output.checkOk();121}122123pub fn back(ctx: Ctx) !void {124    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);125    defer ctx.gpa.free(gens);126127    var current: u32 = 0;128    for (gens) |g| if (g.current) {129        current = g.number;130    };131132    // Newest generation older than current. If there is none, we're already at the133    // oldest — stop cleanly instead of letting rollback fail with 'build failed'.134    var prev: u32 = 0;135    var has_prev = false;136    for (gens) |g| {137        if (g.number < current and (!has_prev or g.number > prev)) {138            prev = g.number;139            has_prev = true;140        }141    }142    if (!has_prev) {143        output.alreadyOldest();144        return;145    }146147    if (!try runPreHook(ctx, "pre-back")) {148        output.aborted();149        return error.HookAborted;150    }151152    output.backStart(ctx.machine.name, current, prev);153    if (ctx.cfg.confirm and !output.confirm("")) return;154155    // Flake systems don't have <nixos-config> in the Nix search path, so156    // `nixos-rebuild --rollback` fails. Switch by generation number instead157    // (same path as `nina go N`), which works for both channel and flake.158    const code = if (flakeSystem(ctx))159        try exec.switchGeneration(ctx.io, &ctx.machine, ctx.gpa, prev)160    else161        try exec.rollback(ctx.io, &ctx.machine, ctx.gpa);162    if (code != 0) return error.BuildFailed;163    output.backDone(prev);164    runPostHook(ctx, "post-back");165}166167pub fn go(ctx: Ctx) !void {168    if (ctx.args.len == 0) return error.Internal;169    const target = std.fmt.parseInt(u32, ctx.args[0], 10) catch return error.Internal;170    const current = try exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine);171172    output.goStart(ctx.machine.name, current, target);173    if (ctx.cfg.confirm and !output.confirm("")) return;174175    const code = try exec.switchGeneration(ctx.io, &ctx.machine, ctx.gpa, target);176    if (code != 0) return error.ProcessFailed;177    output.generationDone(target);178}179180pub fn history(ctx: Ctx) !void {181    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);182    defer ctx.gpa.free(gens);183    output.historyHeader(ctx.machine.name);184    for (gens) |g| output.historyRow(g);185}186187const gen_help = [_][2][]const u8{188    .{ "list", "list generations" },189    .{ "current", "show current generation" },190    .{ "delete <n>", "delete generation n" },191    .{ "delete old", "delete old generations" },192};193194pub fn genCmd(ctx: Ctx) !void {195    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("gen", &gen_help, null);196    if (std.mem.eql(u8, ctx.sub, "list")) return history(ctx);197    if (std.mem.eql(u8, ctx.sub, "current")) {198        const n = try exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine);199        output.genCurrent(n);200        return;201    }202    if (std.mem.eql(u8, ctx.sub, "delete")) {203        if (ctx.args.len == 0) return error.Internal;204        if (std.mem.eql(u8, ctx.args[0], "old")) {205            if (ctx.cfg.confirm and !output.confirm("")) return;206            _ = try exec.deleteOldGenerations(ctx.io, &ctx.machine, ctx.gpa);207        } else {208            const n = std.fmt.parseInt(u32, ctx.args[0], 10) catch return error.Internal;209            if (ctx.cfg.confirm and !output.confirm("")) return;210            _ = try exec.deleteGeneration(ctx.io, &ctx.machine, ctx.gpa, n);211        }212        output.done();213        return;214    }215    return error.Internal;216}217218pub fn clean(ctx: Ctx) !void {219    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);220    defer ctx.gpa.free(gens);221    const all = ctx.all or std.mem.eql(u8, ctx.sub, "all");222    const total: u32 = @intCast(gens.len);223    // `clean all` keeps only the current generation; otherwise keep the configured224    // count. With nothing older than the keep limit, there's nothing to collect.225    const keep: u32 = if (all) 1 else ctx.cfg.generations;226    if (total <= keep) {227        output.cleanNothing(ctx.machine.name, total);228        return;229    }230    output.cleanStart(ctx.machine.name, keep, total);231    if (ctx.cfg.confirm and !output.confirm("removing — cannot be undone")) return;232    _ = try exec.collectGarbage(ctx.io, &ctx.machine, ctx.gpa, all, ctx.cfg.generations);233    output.cleanDone();234}235236pub fn statusCmd(ctx: Ctx) !void {237    output.statusHeader();238    // --all renders every configured machine; remotes route through the same SSH239    // path as exec.capture. An unreachable machine is shown in red, not fatal.240    if (ctx.all and ctx.cfg.machines.len > 0) {241        for (ctx.cfg.machines) |m| statusRowFor(ctx, &m);242    } else {243        statusRowFor(ctx, &ctx.machine);244    }245    homeStatusLine(ctx);246}247248// When standalone Home Manager is present, show its current generation as a dim249// line indented under the machine rows. Gated on standalone mode (the only mode250// where we can read a generation), so a machine without HM is unaffected.251fn homeStatusLine(ctx: Ctx) void {252    if (exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ) != .standalone) return;253    const out = exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine) catch return;254    defer ctx.gpa.free(out);255    const gens = parseHomeGenerations(ctx.gpa, out) catch return;256    defer freeHomeGens(ctx.gpa, gens);257    if (gens.len == 0) return;258    output.statusHomeRow(gens[0].number, gens[0].date);259}260261fn statusRowFor(ctx: Ctx, machine: *const types.Machine) void {262    // A failure to read the current generation means we couldn't reach or query263    // the machine — mark it unreachable rather than reporting a bogus gen 0.264    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, machine) catch {265        output.statusRow(machine.name, 0, "", "", false);266        return;267    };268    const st = exec.systemStatus(ctx.gpa, ctx.io, machine);269    defer ctx.gpa.free(st.size);270    defer ctx.gpa.free(st.age);271    output.statusRow(machine.name, gen, st.age, st.size, true);272}273274pub fn diff(ctx: Ctx) !void {275    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);276    defer ctx.gpa.free(gens);277    var current: u32 = 0;278    var prev: u32 = 0;279    for (gens) |g| {280        if (g.current) current = g.number;281        if (!g.current and g.number > prev and g.number < current) prev = g.number;282    }283    if (ctx.args.len >= 2) {284        const a = std.fmt.parseInt(u32, ctx.args[0], 10) catch current - 1;285        const b = std.fmt.parseInt(u32, ctx.args[1], 10) catch current;286        output.diffHeader(a, b, ctx.machine.name);287        if (try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, a, b) != 0) return error.ProcessFailed;288    } else {289        output.diffHeader(if (prev > 0) prev else current - 1, current, ctx.machine.name);290        if (try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, if (prev > 0) prev else current - 1, current) != 0) return error.ProcessFailed;291    }292}293294pub fn mood(ctx: Ctx) !void {295    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;296    const st = exec.systemStatus(ctx.gpa, ctx.io, &ctx.machine);297    defer ctx.gpa.free(st.size);298    defer ctx.gpa.free(st.age);299    const state = exec.systemRunningState(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");300    defer ctx.gpa.free(state);301    output.mood(ctx.machine.name, state, gen, st.age, st.size);302}303304pub fn doctor(ctx: Ctx) !void {305    output.doctorHeader(ctx.machine.name);306    const checks = try exec.runDoctorChecks(ctx.gpa, ctx.io, &ctx.machine);307    defer ctx.gpa.free(checks);308    var warnings: u32 = 0;309    var failures: u32 = 0;310    for (checks) |ch| {311        output.doctorRow(ch);312        if (ch.status == .warn) warnings += 1;313        if (ch.status == .fail) failures += 1;314    }315316    // Home Manager row only when present — absent on a machine without HM, so317    // doctor's table is unchanged there.318    const hm_mode = exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ);319    if (hm_mode != .none) {320        const note = homeDoctorNote(ctx, hm_mode);321        defer ctx.gpa.free(note);322        output.doctorRow(.{ .name = "home manager", .status = .ok, .note = note });323    }324325    output.doctorSummary(warnings, failures);326}327328// "standalone  gen 765" / "module" — the note shown in doctor's home manager row.329// Caller owns the returned slice.330fn homeDoctorNote(ctx: Ctx, mode: exec.HomeManagerMode) []const u8 {331    const label = switch (mode) {332        .standalone => "standalone",333        .module => "module",334        .none => "",335    };336    if (mode == .standalone) {337        const gen = homeCurrentGen(ctx);338        if (gen != 0)339            return std.fmt.allocPrint(ctx.gpa, "{s}  gen {d}", .{ label, gen }) catch340                (ctx.gpa.dupe(u8, label) catch "");341    }342    return ctx.gpa.dupe(u8, label) catch "";343}344345// nina update — kepr self-update for the nina binary itself.346pub fn update(ctx: Ctx) !void {347    output.updateSelfStart();348349    if (comptime std.mem.eql(u8, version.PLATFORM, "unsupported")) {350        output.updateSelfNoPlatform(@tagName(builtin.cpu.arch) ++ "-" ++ @tagName(builtin.os.tag));351        return error.Internal;352    }353354    const env_url = ctx.environ.get("NINA_UPDATE_SOURCE");355    const source_url = env_url orelse UPDATE_URL;356357    const body = exec.fetchUrl(ctx.gpa, ctx.io, source_url) catch |e| switch (e) {358        error.NetworkError, error.HttpError => {359            output.updateSelfNetworkError();360            return;361        },362        else => return e,363    };364    defer ctx.gpa.free(body);365366    const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, body, .{}) catch {367        output.printWarning("could not parse release metadata");368        return;369    };370    defer parsed.deinit();371372    const root = parsed.value;373    if (root != .object) {374        output.printWarning("malformed release metadata");375        return;376    }377378    const remote_ver = blk: {379        const v = root.object.get("version") orelse {380            output.printWarning("malformed release metadata");381            return;382        };383        break :blk switch (v) {384            .string => |s| s,385            else => {386                output.printWarning("malformed release metadata");387                return;388            },389        };390    };391    if (!remoteVersionNewer(version.VERSION, remote_ver)) {392        output.updateSelfCurrent(version.VERSION);393        return;394    }395396    const release_notes = try updateReleaseNotes(ctx.gpa, ctx.io, root, source_url, version.VERSION, remote_ver);397    defer ctx.gpa.free(release_notes);398399    output.updateSelfAvailable(version.VERSION, remote_ver);400    output.updateSelfReleaseNotes(release_notes);401    if (ctx.check) return;402403    var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;404    const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {405        errors.error_info.setMessage("could not determine install path", .{});406        return error.Internal;407    };408409    // When running from the nix store, defer to nix profile upgrade so nix410    // manages the transition (the store is read-only; binary replacement fails).411    // A NixOS system install also resolves into the store but isn't a profile412    // element, so check the profile to avoid a no-op `upgrade` — it updates with413    // the next nixos-rebuild instead.414    if (std.mem.startsWith(u8, install_path, "/nix/store/")) {415        const nina_info = exec.profileNinaInfo(ctx.gpa, ctx.io, &ctx.machine);416        defer {417            if (nina_info) |n| {418                ctx.gpa.free(n.name);419                if (n.original_url) |u| ctx.gpa.free(u);420            }421        }422        if (nina_info == null) {423            output.updateSelfNotInProfile();424            return;425        }426        const nina = nina_info.?;427        output.updateSelfNixManaged(remote_ver);428        if (ctx.cfg.confirm and !output.confirm("")) return;429        // Pass originalUrl as the installable when available. Nix 2.18+ treats a430        // bare element name as a registry lookup (e.g. nixpkgs#nina) which silently431        // no-ops for tarball installs; the original URL targets the right source.432        const upgrade_arg = nina.original_url orelse nina.name;433        const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "upgrade", upgrade_arg }) catch {434            output.updateSelfNixFailed();435            return;436        };437        if (ec != 0) {438            output.updateSelfNixFailed();439            return;440        }441        output.updateSelfDone(version.VERSION, remote_ver);442        output.updateSelfNixRehash();443        return;444    }445446    const plat_info = blk: {447        const pv = root.object.get("platforms") orelse break :blk null;448        if (pv != .object) break :blk null;449        break :blk pv.object.get(version.PLATFORM);450    };451    if (plat_info == null) {452        output.updateSelfNoPlatform(version.PLATFORM);453        return;454    }455456    const dl_url = blk: {457        const v = plat_info.?.object.get("url") orelse {458            output.printWarning("malformed release metadata");459            return;460        };461        break :blk switch (v) {462            .string => |s| s,463            else => {464                output.printWarning("malformed release metadata");465                return;466            },467        };468    };469470    const raw_cksum = blk: {471        if (plat_info.?.object.get("blake3")) |v|472            break :blk switch (v) {473                .string => |s| s,474                else => {475                    output.printWarning("malformed release metadata");476                    return;477                },478            };479        if (plat_info.?.object.get("checksum")) |v|480            break :blk switch (v) {481                .string => |s| s,482                else => {483                    output.printWarning("malformed release metadata");484                    return;485                },486            };487        output.printWarning("missing checksum in release metadata");488        return;489    };490    const expected_hex = if (std.mem.startsWith(u8, raw_cksum, "blake3:")) raw_cksum["blake3:".len..] else raw_cksum;491492    if (ctx.cfg.confirm and !output.confirm("")) return;493494    output.updateSelfDownloading(remote_ver, version.PLATFORM);495    const tmp_path = exec.downloadToTemp(ctx.gpa, ctx.io, dl_url) catch {496        output.printWarning("download failed — check your connection and try again");497        return;498    };499    defer ctx.gpa.free(tmp_path);500501    output.updateSelfVerifying();502    exec.verifyAndInstall(ctx.gpa, ctx.io, tmp_path, expected_hex, install_path) catch |e| switch (e) {503        error.ChecksumMismatch => {504            output.updateSelfChecksumFailed();505            return;506        },507        else => return e,508    };509510    output.updateSelfDone(version.VERSION, remote_ver);511}512513fn updateReleaseNotes(gpa: std.mem.Allocator, io: std.Io, root: std.json.Value, source_url: []const u8, current: []const u8, latest: []const u8) ![]u8 {514    if (releaseNotesFromMetadata(gpa, root)) |notes| {515        if (std.mem.trim(u8, notes, " \t\r\n").len > 0) return notes;516        gpa.free(notes);517    }518    return buildKeprArchiveReleaseNotes(gpa, io, source_url, current, latest) catch gpa.dupe(u8, "");519}520521fn releaseNotesFromMetadata(gpa: std.mem.Allocator, root: std.json.Value) ?[]u8 {522    if (root != .object) return null;523    const keys = [_][]const u8{ "release_notes", "changelog", "notes" };524    for (keys) |key| {525        const v = root.object.get(key) orelse continue;526        switch (v) {527            .string => |s| return gpa.dupe(u8, s) catch null,528            else => {},529        }530    }531    return null;532}533534fn buildKeprArchiveReleaseNotes(gpa: std.mem.Allocator, io: std.Io, source_url: []const u8, current: []const u8, latest: []const u8) ![]u8 {535    const archive_url = try keprArchiveUrl(gpa, source_url);536    defer gpa.free(archive_url);537538    const body = exec.fetchUrl(gpa, io, archive_url) catch return gpa.dupe(u8, "");539    defer gpa.free(body);540541    return releaseNotesFromArchiveJson(gpa, body, current, latest);542}543544fn keprArchiveUrl(gpa: std.mem.Allocator, source_url: []const u8) ![]u8 {545    const scheme = std.mem.indexOf(u8, source_url, "://") orelse return error.InvalidUpdateSource;546    const path_start = std.mem.indexOfScalarPos(u8, source_url, scheme + 3, '/') orelse return error.InvalidUpdateSource;547    const origin = source_url[0..path_start];548    const path = source_url[path_start..];549    if (!std.mem.startsWith(u8, path, "/api/")) return error.InvalidUpdateSource;550551    const after_api = path["/api/".len..];552    const repo_end = std.mem.indexOfScalar(u8, after_api, '/') orelse return error.InvalidUpdateSource;553    const repo = after_api[0..repo_end];554    if (repo.len == 0) return error.InvalidUpdateSource;555556    return std.fmt.allocPrint(gpa, "{s}/{s}/archives.json?limit=40", .{ origin, repo });557}558559fn releaseNotesFromArchiveJson(gpa: std.mem.Allocator, body: []const u8, current: []const u8, latest: []const u8) ![]u8 {560    const parsed = std.json.parseFromSlice(std.json.Value, gpa, body, .{}) catch return gpa.dupe(u8, "");561    defer parsed.deinit();562563    if (parsed.value != .object) return gpa.dupe(u8, "");564    const saves_v = parsed.value.object.get("saves") orelse return gpa.dupe(u8, "");565    if (saves_v != .array) return gpa.dupe(u8, "");566567    var out: std.ArrayList(u8) = .empty;568    errdefer out.deinit(gpa);569    var any = false;570    for (saves_v.array.items) |save| {571        if (save != .object) continue;572        const ver_v = save.object.get("version") orelse continue;573        const msg_v = save.object.get("message") orelse continue;574        if (ver_v != .string or msg_v != .string) continue;575        const ver = ver_v.string;576        const msg = std.mem.trim(u8, msg_v.string, " \t\r\n");577        if (msg.len == 0 or !versionInUpdateRange(ver, current, latest)) continue;578579        try appendFmt(&out, gpa, "## {s}\n", .{ver});580        try appendFmt(&out, gpa, "- {s}\n\n", .{msg});581        any = true;582    }583584    if (!any) {585        out.deinit(gpa);586        return gpa.dupe(u8, "");587    }588    return out.toOwnedSlice(gpa);589}590591fn appendFmt(out: *std.ArrayList(u8), gpa: std.mem.Allocator, comptime template: []const u8, args: anytype) !void {592    const line = try std.fmt.allocPrint(gpa, template, args);593    defer gpa.free(line);594    try out.appendSlice(gpa, line);595}596597fn versionInUpdateRange(candidate: []const u8, current: []const u8, latest: []const u8) bool {598    const cand = parseSemver(candidate) orelse return std.mem.eql(u8, candidate, latest);599    const cur = parseSemver(current) orelse return std.mem.eql(u8, candidate, latest);600    const lat = parseSemver(latest) orelse return std.mem.eql(u8, candidate, latest);601    return compareSemver(cand, cur) == .gt and compareSemver(cand, lat) != .gt;602}603604fn remoteVersionNewer(current: []const u8, remote: []const u8) bool {605    const cur = parseSemver(current) orelse return !std.mem.eql(u8, current, remote);606    const rem = parseSemver(remote) orelse return !std.mem.eql(u8, current, remote);607    return compareSemver(rem, cur) == .gt;608}609610const VersionOrder = enum { lt, eq, gt };611612fn compareSemver(a: Semver, b: Semver) VersionOrder {613    if (a.major != b.major) return if (a.major < b.major) .lt else .gt;614    if (a.minor != b.minor) return if (a.minor < b.minor) .lt else .gt;615    if (a.patch != b.patch) return if (a.patch < b.patch) .lt else .gt;616    return .eq;617}618619fn parseSemver(raw: []const u8) ?Semver {620    const v = if (std.mem.startsWith(u8, raw, "v")) raw[1..] else raw;621    var it = std.mem.splitScalar(u8, v, '.');622    const major_s = it.next() orelse return null;623    const minor_s = it.next() orelse return null;624    const patch_s = it.next() orelse return null;625    if (it.next() != null) return null;626    return .{627        .major = std.fmt.parseInt(u32, major_s, 10) catch return null,628        .minor = std.fmt.parseInt(u32, minor_s, 10) catch return null,629        .patch = std.fmt.parseInt(u32, patch_s, 10) catch return null,630    };631}632633test "versionInUpdateRange includes only newer versions through latest" {634    try std.testing.expect(versionInUpdateRange("3.2.3", "3.1.9", "3.2.3"));635    try std.testing.expect(versionInUpdateRange("3.2.0", "3.1.9", "3.2.3"));636    try std.testing.expect(!versionInUpdateRange("3.1.9", "3.1.9", "3.2.3"));637    try std.testing.expect(!versionInUpdateRange("3.2.4", "3.1.9", "3.2.3"));638}639640test "remoteVersionNewer does not offer downgrades" {641    try std.testing.expect(remoteVersionNewer("3.2.3", "3.2.4"));642    try std.testing.expect(!remoteVersionNewer("3.2.4", "3.2.3"));643    try std.testing.expect(!remoteVersionNewer("3.2.4", "3.2.4"));644}645646test "releaseNotesFromArchiveJson builds changelog from versioned saves" {647    const body =648        \\{649        \\  "saves": [650        \\    {"version":"3.2.3","message":"upgrade: live build panel during rebuild phase"},651        \\    {"version":"3.1.9","message":"old release"},652        \\    {"version":null,"message":"unversioned"}653        \\  ]654        \\}655    ;656    const notes = try releaseNotesFromArchiveJson(std.testing.allocator, body, "3.1.9", "3.2.3");657    defer std.testing.allocator.free(notes);658659    try std.testing.expect(std.mem.indexOf(u8, notes, "## 3.2.3") != null);660    try std.testing.expect(std.mem.indexOf(u8, notes, "- upgrade: live build panel") != null);661    try std.testing.expect(std.mem.indexOf(u8, notes, "old release") == null);662}663664// nina goodbye — clean uninstall. Three install paths:665// - nix profile (binary in nix store with a profile element) → nix profile remove666// - koh build or source build (plain binary on PATH) → delete the file667pub fn goodbye(ctx: Ctx) !void {668    output.goodbyeStart();669670    var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;671    const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {672        errors.error_info.setMessage("could not determine install path", .{});673        return error.Internal;674    };675676    // A binary outside the nix store is a koh build or source build — delete it.677    if (!std.mem.startsWith(u8, install_path, "/nix/store/")) {678        output.goodbyeFile(install_path);679        if (ctx.cfg.confirm and !output.confirm("")) return;680        std.Io.Dir.deleteFileAbsolute(ctx.io, install_path) catch |e| {681            errors.error_info.setMessage("could not remove {s}", .{install_path});682            return e;683        };684        output.goodbyeDone();685        return;686    }687688    // Binary is in the nix store — find and remove the profile element.689    const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);690    defer {691        if (nina_element) |n| ctx.gpa.free(n);692    }693694    if (nina_element == null) {695        errors.error_info.setMessage("nina not found in nix profile — was it installed via 'nix profile add'?", .{});696        return error.Internal;697    }698699    output.goodbyeNix();700    if (ctx.cfg.confirm and !output.confirm("")) return;701    const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "remove", nina_element.? }) catch {702        output.goodbyeFailed("nix profile remove failed");703        return;704    };705    if (ec != 0) {706        output.goodbyeFailed("nix profile remove failed");707        return;708    }709    output.goodbyeDone();710}711712fn channelUpdateCmd(ctx: Ctx) !void {713    output.updateStart(ctx.machine.name);714    _ = try exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa);715    output.updateDone();716}717718pub fn upgrade(ctx: Ctx) !void {719    if (!try runPreHook(ctx, "pre-upgrade")) {720        output.aborted();721        return error.HookAborted;722    }723724    output.upgradeStart(ctx.machine.name);725    // Flake systems update inputs (flake.lock); channel systems update channels.726    // Running nix-channel --update on a flake system is a no-op at best. The727    // rebuild below is already flake-aware via exec.nixosRebuildSwitch.728    if (flakeSystem(ctx)) {729        output.printSubstep("updating flake inputs", .{});730        _ = exec.flakeUpdateAt(ctx.io, &ctx.machine, ctx.gpa, ctx.machine.config_path) catch {};731    } else {732        output.printSubstep("updating channels", .{});733        _ = exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa) catch {};734    }735    output.printSubstep("rebuilding", .{});736    output.buildPanelInit();737    const start = std.Io.Clock.awake.now(ctx.io);738    var panel = output.BuildPanel{};739    const code = exec.nixosRebuildSwitchWithPanel(ctx.io, &ctx.machine, ctx.gpa, &panel) catch |e| {740        output.buildPanelClear();741        return e;742    };743    output.buildPanelClear();744    if (code != 0) {745        output.applyFailed("");746        return error.BuildFailed;747    }748    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());749    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));750    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;751    output.applyDone(gen, elapsed, false);752    runPostHook(ctx, "post-upgrade");753}754755pub fn log(ctx: Ctx) !void {756    output.logHeader(ctx.machine.name);757    const content = exec.readNinaLog(ctx.gpa, ctx.io, ctx.environ, ctx.last) catch {758        // No log yet — that's fine759        return;760    };761    defer ctx.gpa.free(content);762    var lines = std.mem.splitScalar(u8, content, '\n');763    while (lines.next()) |line| {764        const t = std.mem.trim(u8, line, " \t\r");765        if (t.len == 0) continue;766        if (t[0] == '{') {767            renderJsonLogLine(ctx.gpa, t);768        } else {769            // legacy tab-separated format770            var parts = std.mem.tokenizeScalar(u8, t, '\t');771            const date = parts.next() orelse continue;772            const time = parts.next() orelse "";773            const action = parts.next() orelse "";774            const detail = parts.next() orelse "";775            output.logRow(date, time, action, detail);776        }777    }778}779780// The on-disk log is JSON Lines: {"ts","machine","command","outcome","gen_after",...}.781// Render ts -> date/time columns, command -> action, outcome(+gen) -> detail.782fn renderJsonLogLine(gpa: std.mem.Allocator, line: []const u8) void {783    const parsed = std.json.parseFromSlice(std.json.Value, gpa, line, .{}) catch {784        output.logRow(line, "", "", ""); // unparseable — show raw rather than drop785        return;786    };787    defer parsed.deinit();788    if (parsed.value != .object) return;789    const o = parsed.value.object;790791    const ts = jsonStr(o, "ts");792    const date = if (ts.len >= 10) ts[0..10] else ts;793    const time = if (ts.len >= 16) ts[11..16] else "";794    const action = jsonStr(o, "command");795    const outcome = jsonStr(o, "outcome");796797    var buf: [160]u8 = undefined;798    var detail: []const u8 = outcome;799    if (o.get("gen_after")) |g| {800        if (g == .integer) {801            detail = std.fmt.bufPrint(&buf, "{s}   -> gen {d}", .{ outcome, g.integer }) catch outcome;802        }803    }804    output.logRow(date, time, action, detail);805}806807fn jsonStr(o: std.json.ObjectMap, key: []const u8) []const u8 {808    if (o.get(key)) |v| {809        if (v == .string) return v.string;810    }811    return "";812}813814pub fn edit(ctx: Ctx) !void {815    const hardware = ctx.args.len > 0 and std.mem.eql(u8, ctx.args[0], "hardware");816    const filename = if (hardware) "hardware-configuration.nix" else "configuration.nix";817    const path = try std.fmt.allocPrint(ctx.gpa, "{s}/{s}", .{ ctx.machine.config_path, filename });818    defer ctx.gpa.free(path);819    output.editOpen(path, ctx.cfg.editor);820    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);821}822823pub fn fmt(ctx: Ctx) !void {824    const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});825    defer ctx.gpa.free(path);826    if (ctx.check) {827        const code = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, true);828        if (code != 0) output.fmtNeedsFormat() else output.fmtDone();829        return;830    }831    output.fmtStart(path);832    _ = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, false);833    output.fmtDone();834}835836pub fn repl(ctx: Ctx) !void {837    output.replStart();838    _ = try exec.nixRepl(ctx.io, &ctx.machine, ctx.gpa);839}840841pub fn develop(ctx: Ctx) !void {842    if (std.mem.eql(u8, ctx.sub, "show")) {843        _ = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, null);844        return;845    }846    const run_cmd: ?[]const u8 = if (ctx.args.len > 0 and std.mem.eql(u8, ctx.sub, "run"))847        ctx.args[0]848    else849        null;850    output.developStart(&.{});851    _ = try exec.nixDevelopPs1(ctx.io, &ctx.machine, ctx.gpa, run_cmd, ctx.environ);852    output.developDone();853}854855pub fn info(ctx: Ctx) !void {856    output.infoHeader(ctx.machine.name);857    const nixos_ver = exec.systemInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");858    defer ctx.gpa.free(nixos_ver);859    output.infoRow("nixos", std.mem.trim(u8, nixos_ver, " \t\n\r"));860861    const kernel = exec.kernelInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");862    defer ctx.gpa.free(kernel);863    output.infoRow("kernel", std.mem.trim(u8, kernel, " \t\n\r"));864865    const uptime = exec.uptimeInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");866    defer ctx.gpa.free(uptime);867    output.infoRow("uptime", std.mem.trim(u8, uptime, " \t\n\r"));868}869870pub fn boot(ctx: Ctx) !void {871    output.bootHeader(ctx.machine.name);872    const entries = exec.bootEntries(ctx.gpa, ctx.io, &ctx.machine) catch &.{};873    defer ctx.gpa.free(entries);874    for (entries, 0..) |entry, i| output.bootEntry(entry, i);875}876877pub fn searchCmd(ctx: Ctx) !void {878    const query = if (ctx.args.len > 0) ctx.args[0] else "";879    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);880    const selected = try search_tui.run(ctx.gpa, ctx.io, query, .packages);881    if (selected) |npkg| try selectAndInstall(ctx, npkg);882}883884pub fn optionCmd(ctx: Ctx) !void {885    const query = if (ctx.args.len > 0) ctx.args[0] else "";886    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);887    _ = try search_tui.run(ctx.gpa, ctx.io, query, .options);888}889890pub fn install(ctx: Ctx) !void {891    const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;892893    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);894895    // Search for the package to get the attr896    const pkgs = api.searchPackages(ctx.gpa, ctx.io, pkg_name) catch {897        errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});898        errors.error_info.setSuggestion("nina search {s}", .{pkg_name});899        return error.PackageNotFound;900    };901902    if (pkgs.len == 0) {903        // No matches — likely a typo. Suggest the closest real package and offer it.904        if (closestPackage(ctx, pkg_name)) |sugg| {905            output.didYouMean(pkg_name, sugg.pname);906            if (output.confirm("")) try selectAndInstall(ctx, sugg);907            return;908        }909        errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});910        errors.error_info.setSuggestion("nina search {s}", .{pkg_name});911        return error.PackageNotFound;912    }913914    // Prefer an exact name match over the first search result — `install ripgrep`915    // must pick "ripgrep", not the alphabetically-first match like "repgrep".916    var found = pkgs[0];917    for (pkgs) |p| {918        if (std.mem.eql(u8, p.pname, pkg_name)) {919            found = p;920            break;921        }922    }923    try selectAndInstall(ctx, found);924}925926// Find the real package whose name is closest to a not-found query (typo help).927// Typos usually keep the leading characters, so gather candidates with a prefix928// search and rank by edit distance; return the best only if it's typo-close.929fn closestPackage(ctx: Ctx, query: []const u8) ?types.NixPackage {930    if (query.len < 2) return null;931    var candidates = api.searchPackages(ctx.gpa, ctx.io, query[0..@min(query.len, 4)]) catch &.{};932    if (candidates.len == 0 and query.len > 2) {933        candidates = api.searchPackages(ctx.gpa, ctx.io, query[0..2]) catch &.{};934    }935    if (candidates.len == 0) return null;936937    var best: ?types.NixPackage = null;938    var best_dist: usize = std.math.maxInt(usize);939    for (candidates) |p| {940        const d = editDistance(query, p.pname);941        if (d > 0 and d < best_dist) {942            best_dist = d;943            best = p;944        }945    }946    // Only suggest a genuinely close name, scaled to query length.947    const threshold = @max(@as(usize, 2), query.len / 3);948    return if (best_dist <= threshold) best else null;949}950951// Case-insensitive Levenshtein distance. Names longer than the row buffer are952// treated as far away (never suggested).953fn editDistance(a: []const u8, b: []const u8) usize {954    const n = b.len;955    if (a.len == 0) return n;956    if (n == 0) return a.len;957    if (n + 1 > 128) return std.math.maxInt(usize);958    var prev: [128]usize = undefined;959    var curr: [128]usize = undefined;960    var j: usize = 0;961    while (j <= n) : (j += 1) prev[j] = j;962    var i: usize = 1;963    while (i <= a.len) : (i += 1) {964        curr[0] = i;965        j = 1;966        while (j <= n) : (j += 1) {967            const cost: usize = if (std.ascii.toLower(a[i - 1]) == std.ascii.toLower(b[j - 1])) 0 else 1;968            curr[j] = @min(prev[j] + 1, @min(curr[j - 1] + 1, prev[j - 1] + cost));969        }970        @memcpy(prev[0 .. n + 1], curr[0 .. n + 1]);971    }972    return prev[n];973}974975test "editDistance is case-insensitive Levenshtein" {976    try std.testing.expectEqual(@as(usize, 1), editDistance("firefux", "firefox"));977    try std.testing.expectEqual(@as(usize, 0), editDistance("git", "GIT"));978    try std.testing.expectEqual(@as(usize, 2), editDistance("fierfox", "firefox"));979    try std.testing.expectEqual(@as(usize, 7), editDistance("", "firefox"));980}981982// Prompt for the install method (profile / system / try) and dispatch. Shared by983// `nina install <pkg>` and the search widget's Enter-to-select — the letter keys984// are read here, after the search widget's raw mode is gone, so they don't985// collide with typing a query.986fn selectAndInstall(ctx: Ctx, npkg: types.NixPackage) !void {987    output.installSelectPrompt(npkg.pname, npkg.version);988989    var choice_buf: [8]u8 = undefined;990    var choice_len: usize = 0;991    while (choice_len < choice_buf.len) {992        const n = std.posix.read(std.posix.STDIN_FILENO, choice_buf[choice_len .. choice_len + 1]) catch break;993        if (n == 0) break;994        if (choice_buf[choice_len] == '\n') break;995        choice_len += 1;996    }997    const choice = std.mem.trim(u8, choice_buf[0..choice_len], " \t");998999    if (choice.len == 0 or choice[0] == 'i' or choice[0] == 'I') {1000        try profileInstallPkg(ctx, npkg);1001    } else if (choice[0] == 's' or choice[0] == 'S') {1002        try systemInstallPkg(ctx, npkg);1003    } else if (choice[0] == 't' or choice[0] == 'T') {1004        try tryPkg(ctx, npkg);1005    }1006}10071008fn profileInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {1009    output.installStart(npkg.pname, .profile);1010    output.printSubstep("nix profile add nixpkgs#{s}", .{npkg.attr});1011    output.printTeach(try std.fmt.allocPrint(ctx.gpa, "nix profile add nixpkgs#{s}", .{npkg.attr}));1012    const code = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, npkg.attr);1013    if (code != 0) return error.ProcessFailed;1014    output.installDone(npkg.pname);1015}10161017fn systemInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {1018    const config_path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});1019    defer ctx.gpa.free(config_path);1020    const line = api.findSystemPackagesLine(ctx.io, config_path) orelse 1;1021    output.installEditorPrompt(npkg.pname, config_path, line, ctx.cfg.editor);1022    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, config_path, line);1023    if (ctx.cfg.confirm) {1024        if (output.confirm("apply now? ")) {1025            try apply(ctx);1026        }1027    }1028}10291030fn tryPkg(ctx: Ctx, npkg: types.NixPackage) !void {1031    output.tryStart(npkg.pname);1032    output.printSubstep("nix shell nixpkgs#{s}", .{npkg.attr});1033    output.tryExitHint();1034    _ = try exec.nixShellPs1(ctx.io, &ctx.machine, ctx.gpa, npkg.attr, ctx.environ);1035    output.tryDone();1036}10371038pub fn remove(ctx: Ctx) !void {1039    const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1040    output.removeStart(pkg_name);1041    const code = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, pkg_name);1042    if (code != 0) return error.ProcessFailed;1043    output.done();1044}10451046pub fn list(ctx: Ctx) !void {1047    output.listHeader(ctx.machine.name);10481049    // Profile packages: parse `nix profile list --json` into clean name+version1050    // rows instead of dumping nix's verbose multi-line "Name:/Flake attribute:"1051    // blocks.1052    if (exec.profileListJson(ctx.gpa, ctx.io, &ctx.machine) catch null) |json| {1053        defer ctx.gpa.free(json);1054        output.listSection("profile");1055        renderProfileJson(ctx.gpa, json);1056    }10571058    // System packages: the references of /run/current-system/sw, each a1059    // <hash>-<name>-<version> store path.1060    if (exec.systemPackagePaths(ctx.gpa, ctx.io, &ctx.machine) catch null) |paths| {1061        defer ctx.gpa.free(paths);1062        output.blankLine();1063        output.listSection("system");1064        var lines = std.mem.splitScalar(u8, paths, '\n');1065        while (lines.next()) |line| {1066            const t = std.mem.trim(u8, line, " \t\r");1067            if (t.len == 0) continue;1068            const row = pkgFromStorePath(t);1069            // Skip support paths with no parseable version (man pages, wrappers).1070            if (row.version.len == 0) continue;1071            output.listPkg(row.name, row.version);1072        }1073    }1074}10751076const PkgRow = struct { name: []const u8, version: []const u8 };10771078// Split a nix store path basename (<hash>-<name>-<version>) into name + version.1079// Version begins at the first '-' followed by a digit, which reliably lands on1080// the name/version boundary since the 32-char hash and package names start with1081// non-digits.1082fn pkgFromStorePath(path: []const u8) PkgRow {1083    const base = std.fs.path.basename(path);1084    const after_hash = if (base.len > 33 and base[32] == '-') base[33..] else base;1085    var i: usize = 0;1086    while (i + 1 < after_hash.len) : (i += 1) {1087        if (after_hash[i] == '-' and std.ascii.isDigit(after_hash[i + 1])) {1088            return .{ .name = after_hash[0..i], .version = stripOutputSuffix(after_hash[i + 1 ..]) };1089        }1090    }1091    return .{ .name = after_hash, .version = "" };1092}10931094// Multi-output derivations append the output name to the store path (e.g.1095// curl-8.20.0-bin, less-692-man). Strip that suffix so the version column reads1096// as just the version.1097fn stripOutputSuffix(ver: []const u8) []const u8 {1098    const suffixes = [_][]const u8{ "-bin", "-man", "-dev", "-doc", "-lib", "-info", "-out", "-static", "-devdoc" };1099    for (suffixes) |s| {1100        if (std.mem.endsWith(u8, ver, s)) return ver[0 .. ver.len - s.len];1101    }1102    return ver;1103}11041105test "pkgFromStorePath splits name and version at first dash-digit" {1106    const a = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-ripgrep-15.1.0");1107    try std.testing.expectEqualStrings("ripgrep", a.name);1108    try std.testing.expectEqualStrings("15.1.0", a.version);11091110    const b = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-helix-25.01");1111    try std.testing.expectEqualStrings("helix", b.name);1112    try std.testing.expectEqualStrings("25.01", b.version);11131114    // multi-output store paths drop their output-name suffix1115    const c = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-curl-8.20.0-bin");1116    try std.testing.expectEqualStrings("curl", c.name);1117    try std.testing.expectEqualStrings("8.20.0", c.version);1118}11191120fn firstStorePath(el: std.json.Value) ?[]const u8 {1121    if (el != .object) return null;1122    const sp = el.object.get("storePaths") orelse return null;1123    if (sp != .array or sp.array.items.len == 0) return null;1124    const first = sp.array.items[0];1125    return if (first == .string) first.string else null;1126}11271128// `nix profile list --json` has two shapes across nix versions: newer keys each1129// element by name (object), older lists them positionally (array). Handle both.1130fn renderProfileJson(gpa: std.mem.Allocator, json: []const u8) void {1131    const parsed = std.json.parseFromSlice(std.json.Value, gpa, json, .{}) catch return;1132    defer parsed.deinit();1133    if (parsed.value != .object) return;1134    const elements = parsed.value.object.get("elements") orelse return;1135    switch (elements) {1136        .object => |obj| {1137            var it = obj.iterator();1138            while (it.next()) |entry| {1139                const ver = if (firstStorePath(entry.value_ptr.*)) |p| pkgFromStorePath(p).version else "";1140                output.listPkg(entry.key_ptr.*, ver);1141            }1142        },1143        .array => |arr| {1144            for (arr.items) |el| {1145                const path = firstStorePath(el) orelse continue;1146                const row = pkgFromStorePath(path);1147                output.listPkg(row.name, row.version);1148            }1149        },1150        else => {},1151    }1152}11531154pub fn tryCmd(ctx: Ctx) !void {1155    const pkg_name_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1156    const shell_pkg = types.NixPackage{ .attr = pkg_name_arg, .pname = pkg_name_arg, .version = "", .description = "" };1157    try tryPkg(ctx, shell_pkg);1158}11591160// --- Home Manager commands ---11611162const home_help = [_][2][]const u8{1163    .{ "apply", "apply home-manager configuration" },1164    .{ "apply --dry", "preview changes without activating" },1165    .{ "back", "roll back one generation" },1166    .{ "history", "list all generations" },1167    .{ "edit", "open home.nix" },1168    .{ "check", "validate without applying" },1169    .{ "diff", "compare the latest two generations" },1170    .{ "packages", "list managed packages" },1171};11721173const HomeGen = struct {1174    number: u32,1175    date: []const u8,1176    time: []const u8,1177    path: []const u8,1178};11791180// `home-manager generations` lines read:1181//   2026-06-01 11:56 : id 765 -> /nix/store/<hash>-home-manager-generation1182// Newest first, so index 0 is the current generation.1183fn parseHomeGenerations(gpa: std.mem.Allocator, out_str: []const u8) ![]HomeGen {1184    var gens: std.ArrayList(HomeGen) = .empty;1185    var lines = std.mem.splitScalar(u8, out_str, '\n');1186    while (lines.next()) |line| {1187        const t = std.mem.trim(u8, line, " \t\r");1188        if (t.len == 0) continue;1189        var it = std.mem.tokenizeAny(u8, t, " \t");1190        const date = it.next() orelse continue;1191        const time = it.next() orelse continue;1192        var number: ?u32 = null;1193        var path: []const u8 = "";1194        while (it.next()) |tok| {1195            if (std.mem.eql(u8, tok, "id")) {1196                if (it.next()) |n| number = std.fmt.parseInt(u32, n, 10) catch null;1197            } else if (std.mem.startsWith(u8, tok, "/nix/store/")) {1198                path = tok;1199            }1200        }1201        const num = number orelse continue;1202        try gens.append(gpa, .{1203            .number = num,1204            .date = try gpa.dupe(u8, date),1205            .time = try gpa.dupe(u8, time),1206            .path = try gpa.dupe(u8, path),1207        });1208    }1209    return gens.toOwnedSlice(gpa);1210}12111212fn freeHomeGens(gpa: std.mem.Allocator, gens: []HomeGen) void {1213    for (gens) |g| {1214        gpa.free(g.date);1215        gpa.free(g.time);1216        gpa.free(g.path);1217    }1218    gpa.free(gens);1219}12201221test "parseHomeGenerations reads id, date and store path" {1222    const a = std.testing.allocator;1223    const sample =1224        \\2026-06-01 11:56 : id 765 -> /nix/store/aaaa-home-manager-generation1225        \\2026-05-31 10:29 : id 764 -> /nix/store/bbbb-home-manager-generation1226    ;1227    const gens = try parseHomeGenerations(a, sample);1228    defer freeHomeGens(a, gens);1229    try std.testing.expectEqual(@as(usize, 2), gens.len);1230    try std.testing.expectEqual(@as(u32, 765), gens[0].number);1231    try std.testing.expectEqualStrings("2026-06-01", gens[0].date);1232    try std.testing.expectEqualStrings("11:56", gens[0].time);1233    try std.testing.expectEqualStrings("/nix/store/aaaa-home-manager-generation", gens[0].path);1234    try std.testing.expectEqual(@as(u32, 764), gens[1].number);1235}12361237// Current (newest) home generation number, or 0 if unavailable.1238fn homeCurrentGen(ctx: Ctx) u32 {1239    const out = exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine) catch return 0;1240    defer ctx.gpa.free(out);1241    const gens = parseHomeGenerations(ctx.gpa, out) catch return 0;1242    defer freeHomeGens(ctx.gpa, gens);1243    return if (gens.len > 0) gens[0].number else 0;1244}12451246pub fn home(ctx: Ctx) !void {1247    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help"))1248        return output.subcommandHelp("home", &home_help, null);12491250    // Home Manager manages the local user's environment. Detection (which binary,1251    // ~/.config/home-manager, $HOME/$USER for the flake ref) all read the LOCAL1252    // host, while exec routes over SSH for a remote machine — so `home --on1253    // <remote>` would decide mode/flake-ref from the wrong box. Refuse it cleanly1254    // rather than acting on a mismatch.1255    if (!ctx.machine.local) {1256        output.homeLocalOnly(ctx.machine.name);1257        return;1258    }12591260    const mode = exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ);1261    if (mode == .none) {1262        output.homeNotInstalled();1263        return;1264    }12651266    // apply is the only command meaningful in module mode (it redirects to1267    // `nina apply`); everything else needs the standalone home-manager CLI.1268    if (std.mem.eql(u8, ctx.sub, "apply")) return homeApply(ctx, mode);1269    // edit just opens the local home.nix — fine in module mode too.1270    if (std.mem.eql(u8, ctx.sub, "edit")) return homeEdit(ctx);12711272    if (mode == .module) {1273        output.homeModuleManaged();1274        return;1275    }12761277    if (std.mem.eql(u8, ctx.sub, "back")) return homeBack(ctx);1278    if (std.mem.eql(u8, ctx.sub, "history")) return homeHistory(ctx);1279    if (std.mem.eql(u8, ctx.sub, "check")) return homeCheck(ctx);1280    if (std.mem.eql(u8, ctx.sub, "diff")) return homeDiff(ctx);1281    if (std.mem.eql(u8, ctx.sub, "packages")) return homePackages(ctx);12821283    return output.subcommandHelp("home", &home_help, null);1284}12851286fn homePackages(ctx: Ctx) !void {1287    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1288    defer ctx.gpa.free(out);1289    const gens = try parseHomeGenerations(ctx.gpa, out);1290    defer freeHomeGens(ctx.gpa, gens);12911292    output.homePackagesHeader(ctx.machine.name);1293    if (gens.len == 0 or gens[0].path.len == 0) return;12941295    // The generation's OWN references are home-manager's activation deps1296    // (bash, coreutils, ...), not what the user installed. The user's packages1297    // live one level down, in the `…-home-manager-path` env the generation1298    // references — descend into it and list ITS references. Fall back to the1299    // generation refs if that env isn't present (older home-manager layouts).1300    const gen_refs = exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, gens[0].path) catch return;1301    defer ctx.gpa.free(gen_refs);13021303    var refs = gen_refs;1304    var env_refs: ?[]u8 = null;1305    defer if (env_refs) |e| ctx.gpa.free(e);1306    if (findHomeManagerPath(gen_refs)) |pkg_path| {1307        if (exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, pkg_path)) |e| {1308            env_refs = e;1309            refs = e;1310        } else |_| {}1311    }13121313    // Dedup by name: multi-output derivations (jq, jq-lib, jq-doc) collapse to1314    // the same name after the output suffix is stripped. Keys are slices into1315    // `refs`, valid for this function's lifetime.1316    var seen = std.StringHashMap(void).init(ctx.gpa);1317    defer seen.deinit();1318    var lines = std.mem.splitScalar(u8, refs, '\n');1319    while (lines.next()) |line| {1320        const t = std.mem.trim(u8, line, " \t\r");1321        if (t.len == 0) continue;1322        const row = pkgFromStorePath(t);1323        if (row.version.len == 0) continue;1324        if (std.mem.indexOf(u8, row.name, "home-manager") != null) continue;1325        if (seen.contains(row.name)) continue;1326        seen.put(row.name, {}) catch {};1327        output.listPkg(row.name, row.version);1328    }1329}13301331// The `…-home-manager-path` env among a generation's references — the buildEnv1332// of the user's home.packages. Returns the full store-path line, or null.1333fn findHomeManagerPath(refs: []const u8) ?[]const u8 {1334    var lines = std.mem.splitScalar(u8, refs, '\n');1335    while (lines.next()) |line| {1336        const t = std.mem.trim(u8, line, " \t\r");1337        if (std.mem.indexOf(u8, t, "home-manager-path") != null) return t;1338    }1339    return null;1340}13411342test "findHomeManagerPath picks the env, not the generation or infra" {1343    const refs =1344        \\/nix/store/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-bash-5.31345        \\/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path1346        \\/nix/store/cccccccccccccccccccccccccccccccc-coreutils-9.111347    ;1348    try std.testing.expectEqualStrings(1349        "/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path",1350        findHomeManagerPath(refs).?,1351    );1352    try std.testing.expectEqual(@as(?[]const u8, null), findHomeManagerPath("/nix/store/x-bash-5.3\n"));1353}13541355fn homeDiff(ctx: Ctx) !void {1356    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1357    defer ctx.gpa.free(out);1358    const gens = try parseHomeGenerations(ctx.gpa, out);1359    defer freeHomeGens(ctx.gpa, gens);13601361    // Need two generations and both their store paths to diff their closures.1362    if (gens.len < 2 or gens[0].path.len == 0 or gens[1].path.len == 0) {1363        output.homeNothingToDiff();1364        return;1365    }1366    const newer = gens[0];1367    const older = gens[1];1368    output.homeDiffHeader(older.number, newer.number, ctx.machine.name);1369    if (try exec.diffClosuresPaths(ctx.io, &ctx.machine, ctx.gpa, older.path, newer.path) != 0)1370        return error.ProcessFailed;1371}13721373fn homeCheck(ctx: Ctx) !void {1374    output.homeCheckStart(ctx.machine.name);1375    const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa);1376    if (code != 0) return error.BuildFailed;1377    output.homeCheckOk();1378}13791380fn homeEdit(ctx: Ctx) !void {1381    // Standalone home config lives at ~/.config/home-manager/home.nix; the same1382    // path is what detection keys on for module mode, so it resolves for both.1383    const path = exec.homeNixPath(ctx.gpa, ctx.environ) orelse {1384        errors.error_info.setMessage("could not resolve ~/.config/home-manager/home.nix", .{});1385        return error.ConfigNotFound;1386    };1387    defer ctx.gpa.free(path);1388    output.homeEditOpen(path, ctx.cfg.editor);1389    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);1390}13911392fn homeHistory(ctx: Ctx) !void {1393    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1394    defer ctx.gpa.free(out);1395    const gens = try parseHomeGenerations(ctx.gpa, out);1396    defer freeHomeGens(ctx.gpa, gens);1397    output.homeHistoryHeader(ctx.machine.name);1398    // Newest-first from home-manager; the first row is the current generation.1399    for (gens, 0..) |g, i| output.homeHistoryRow(g.number, g.date, g.time, i == 0);1400}14011402fn homeBack(ctx: Ctx) !void {1403    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1404    defer ctx.gpa.free(out);1405    const gens = try parseHomeGenerations(ctx.gpa, out);1406    defer freeHomeGens(ctx.gpa, gens);14071408    // Newest-first: [0] is current, [1] is the generation to roll back to.1409    if (gens.len < 2) {1410        output.alreadyOldest();1411        return;1412    }1413    const current = gens[0].number;1414    const prev = gens[1].number;14151416    output.homeBackStart(ctx.machine.name, current, prev);1417    if (ctx.cfg.confirm and !output.confirm("")) return;1418    const code = try exec.homeManagerRollback(ctx.io, &ctx.machine, ctx.gpa);1419    if (code != 0) return error.BuildFailed;1420    output.homeBackDone(prev);1421}14221423fn homeApply(ctx: Ctx, mode: exec.HomeManagerMode) !void {1424    // NixOS/flake module: home config is rebuilt by nixos-rebuild — redirect.1425    if (mode == .module) {1426        output.homeModuleManaged();1427        return;1428    }1429    if (ctx.dry) {1430        output.homeApplyDry(ctx.machine.name);1431        const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa);1432        if (code != 0) return error.BuildFailed;1433        output.homeApplyDryDone();1434        return;1435    }14361437    if (!try runPreHook(ctx, "pre-home")) {1438        output.aborted();1439        return error.HookAborted;1440    }14411442    output.homeApplyStart(ctx.machine.name);1443    const flake_ref = exec.homeFlakeRef(ctx.gpa, ctx.io, ctx.environ);1444    defer if (flake_ref) |r| ctx.gpa.free(r);1445    if (flake_ref) |ref| {1446        output.printSubstep("home-manager switch --flake {s}", .{ref});1447    } else {1448        output.printSubstep("home-manager switch", .{});1449    }14501451    const start = std.Io.Clock.awake.now(ctx.io);1452    const code = if (flake_ref) |ref|1453        try exec.homeManagerSwitchFlake(ctx.io, &ctx.machine, ctx.gpa, ref)1454    else1455        try exec.homeManagerSwitch(ctx.io, &ctx.machine, ctx.gpa);1456    if (code != 0) return error.BuildFailed;14571458    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());1459    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));1460    output.homeApplyDone(homeCurrentGen(ctx), elapsed);1461    runPostHook(ctx, "post-home");1462}14631464// --- Service commands ---14651466const service_help = [_][2][]const u8{1467    .{ "list", "list running services" },1468    .{ "logs <svc>", "show service logs" },1469    .{ "status <svc>", "service status" },1470    .{ "start <svc>", "start a service" },1471    .{ "stop <svc>", "stop a service" },1472    .{ "restart <svc>", "restart a service" },1473    .{ "enable <svc>", "enable at boot" },1474    .{ "disable <svc>", "disable at boot" },1475};14761477pub fn service(ctx: Ctx) !void {1478    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");1479    if (std.mem.eql(u8, ctx.sub, "list")) {1480        output.serviceListHeader(ctx.machine.name);1481        const svcs = exec.serviceList(ctx.gpa, ctx.io, &ctx.machine, ctx.user) catch &.{};1482        defer ctx.gpa.free(svcs);1483        for (svcs) |s| output.serviceRow(s);1484        return;1485    }1486    if (std.mem.eql(u8, ctx.sub, "logs")) {1487        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1488        const follow = ctx.args.len > 1 and std.mem.eql(u8, ctx.args[1], "-f");1489        output.serviceLogsHeader(name, ctx.last, ctx.machine.name);1490        _ = try exec.serviceLogs(ctx.io, &ctx.machine, ctx.gpa, name, ctx.last, follow, ctx.user);1491        return;1492    }1493    if (std.mem.eql(u8, ctx.sub, "status")) {1494        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1495        output.serviceVerb("status", name, ctx.machine.name);1496        _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, "status", name, ctx.user);1497        return;1498    }1499    // start/stop/restart/enable/disable1500    const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1501    if (ctx.cfg.confirm and (std.mem.eql(u8, ctx.sub, "stop") or std.mem.eql(u8, ctx.sub, "disable"))) {1502        if (!output.confirm("")) return;1503    }1504    output.serviceVerb(ctx.sub, name, ctx.machine.name);1505    _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, ctx.sub, name, ctx.user);1506    output.serviceDone();1507}15081509// --- Flake commands ---15101511const flake_help = [_][2][]const u8{1512    .{ "init", "create a new flake.nix" },1513    .{ "update", "update flake inputs" },1514    .{ "update <in>", "update a specific input" },1515    .{ "check", "validate the flake" },1516    .{ "show", "inspect flake outputs" },1517    .{ "lock", "regenerate flake.lock" },1518    .{ "clone <url>", "clone a flake repository" },1519};15201521pub fn flake(ctx: Ctx) !void {1522    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("flake", &flake_help, null);1523    if (std.mem.eql(u8, ctx.sub, "update")) {1524        output.flakeUpdateStart();1525        const input: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1526        _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1527        output.flakeLockWritten();1528        return;1529    }1530    if (std.mem.eql(u8, ctx.sub, "check")) {1531        output.flakeCheckStart();1532        const code = try exec.flakeCheck(ctx.io, &ctx.machine, ctx.gpa);1533        if (code == 0) output.flakeValid() else output.checkFailed("");1534        return;1535    }1536    if (std.mem.eql(u8, ctx.sub, "show")) {1537        const json_out = exec.flakeShow(ctx.gpa, ctx.io, &ctx.machine) catch null;1538        if (json_out) |j| {1539            defer ctx.gpa.free(j);1540            output.flakeShowHeader("flake outputs");1541            // Parse and display the flake outputs1542            const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, j, .{}) catch return;1543            defer parsed.deinit();1544            if (parsed.value == .object) {1545                var it = parsed.value.object.iterator();1546                while (it.next()) |entry| {1547                    if (entry.value_ptr.* == .object) {1548                        var inner = entry.value_ptr.object.iterator();1549                        while (inner.next()) |e2| {1550                            const desc = if (e2.value_ptr.* == .object)1551                                if (e2.value_ptr.object.get("description")) |d|1552                                    if (d == .string) d.string else ""1553                                else1554                                    ""1555                            else1556                                "";1557                            output.flakeShowEntry(entry.key_ptr.*, e2.key_ptr.*, desc);1558                        }1559                    }1560                }1561            }1562        }1563        return;1564    }1565    if (std.mem.eql(u8, ctx.sub, "init")) {1566        _ = try exec.flakeInit(ctx.io, &ctx.machine, ctx.gpa);1567        return;1568    }1569    if (std.mem.eql(u8, ctx.sub, "lock")) {1570        _ = try exec.flakeLock(ctx.io, &ctx.machine, ctx.gpa);1571        return;1572    }1573    if (std.mem.eql(u8, ctx.sub, "clone")) {1574        const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1575        _ = try exec.flakeClone(ctx.io, &ctx.machine, ctx.gpa, url);1576        return;1577    }1578}15791580// --- Store commands ---15811582const store_help = [_][2][]const u8{1583    .{ "info", "store size and counts" },1584    .{ "path <attr>", "store path of a package" },1585    .{ "gc", "collect garbage" },1586    .{ "verify", "verify store integrity" },1587    .{ "repair", "repair corrupted paths" },1588};15891590pub fn store(ctx: Ctx) !void {1591    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("store", &store_help, null);1592    if (std.mem.eql(u8, ctx.sub, "gc")) {1593        _ = try exec.storeGc(ctx.io, &ctx.machine, ctx.gpa);1594        return;1595    }1596    if (std.mem.eql(u8, ctx.sub, "verify")) {1597        output.storeVerifyStart();1598        _ = try exec.storeVerify(ctx.io, &ctx.machine, ctx.gpa);1599        return;1600    }1601    if (std.mem.eql(u8, ctx.sub, "repair")) {1602        if (ctx.cfg.confirm and !output.confirm("")) return;1603        output.storeRepairStart();1604        _ = try exec.storeRepair(ctx.io, &ctx.machine, ctx.gpa);1605        return;1606    }1607    if (std.mem.eql(u8, ctx.sub, "info")) {1608        const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1609        output.storeInfo(si);1610        return;1611    }1612    if (std.mem.eql(u8, ctx.sub, "path")) {1613        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1614        const path = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, attr);1615        defer ctx.gpa.free(path);1616        output.storePath(path);1617        return;1618    }1619    // default: info1620    const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1621    output.storeInfo(si);1622}16231624// --- Channel commands ---16251626const channel_help = [_][2][]const u8{1627    .{ "list", "list channels" },1628    .{ "add <url> [name]", "add a channel" },1629    .{ "remove <name>", "remove a channel" },1630    .{ "update", "update all channels" },1631};16321633pub fn channel(ctx: Ctx) !void {1634    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("channel", &channel_help, null);1635    // On a flake-managed system, nix-channel operations generally don't apply.1636    if (flakeSystem(ctx)) output.flakeChannelNote();1637    if (std.mem.eql(u8, ctx.sub, "list")) {1638        output.channelListHeader(ctx.machine.name);1639        const chans = try exec.channelList(ctx.gpa, ctx.io, &ctx.machine);1640        defer ctx.gpa.free(chans);1641        for (chans) |ch| output.channelRow(ch);1642        return;1643    }1644    if (std.mem.eql(u8, ctx.sub, "add")) {1645        const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1646        const name = if (ctx.args.len > 1) ctx.args[1] else "";1647        _ = try exec.channelAdd(ctx.io, &ctx.machine, ctx.gpa, url, name);1648        output.channelDone();1649        return;1650    }1651    if (std.mem.eql(u8, ctx.sub, "remove")) {1652        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1653        _ = try exec.channelRemove(ctx.io, &ctx.machine, ctx.gpa, name);1654        output.channelDone();1655        return;1656    }1657    if (std.mem.eql(u8, ctx.sub, "update")) {1658        return channelUpdateCmd(ctx);1659    }1660}16611662// --- Profile commands ---16631664pub fn profile(ctx: Ctx) !void {1665    if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {1666        output.profileListHeader();1667        const out = exec.profileList(ctx.gpa, ctx.io, &ctx.machine) catch null;1668        if (out) |o| {1669            defer ctx.gpa.free(o);1670            var lines = std.mem.splitScalar(u8, o, '\n');1671            while (lines.next()) |line| {1672                const t = std.mem.trim(u8, line, " \t\r");1673                if (t.len == 0) continue;1674                output.profileRow(t, "", "");1675            }1676        }1677        return;1678    }1679    if (std.mem.eql(u8, ctx.sub, "install")) {1680        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1681        _ = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, attr);1682        output.done();1683        return;1684    }1685    if (std.mem.eql(u8, ctx.sub, "remove")) {1686        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1687        _ = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, attr);1688        output.done();1689        return;1690    }1691    if (std.mem.eql(u8, ctx.sub, "upgrade")) {1692        _ = try exec.profileUpgrade(ctx.io, &ctx.machine, ctx.gpa);1693        output.done();1694        return;1695    }1696}16971698// --- Pkg commands ---16991700const pkg_help = [_][2][]const u8{1701    .{ "why <pkg>", "what pulled it in" },1702    .{ "deps <pkg>", "direct dependencies" },1703    .{ "size <pkg>", "closure size" },1704    .{ "path <pkg>", "store path" },1705    .{ "closure <pkg>", "full closure" },1706};17071708pub fn pkg(ctx: Ctx) !void {1709    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("pkg", &pkg_help, null);1710    const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1711    if (std.mem.eql(u8, ctx.sub, "why")) {1712        if (try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1713        return;1714    }1715    if (std.mem.eql(u8, ctx.sub, "deps")) {1716        if (try exec.pkgDeps(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1717        return;1718    }1719    if (std.mem.eql(u8, ctx.sub, "size")) {1720        const s = try exec.pkgSize(ctx.gpa, ctx.io, &ctx.machine, name);1721        defer ctx.gpa.free(s);1722        output.pkgResult("size", s);1723        return;1724    }1725    if (std.mem.eql(u8, ctx.sub, "path")) {1726        const p = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, name);1727        defer ctx.gpa.free(p);1728        output.pkgResult("path", p);1729        return;1730    }1731    if (std.mem.eql(u8, ctx.sub, "closure")) {1732        if (try exec.pkgClosure(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1733        return;1734    }1735}17361737// Top-level alias for `nina pkg why <pkg>` — surfaces what pulled a package in1738// without the user needing to know about the `pkg` subgroup.1739pub fn why(ctx: Ctx) !void {1740    const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1741    if (try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1742}17431744// --- Pin / Unpin ---17451746pub fn pin(ctx: Ctx) !void {1747    const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1748    const commit = if (ctx.args.len > 1) ctx.args[1] else return error.Internal;1749    exec.editFlakeLock(ctx.gpa, input, commit) catch return error.ProcessFailed;1750    output.pinDone(input, commit);1751}17521753pub fn unpin(ctx: Ctx) !void {1754    const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1755    _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1756    output.unpinDone(input);1757}17581759// --- Hash / Fetch ---17601761pub fn hash(ctx: Ctx) !void {1762    const path = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1763    const h = try exec.nixHash(ctx.gpa, ctx.io, &ctx.machine, path);1764    defer ctx.gpa.free(h);1765    output.hashResult(std.mem.trim(u8, h, " \t\n\r"));1766}17671768pub fn fetch(ctx: Ctx) !void {1769    const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1770    const h = try exec.nixFetch(ctx.gpa, ctx.io, &ctx.machine, url);1771    defer ctx.gpa.free(h);1772    output.fetchResult(std.mem.trim(u8, h, " \t\n\r"), url);1773}17741775// --- Build / Run ---17761777pub fn build(ctx: Ctx) !void {1778    const attr: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1779    output.buildStart(attr orelse "default");1780    const code = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, attr);1781    if (code != 0) return error.BuildFailed;1782    output.buildDone();1783}17841785pub fn runCmd(ctx: Ctx) !void {1786    const pkg_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1787    output.runStart(pkg_arg);1788    _ = try exec.nixRun(ctx.io, &ctx.machine, ctx.gpa, pkg_arg);1789}17901791// --- Hello ---17921793pub fn hello(ctx: Ctx) !void {1794    output.hello(ctx.cfg.machines);1795}17961797const ConfigKind = enum { flake, channel, none };17981799// Scan the conventional /etc/nixos for a flake.nix (flake-based) or a1800// configuration.nix (channel-based) to pre-fill the wizard's defaults.1801fn scanConfig(io: std.Io) ConfigKind {1802    if (exec.pathExists(io, "/etc/nixos/flake.nix")) return .flake;1803    if (exec.pathExists(io, "/etc/nixos/configuration.nix")) return .channel;1804    return .none;1805}18061807// Runs when the config is absent on first invocation (interactive TTY only).1808// Scans for an existing nixos config, detects flake vs channel, and offers a1809// smart default path — flake-ness is detected, never asked.1810pub fn firstRunWizard(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1811    output.firstRunBanner();1812    output.firstRunNoConfig();18131814    var name_buf: [256]u8 = undefined;1815    var path_buf: [256]u8 = undefined;18161817    const machine_name = output.firstRunPrompt("machine name", "my-machine", &name_buf);18181819    output.firstRunScanning();1820    const kind = scanConfig(io);1821    switch (kind) {1822        .flake => output.firstRunDetected("/etc/nixos/flake.nix", true),1823        .channel => output.firstRunDetected("/etc/nixos/configuration.nix", false),1824        .none => output.firstRunNoneFound(),1825    }18261827    // Detected systems default to /etc/nixos (press enter to confirm); when1828    // nothing was found, leave the default empty so the user must type a path.1829    const default_path: []const u8 = if (kind == .none) "" else "/etc/nixos";1830    const config_path = output.firstRunPromptDefault("config path", default_path, kind != .none, &path_buf);18311832    // Re-detect at the chosen path in case the user pointed elsewhere — flake.nix1833    // there means a flake system, recorded so channel commands warn appropriately.1834    const use_flakes = exec.dirHasFlake(gpa, io, config_path);18351836    const conf_path = try config.configPath(gpa, environ);1837    defer gpa.free(conf_path);1838    if (std.fs.path.dirname(conf_path)) |dir| exec.ensureDir(gpa, io, dir);18391840    // `flake` is a top-level config field, so it must precede the [machine] block.1841    const flake_line = if (use_flakes) "flake = true\n" else "";1842    var content_buf: [1024]u8 = undefined;1843    const content = try std.fmt.bufPrint(1844        &content_buf,1845        "{s}[machine]\nname = {s}\nconfig = {s}\nlocal = true\n",1846        .{ flake_line, machine_name, config_path },1847    );18481849    const file = std.Io.Dir.createFile(.cwd(), io, conf_path, .{}) catch {1850        errors.error_info.setMessage("could not write {s}", .{conf_path});1851        return error.Internal;1852    };1853    defer file.close(io);1854    file.writePositionalAll(io, content, 0) catch {1855        errors.error_info.setMessage("could not write {s}", .{conf_path});1856        return error.Internal;1857    };18581859    output.firstRunWritten(conf_path);1860}18611862pub fn setup(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1863    // Create the config first if it doesn't exist. This makes `nina setup`1864    // a complete onboarding command — not just a nix-features check. Any legacy1865    // ~/.nina.conf is migrated to the XDG path before we decide to run the wizard.1866    config.migrateLegacyConfig(gpa, io, environ);1867    if (config.configPath(gpa, environ)) |conf_path| {1868        defer gpa.free(conf_path);1869        if (std.Io.Dir.openFile(.cwd(), io, conf_path, .{})) |f| {1870            f.close(io);1871        } else |_| {1872            try firstRunWizard(gpa, io, environ);1873            errors.error_info.reset();1874        }1875    } else |_| {}18761877    output.setupCheck();1878    const status = exec.checkNixFeatures(gpa, io, environ);1879    output.setupFeatures(status.nix_command, status.flakes);18801881    if (status.allEnabled()) {1882        output.setupAllSet();1883        api.ensureRegistryPinned(gpa, io, environ);1884        return;1885    }18861887    // On NixOS the features belong in configuration.nix (the declarative,1888    // permanent home), not ~/.config/nix/nix.conf. Offer to add the one line;1889    // the user runs the rebuild. We don't pin the registry here because the1890    // features aren't live until that rebuild lands.1891    if (exec.isNixOS(io)) {1892        const conf_path = "/etc/nixos/configuration.nix";1893        if (exec.nixosConfigEnablesFeatures(gpa, io, conf_path)) {1894            output.setupNixosNeedsRebuild(conf_path);1895            return;1896        }1897        output.setupNixosOffer(exec.NIXOS_FEATURES_LINE, conf_path);1898        if (output.confirmDefaultNo("add it now?")) {1899            if (exec.appendFeaturesToNixosConfig(gpa, io, environ, conf_path)) |_| {1900                output.setupNixosWrote(conf_path);1901            } else |_| {1902                output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);1903            }1904        } else {1905            output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);1906        }1907        return;1908    }19091910    // Non-NixOS: a user-level nix.conf takes effect immediately, no sudo needed.1911    output.setupEnabling();1912    const path = try exec.enableNixFeatures(gpa, io, environ);1913    defer gpa.free(path);19141915    output.setupDone(path);1916    api.ensureRegistryPinned(gpa, io, environ);1917}19181919// --- Log helper ---19201921fn logAction(ctx: Ctx, action: []const u8, gen: u32) void {1922    var ts_buf: [32]u8 = undefined;1923    const ts = nowIso(ctx.io, &ts_buf);1924    var buf: [256]u8 = undefined;1925    const entry = std.fmt.bufPrint(&buf, "{{\"ts\":\"{s}\",\"machine\":\"{s}\",\"command\":\"{s}\",\"outcome\":\"success\",\"gen_before\":null,\"gen_after\":{d},\"duration_ms\":0}}\n", .{1926        ts, ctx.machine.name, action, gen,1927    }) catch return;1928    exec.appendNinaLog(ctx.io, ctx.environ, entry);1929}19301931// Wall-clock UTC as ISO-8601. Uses Io.Clock.real (the settable Unix-epoch clock);1932// Io.Clock.awake is monotonic and unsuitable for timestamps. Falls back to epoch 0.1933fn nowIso(io: std.Io, buf: []u8) []const u8 {1934    const fallback = "1970-01-01T00:00:00Z";1935    const ns = std.Io.Clock.real.now(io).toNanoseconds();1936    if (ns <= 0) return fallback;1937    const secs: u64 = @intCast(@divFloor(ns, 1_000_000_000));1938    const es = std.time.epoch.EpochSeconds{ .secs = secs };1939    const ed = es.getEpochDay();1940    const yd = ed.calculateYearDay();1941    const md = yd.calculateMonthDay();1942    const ds = es.getDaySeconds();1943    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", .{1944        yd.year,              md.month.numeric(),      @as(u32, md.day_index) + 1,1945        ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(),1946    }) catch return fallback;1947}