commands.zig

80.1 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=100", .{ origin, repo });557}558559// Saves arrive newest-first. For each version in the update range we want the OLDEST560// save message (the one that introduced that version), not a follow-up cleanup/docs save.561// We overwrite the tracked message on each occurrence, so the final stored value per562// version is always the oldest (last-seen in a newest-first stream).563fn releaseNotesFromArchiveJson(gpa: std.mem.Allocator, body: []const u8, current: []const u8, latest: []const u8) ![]u8 {564    const parsed = std.json.parseFromSlice(std.json.Value, gpa, body, .{}) catch return gpa.dupe(u8, "");565    defer parsed.deinit();566567    if (parsed.value != .object) return gpa.dupe(u8, "");568    const saves_v = parsed.value.object.get("saves") orelse return gpa.dupe(u8, "");569    if (saves_v != .array) return gpa.dupe(u8, "");570571    // version string → oldest message seen (both slice into parsed JSON, valid until deinit)572    var best_msg = std.StringHashMap([]const u8).init(gpa);573    defer best_msg.deinit();574    var order: std.ArrayList([]const u8) = .empty;575    defer order.deinit(gpa);576577    for (saves_v.array.items) |save| {578        if (save != .object) continue;579        const ver_v = save.object.get("version") orelse continue;580        const msg_v = save.object.get("message") orelse continue;581        if (ver_v != .string or msg_v != .string) continue;582        const ver = ver_v.string;583        const msg = std.mem.trim(u8, msg_v.string, " \t\r\n");584        if (msg.len == 0 or !versionInUpdateRange(ver, current, latest)) continue;585586        const entry = try best_msg.getOrPut(ver);587        if (!entry.found_existing) try order.append(gpa, ver);588        // Always overwrite: saves are newest-first, so last write = oldest save = version-intro message589        entry.value_ptr.* = msg;590    }591592    if (order.items.len == 0) return gpa.dupe(u8, "");593594    var out: std.ArrayList(u8) = .empty;595    errdefer out.deinit(gpa);596    for (order.items) |ver| {597        const msg = best_msg.get(ver).?;598        // Use only the first line as the summary; multi-line saves may have implementation details below599        const summary_end = std.mem.indexOf(u8, msg, "\n") orelse msg.len;600        const summary = std.mem.trim(u8, msg[0..summary_end], " \t\r");601        if (summary.len == 0) continue;602        try appendLine(&out, gpa, "## {s}\n", .{ver});603        try appendLine(&out, gpa, "- {s}\n\n", .{summary});604    }605606    if (out.items.len == 0) {607        out.deinit(gpa);608        return gpa.dupe(u8, "");609    }610    return out.toOwnedSlice(gpa);611}612613fn appendLine(out: *std.ArrayList(u8), gpa: std.mem.Allocator, comptime template: []const u8, args: anytype) !void {614    const line = try std.fmt.allocPrint(gpa, template, args);615    defer gpa.free(line);616    try out.appendSlice(gpa, line);617}618619fn versionInUpdateRange(candidate: []const u8, current: []const u8, latest: []const u8) bool {620    const cand = parseSemver(candidate) orelse return std.mem.eql(u8, candidate, latest);621    const cur = parseSemver(current) orelse return std.mem.eql(u8, candidate, latest);622    const lat = parseSemver(latest) orelse return std.mem.eql(u8, candidate, latest);623    return compareSemver(cand, cur) == .gt and compareSemver(cand, lat) != .gt;624}625626fn remoteVersionNewer(current: []const u8, remote: []const u8) bool {627    const cur = parseSemver(current) orelse return !std.mem.eql(u8, current, remote);628    const rem = parseSemver(remote) orelse return !std.mem.eql(u8, current, remote);629    return compareSemver(rem, cur) == .gt;630}631632const VersionOrder = enum { lt, eq, gt };633634fn compareSemver(a: Semver, b: Semver) VersionOrder {635    if (a.major != b.major) return if (a.major < b.major) .lt else .gt;636    if (a.minor != b.minor) return if (a.minor < b.minor) .lt else .gt;637    if (a.patch != b.patch) return if (a.patch < b.patch) .lt else .gt;638    return .eq;639}640641fn parseSemver(raw: []const u8) ?Semver {642    const v = if (std.mem.startsWith(u8, raw, "v")) raw[1..] else raw;643    var it = std.mem.splitScalar(u8, v, '.');644    const major_s = it.next() orelse return null;645    const minor_s = it.next() orelse return null;646    const patch_s = it.next() orelse return null;647    if (it.next() != null) return null;648    return .{649        .major = std.fmt.parseInt(u32, major_s, 10) catch return null,650        .minor = std.fmt.parseInt(u32, minor_s, 10) catch return null,651        .patch = std.fmt.parseInt(u32, patch_s, 10) catch return null,652    };653}654655test "versionInUpdateRange includes only newer versions through latest" {656    try std.testing.expect(versionInUpdateRange("3.2.3", "3.1.9", "3.2.3"));657    try std.testing.expect(versionInUpdateRange("3.2.0", "3.1.9", "3.2.3"));658    try std.testing.expect(!versionInUpdateRange("3.1.9", "3.1.9", "3.2.3"));659    try std.testing.expect(!versionInUpdateRange("3.2.4", "3.1.9", "3.2.3"));660}661662test "remoteVersionNewer does not offer downgrades" {663    try std.testing.expect(remoteVersionNewer("3.2.3", "3.2.4"));664    try std.testing.expect(!remoteVersionNewer("3.2.4", "3.2.3"));665    try std.testing.expect(!remoteVersionNewer("3.2.4", "3.2.4"));666}667668test "releaseNotesFromArchiveJson uses oldest save per version" {669    // Saves arrive newest-first. For 3.2.3, the newest save is a CONTINUITY update;670    // the oldest is the version-intro message. We expect the intro message in the output.671    const body =672        \\{673        \\  "saves": [674        \\    {"version":"3.2.3","message":"wip: record verification in CONTINUITY"},675        \\    {"version":"3.2.1","message":"old release"},676        \\    {"version":"3.2.3","message":"add streaming deflate path"}677        \\  ]678        \\}679    ;680    const notes = try releaseNotesFromArchiveJson(std.testing.allocator, body, "3.2.1", "3.2.3");681    defer std.testing.allocator.free(notes);682683    try std.testing.expect(std.mem.indexOf(u8, notes, "## 3.2.3") != null);684    try std.testing.expect(std.mem.indexOf(u8, notes, "- add streaming deflate path") != null);685    try std.testing.expect(std.mem.indexOf(u8, notes, "CONTINUITY") == null);686    try std.testing.expect(std.mem.indexOf(u8, notes, "old release") == null);687}688689// nina goodbye — clean uninstall. Three install paths:690// - nix profile (binary in nix store with a profile element) → nix profile remove691// - koh build or source build (plain binary on PATH) → delete the file692pub fn goodbye(ctx: Ctx) !void {693    output.goodbyeStart();694695    var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;696    const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {697        errors.error_info.setMessage("could not determine install path", .{});698        return error.Internal;699    };700701    // A binary outside the nix store is a koh build or source build — delete it.702    if (!std.mem.startsWith(u8, install_path, "/nix/store/")) {703        output.goodbyeFile(install_path);704        if (ctx.cfg.confirm and !output.confirm("")) return;705        std.Io.Dir.deleteFileAbsolute(ctx.io, install_path) catch |e| {706            errors.error_info.setMessage("could not remove {s}", .{install_path});707            return e;708        };709        output.goodbyeDone();710        return;711    }712713    // Binary is in the nix store — find and remove the profile element.714    const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);715    defer {716        if (nina_element) |n| ctx.gpa.free(n);717    }718719    if (nina_element == null) {720        errors.error_info.setMessage("nina not found in nix profile — was it installed via 'nix profile add'?", .{});721        return error.Internal;722    }723724    output.goodbyeNix();725    if (ctx.cfg.confirm and !output.confirm("")) return;726    const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "remove", nina_element.? }) catch {727        output.goodbyeFailed("nix profile remove failed");728        return;729    };730    if (ec != 0) {731        output.goodbyeFailed("nix profile remove failed");732        return;733    }734    output.goodbyeDone();735}736737fn channelUpdateCmd(ctx: Ctx) !void {738    output.updateStart(ctx.machine.name);739    _ = try exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa);740    output.updateDone();741}742743pub fn upgrade(ctx: Ctx) !void {744    if (!try runPreHook(ctx, "pre-upgrade")) {745        output.aborted();746        return error.HookAborted;747    }748749    output.upgradeStart(ctx.machine.name);750    // Flake systems update inputs (flake.lock); channel systems update channels.751    // Running nix-channel --update on a flake system is a no-op at best. The752    // rebuild below is already flake-aware via exec.nixosRebuildSwitch.753    if (flakeSystem(ctx)) {754        output.printSubstep("updating flake inputs", .{});755        _ = exec.flakeUpdateAt(ctx.io, &ctx.machine, ctx.gpa, ctx.machine.config_path) catch {};756    } else {757        output.printSubstep("updating channels", .{});758        _ = exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa) catch {};759    }760    output.printSubstep("rebuilding", .{});761    output.buildPanelInit();762    const start = std.Io.Clock.awake.now(ctx.io);763    var panel = output.BuildPanel{};764    const code = exec.nixosRebuildSwitchWithPanel(ctx.io, &ctx.machine, ctx.gpa, &panel) catch |e| {765        output.buildPanelClear();766        return e;767    };768    output.buildPanelClear();769    if (code != 0) {770        output.applyFailed("");771        return error.BuildFailed;772    }773    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());774    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));775    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;776    output.applyDone(gen, elapsed, false);777    runPostHook(ctx, "post-upgrade");778}779780pub fn log(ctx: Ctx) !void {781    output.logHeader(ctx.machine.name);782    const content = exec.readNinaLog(ctx.gpa, ctx.io, ctx.environ, ctx.last) catch {783        // No log yet — that's fine784        return;785    };786    defer ctx.gpa.free(content);787    var lines = std.mem.splitScalar(u8, content, '\n');788    while (lines.next()) |line| {789        const t = std.mem.trim(u8, line, " \t\r");790        if (t.len == 0) continue;791        if (t[0] == '{') {792            renderJsonLogLine(ctx.gpa, t);793        } else {794            // legacy tab-separated format795            var parts = std.mem.tokenizeScalar(u8, t, '\t');796            const date = parts.next() orelse continue;797            const time = parts.next() orelse "";798            const action = parts.next() orelse "";799            const detail = parts.next() orelse "";800            output.logRow(date, time, action, detail);801        }802    }803}804805// The on-disk log is JSON Lines: {"ts","machine","command","outcome","gen_after",...}.806// Render ts -> date/time columns, command -> action, outcome(+gen) -> detail.807fn renderJsonLogLine(gpa: std.mem.Allocator, line: []const u8) void {808    const parsed = std.json.parseFromSlice(std.json.Value, gpa, line, .{}) catch {809        output.logRow(line, "", "", ""); // unparseable — show raw rather than drop810        return;811    };812    defer parsed.deinit();813    if (parsed.value != .object) return;814    const o = parsed.value.object;815816    const ts = jsonStr(o, "ts");817    const date = if (ts.len >= 10) ts[0..10] else ts;818    const time = if (ts.len >= 16) ts[11..16] else "";819    const action = jsonStr(o, "command");820    const outcome = jsonStr(o, "outcome");821822    var buf: [160]u8 = undefined;823    var detail: []const u8 = outcome;824    if (o.get("gen_after")) |g| {825        if (g == .integer) {826            detail = std.fmt.bufPrint(&buf, "{s}   -> gen {d}", .{ outcome, g.integer }) catch outcome;827        }828    }829    output.logRow(date, time, action, detail);830}831832fn jsonStr(o: std.json.ObjectMap, key: []const u8) []const u8 {833    if (o.get(key)) |v| {834        if (v == .string) return v.string;835    }836    return "";837}838839pub fn edit(ctx: Ctx) !void {840    // `edit` is multi-word, so a bare positional ("hardware") arrives as ctx.sub.841    // hardware-configuration.nix is generated by nixos-generate-config and warns842    // against hand-editing — refuse rather than silently opening the wrong file.843    if (std.mem.eql(u8, ctx.sub, "hardware")) {844        output.editHardwareWarning();845        return;846    }847848    // --dir opens the whole config directory (for editors that work better with849    // a folder open), as root so root-owned config trees like /etc/nixos work.850    var open_dir = false;851    for (ctx.args) |arg| {852        if (std.mem.eql(u8, arg, "--dir")) open_dir = true;853    }854    if (open_dir) {855        output.editOpen(ctx.machine.config_path, ctx.cfg.editor);856        _ = try exec.openEditorSudo(ctx.io, ctx.gpa, ctx.cfg.editor, ctx.machine.config_path);857        return;858    }859860    const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});861    defer ctx.gpa.free(path);862    output.editOpen(path, ctx.cfg.editor);863    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);864}865866pub fn fmt(ctx: Ctx) !void {867    const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});868    defer ctx.gpa.free(path);869    if (ctx.check) {870        const code = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, true);871        if (code != 0) output.fmtNeedsFormat() else output.fmtDone();872        return;873    }874    output.fmtStart(path);875    _ = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, false);876    output.fmtDone();877}878879pub fn repl(ctx: Ctx) !void {880    output.replStart();881    _ = try exec.nixRepl(ctx.io, &ctx.machine, ctx.gpa);882}883884pub fn develop(ctx: Ctx) !void {885    if (std.mem.eql(u8, ctx.sub, "show")) {886        _ = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, null);887        return;888    }889    const run_cmd: ?[]const u8 = if (ctx.args.len > 0 and std.mem.eql(u8, ctx.sub, "run"))890        ctx.args[0]891    else892        null;893    output.developStart(&.{});894    _ = try exec.nixDevelopPs1(ctx.io, &ctx.machine, ctx.gpa, run_cmd, ctx.environ);895    output.developDone();896}897898pub fn info(ctx: Ctx) !void {899    output.infoHeader(ctx.machine.name);900    const nixos_ver = exec.systemInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");901    defer ctx.gpa.free(nixos_ver);902    output.infoRow("nixos", std.mem.trim(u8, nixos_ver, " \t\n\r"));903904    const kernel = exec.kernelInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");905    defer ctx.gpa.free(kernel);906    output.infoRow("kernel", std.mem.trim(u8, kernel, " \t\n\r"));907908    const uptime = exec.uptimeInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");909    defer ctx.gpa.free(uptime);910    output.infoRow("uptime", std.mem.trim(u8, uptime, " \t\n\r"));911}912913pub fn boot(ctx: Ctx) !void {914    output.bootHeader(ctx.machine.name);915    const entries = exec.bootEntries(ctx.gpa, ctx.io, &ctx.machine) catch &.{};916    defer ctx.gpa.free(entries);917    for (entries, 0..) |entry, i| output.bootEntry(entry, i);918}919920pub fn searchCmd(ctx: Ctx) !void {921    const query = if (ctx.args.len > 0) ctx.args[0] else "";922    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);923    const selected = try search_tui.run(ctx.gpa, ctx.io, query, .packages);924    if (selected) |npkg| try selectAndInstall(ctx, npkg);925}926927pub fn optionCmd(ctx: Ctx) !void {928    const query = if (ctx.args.len > 0) ctx.args[0] else "";929    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);930    _ = try search_tui.run(ctx.gpa, ctx.io, query, .options);931}932933pub fn install(ctx: Ctx) !void {934    const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;935936    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);937938    // Search for the package to get the attr939    const pkgs = api.searchPackages(ctx.gpa, ctx.io, pkg_name) catch {940        errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});941        errors.error_info.setSuggestion("nina search {s}", .{pkg_name});942        return error.PackageNotFound;943    };944945    if (pkgs.len == 0) {946        // No matches — likely a typo. Suggest the closest real package and offer it.947        if (closestPackage(ctx, pkg_name)) |sugg| {948            output.didYouMean(pkg_name, sugg.pname);949            if (output.confirm("")) try selectAndInstall(ctx, sugg);950            return;951        }952        errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});953        errors.error_info.setSuggestion("nina search {s}", .{pkg_name});954        return error.PackageNotFound;955    }956957    // Prefer an exact name match over the first search result — `install ripgrep`958    // must pick "ripgrep", not the alphabetically-first match like "repgrep".959    var found = pkgs[0];960    for (pkgs) |p| {961        if (std.mem.eql(u8, p.pname, pkg_name)) {962            found = p;963            break;964        }965    }966    try selectAndInstall(ctx, found);967}968969// Find the real package whose name is closest to a not-found query (typo help).970// Typos usually keep the leading characters, so gather candidates with a prefix971// search and rank by edit distance; return the best only if it's typo-close.972fn closestPackage(ctx: Ctx, query: []const u8) ?types.NixPackage {973    if (query.len < 2) return null;974    var candidates = api.searchPackages(ctx.gpa, ctx.io, query[0..@min(query.len, 4)]) catch &.{};975    if (candidates.len == 0 and query.len > 2) {976        candidates = api.searchPackages(ctx.gpa, ctx.io, query[0..2]) catch &.{};977    }978    if (candidates.len == 0) return null;979980    var best: ?types.NixPackage = null;981    var best_dist: usize = std.math.maxInt(usize);982    for (candidates) |p| {983        const d = editDistance(query, p.pname);984        if (d > 0 and d < best_dist) {985            best_dist = d;986            best = p;987        }988    }989    // Only suggest a genuinely close name, scaled to query length.990    const threshold = @max(@as(usize, 2), query.len / 3);991    return if (best_dist <= threshold) best else null;992}993994// Case-insensitive Levenshtein distance. Names longer than the row buffer are995// treated as far away (never suggested).996fn editDistance(a: []const u8, b: []const u8) usize {997    const n = b.len;998    if (a.len == 0) return n;999    if (n == 0) return a.len;1000    if (n + 1 > 128) return std.math.maxInt(usize);1001    var prev: [128]usize = undefined;1002    var curr: [128]usize = undefined;1003    var j: usize = 0;1004    while (j <= n) : (j += 1) prev[j] = j;1005    var i: usize = 1;1006    while (i <= a.len) : (i += 1) {1007        curr[0] = i;1008        j = 1;1009        while (j <= n) : (j += 1) {1010            const cost: usize = if (std.ascii.toLower(a[i - 1]) == std.ascii.toLower(b[j - 1])) 0 else 1;1011            curr[j] = @min(prev[j] + 1, @min(curr[j - 1] + 1, prev[j - 1] + cost));1012        }1013        @memcpy(prev[0 .. n + 1], curr[0 .. n + 1]);1014    }1015    return prev[n];1016}10171018test "editDistance is case-insensitive Levenshtein" {1019    try std.testing.expectEqual(@as(usize, 1), editDistance("firefux", "firefox"));1020    try std.testing.expectEqual(@as(usize, 0), editDistance("git", "GIT"));1021    try std.testing.expectEqual(@as(usize, 2), editDistance("fierfox", "firefox"));1022    try std.testing.expectEqual(@as(usize, 7), editDistance("", "firefox"));1023}10241025// Prompt for the install method (profile / system / try) and dispatch. Shared by1026// `nina install <pkg>` and the search widget's Enter-to-select — the letter keys1027// are read here, after the search widget's raw mode is gone, so they don't1028// collide with typing a query.1029fn selectAndInstall(ctx: Ctx, npkg: types.NixPackage) !void {1030    output.installSelectPrompt(npkg.pname, npkg.version);10311032    var choice_buf: [8]u8 = undefined;1033    var choice_len: usize = 0;1034    while (choice_len < choice_buf.len) {1035        const n = std.posix.read(std.posix.STDIN_FILENO, choice_buf[choice_len .. choice_len + 1]) catch break;1036        if (n == 0) break;1037        if (choice_buf[choice_len] == '\n') break;1038        choice_len += 1;1039    }1040    const choice = std.mem.trim(u8, choice_buf[0..choice_len], " \t");10411042    if (choice.len == 0 or choice[0] == 'i' or choice[0] == 'I') {1043        try profileInstallPkg(ctx, npkg);1044    } else if (choice[0] == 's' or choice[0] == 'S') {1045        try systemInstallPkg(ctx, npkg);1046    } else if (choice[0] == 't' or choice[0] == 'T') {1047        try tryPkg(ctx, npkg);1048    }1049}10501051fn profileInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {1052    output.installStart(npkg.pname, .profile);1053    output.printSubstep("nix profile add nixpkgs#{s}", .{npkg.attr});1054    output.printTeach(try std.fmt.allocPrint(ctx.gpa, "nix profile add nixpkgs#{s}", .{npkg.attr}));1055    const code = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, npkg.attr);1056    if (code != 0) return error.ProcessFailed;1057    output.installDone(npkg.pname);1058}10591060fn systemInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {1061    const config_path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});1062    defer ctx.gpa.free(config_path);1063    const line = api.findSystemPackagesLine(ctx.io, config_path) orelse 1;1064    output.installEditorPrompt(npkg.pname, config_path, line, ctx.cfg.editor);1065    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, config_path, line);1066    if (ctx.cfg.confirm) {1067        if (output.confirm("apply now? ")) {1068            try apply(ctx);1069        }1070    }1071}10721073fn tryPkg(ctx: Ctx, npkg: types.NixPackage) !void {1074    output.tryStart(npkg.pname);1075    output.printSubstep("nix shell nixpkgs#{s}", .{npkg.attr});1076    output.tryExitHint();1077    _ = try exec.nixShellPs1(ctx.io, &ctx.machine, ctx.gpa, npkg.attr, ctx.environ);1078    output.tryDone();1079}10801081pub fn remove(ctx: Ctx) !void {1082    const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1083    output.removeStart(pkg_name);1084    const code = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, pkg_name);1085    if (code != 0) return error.ProcessFailed;1086    output.done();1087}10881089pub fn list(ctx: Ctx) !void {1090    output.listHeader(ctx.machine.name);10911092    // Profile packages: parse `nix profile list --json` into clean name+version1093    // rows instead of dumping nix's verbose multi-line "Name:/Flake attribute:"1094    // blocks.1095    if (exec.profileListJson(ctx.gpa, ctx.io, &ctx.machine) catch null) |json| {1096        defer ctx.gpa.free(json);1097        output.listSection("profile");1098        renderProfileJson(ctx.gpa, json);1099    }11001101    // System packages: the references of /run/current-system/sw, each a1102    // <hash>-<name>-<version> store path.1103    if (exec.systemPackagePaths(ctx.gpa, ctx.io, &ctx.machine) catch null) |paths| {1104        defer ctx.gpa.free(paths);1105        output.blankLine();1106        output.listSection("system");1107        var lines = std.mem.splitScalar(u8, paths, '\n');1108        while (lines.next()) |line| {1109            const t = std.mem.trim(u8, line, " \t\r");1110            if (t.len == 0) continue;1111            const row = pkgFromStorePath(t);1112            // Skip support paths with no parseable version (man pages, wrappers).1113            if (row.version.len == 0) continue;1114            output.listPkg(row.name, row.version);1115        }1116    }1117}11181119const PkgRow = struct { name: []const u8, version: []const u8 };11201121// Split a nix store path basename (<hash>-<name>-<version>) into name + version.1122// Version begins at the first '-' followed by a digit, which reliably lands on1123// the name/version boundary since the 32-char hash and package names start with1124// non-digits.1125fn pkgFromStorePath(path: []const u8) PkgRow {1126    const base = std.fs.path.basename(path);1127    const after_hash = if (base.len > 33 and base[32] == '-') base[33..] else base;1128    var i: usize = 0;1129    while (i + 1 < after_hash.len) : (i += 1) {1130        if (after_hash[i] == '-' and std.ascii.isDigit(after_hash[i + 1])) {1131            return .{ .name = after_hash[0..i], .version = stripOutputSuffix(after_hash[i + 1 ..]) };1132        }1133    }1134    return .{ .name = after_hash, .version = "" };1135}11361137// Multi-output derivations append the output name to the store path (e.g.1138// curl-8.20.0-bin, less-692-man). Strip that suffix so the version column reads1139// as just the version.1140fn stripOutputSuffix(ver: []const u8) []const u8 {1141    const suffixes = [_][]const u8{ "-bin", "-man", "-dev", "-doc", "-lib", "-info", "-out", "-static", "-devdoc" };1142    for (suffixes) |s| {1143        if (std.mem.endsWith(u8, ver, s)) return ver[0 .. ver.len - s.len];1144    }1145    return ver;1146}11471148test "pkgFromStorePath splits name and version at first dash-digit" {1149    const a = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-ripgrep-15.1.0");1150    try std.testing.expectEqualStrings("ripgrep", a.name);1151    try std.testing.expectEqualStrings("15.1.0", a.version);11521153    const b = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-helix-25.01");1154    try std.testing.expectEqualStrings("helix", b.name);1155    try std.testing.expectEqualStrings("25.01", b.version);11561157    // multi-output store paths drop their output-name suffix1158    const c = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-curl-8.20.0-bin");1159    try std.testing.expectEqualStrings("curl", c.name);1160    try std.testing.expectEqualStrings("8.20.0", c.version);1161}11621163fn firstStorePath(el: std.json.Value) ?[]const u8 {1164    if (el != .object) return null;1165    const sp = el.object.get("storePaths") orelse return null;1166    if (sp != .array or sp.array.items.len == 0) return null;1167    const first = sp.array.items[0];1168    return if (first == .string) first.string else null;1169}11701171// `nix profile list --json` has two shapes across nix versions: newer keys each1172// element by name (object), older lists them positionally (array). Handle both.1173fn renderProfileJson(gpa: std.mem.Allocator, json: []const u8) void {1174    const parsed = std.json.parseFromSlice(std.json.Value, gpa, json, .{}) catch return;1175    defer parsed.deinit();1176    if (parsed.value != .object) return;1177    const elements = parsed.value.object.get("elements") orelse return;1178    switch (elements) {1179        .object => |obj| {1180            var it = obj.iterator();1181            while (it.next()) |entry| {1182                const ver = if (firstStorePath(entry.value_ptr.*)) |p| pkgFromStorePath(p).version else "";1183                output.listPkg(entry.key_ptr.*, ver);1184            }1185        },1186        .array => |arr| {1187            for (arr.items) |el| {1188                const path = firstStorePath(el) orelse continue;1189                const row = pkgFromStorePath(path);1190                output.listPkg(row.name, row.version);1191            }1192        },1193        else => {},1194    }1195}11961197pub fn tryCmd(ctx: Ctx) !void {1198    const pkg_name_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1199    const shell_pkg = types.NixPackage{ .attr = pkg_name_arg, .pname = pkg_name_arg, .version = "", .description = "" };1200    try tryPkg(ctx, shell_pkg);1201}12021203// --- Home Manager commands ---12041205const home_help = [_][2][]const u8{1206    .{ "init", "set up home manager for the first time" },1207    .{ "init --switch", "set up and activate immediately" },1208    .{ "apply", "apply home-manager configuration" },1209    .{ "apply --dry", "preview changes without activating" },1210    .{ "back", "roll back one generation" },1211    .{ "history", "list all generations" },1212    .{ "edit", "open home.nix" },1213    .{ "check", "validate without applying" },1214    .{ "diff", "compare the latest two generations" },1215    .{ "packages", "list managed packages" },1216};12171218const HomeGen = struct {1219    number: u32,1220    date: []const u8,1221    time: []const u8,1222    path: []const u8,1223};12241225// `home-manager generations` lines read:1226//   2026-06-01 11:56 : id 765 -> /nix/store/<hash>-home-manager-generation1227// Newest first, so index 0 is the current generation.1228fn parseHomeGenerations(gpa: std.mem.Allocator, out_str: []const u8) ![]HomeGen {1229    var gens: std.ArrayList(HomeGen) = .empty;1230    var lines = std.mem.splitScalar(u8, out_str, '\n');1231    while (lines.next()) |line| {1232        const t = std.mem.trim(u8, line, " \t\r");1233        if (t.len == 0) continue;1234        var it = std.mem.tokenizeAny(u8, t, " \t");1235        const date = it.next() orelse continue;1236        const time = it.next() orelse continue;1237        var number: ?u32 = null;1238        var path: []const u8 = "";1239        while (it.next()) |tok| {1240            if (std.mem.eql(u8, tok, "id")) {1241                if (it.next()) |n| number = std.fmt.parseInt(u32, n, 10) catch null;1242            } else if (std.mem.startsWith(u8, tok, "/nix/store/")) {1243                path = tok;1244            }1245        }1246        const num = number orelse continue;1247        try gens.append(gpa, .{1248            .number = num,1249            .date = try gpa.dupe(u8, date),1250            .time = try gpa.dupe(u8, time),1251            .path = try gpa.dupe(u8, path),1252        });1253    }1254    return gens.toOwnedSlice(gpa);1255}12561257fn freeHomeGens(gpa: std.mem.Allocator, gens: []HomeGen) void {1258    for (gens) |g| {1259        gpa.free(g.date);1260        gpa.free(g.time);1261        gpa.free(g.path);1262    }1263    gpa.free(gens);1264}12651266test "parseHomeGenerations reads id, date and store path" {1267    const a = std.testing.allocator;1268    const sample =1269        \\2026-06-01 11:56 : id 765 -> /nix/store/aaaa-home-manager-generation1270        \\2026-05-31 10:29 : id 764 -> /nix/store/bbbb-home-manager-generation1271    ;1272    const gens = try parseHomeGenerations(a, sample);1273    defer freeHomeGens(a, gens);1274    try std.testing.expectEqual(@as(usize, 2), gens.len);1275    try std.testing.expectEqual(@as(u32, 765), gens[0].number);1276    try std.testing.expectEqualStrings("2026-06-01", gens[0].date);1277    try std.testing.expectEqualStrings("11:56", gens[0].time);1278    try std.testing.expectEqualStrings("/nix/store/aaaa-home-manager-generation", gens[0].path);1279    try std.testing.expectEqual(@as(u32, 764), gens[1].number);1280}12811282// Current (newest) home generation number, or 0 if unavailable.1283fn homeCurrentGen(ctx: Ctx) u32 {1284    const out = exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine) catch return 0;1285    defer ctx.gpa.free(out);1286    const gens = parseHomeGenerations(ctx.gpa, out) catch return 0;1287    defer freeHomeGens(ctx.gpa, gens);1288    return if (gens.len > 0) gens[0].number else 0;1289}12901291pub fn home(ctx: Ctx) !void {1292    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help"))1293        return output.subcommandHelp("home", &home_help, null);12941295    // Home Manager manages the local user's environment. Detection (which binary,1296    // ~/.config/home-manager, $HOME/$USER for the flake ref) all read the LOCAL1297    // host, while exec routes over SSH for a remote machine — so `home --on1298    // <remote>` would decide mode/flake-ref from the wrong box. Refuse it cleanly1299    // rather than acting on a mismatch.1300    if (!ctx.machine.local) {1301        output.homeLocalOnly(ctx.machine.name);1302        return;1303    }13041305    // init runs before mode detection: its whole purpose is bootstrapping a host1306    // that has no home-manager yet, so a .none mode must not short-circuit it.1307    if (std.mem.eql(u8, ctx.sub, "init")) return homeInitCmd(ctx);13081309    const mode = exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ);1310    if (mode == .none) {1311        output.homeNotInstalled();1312        return;1313    }13141315    // apply is the only command meaningful in module mode (it redirects to1316    // `nina apply`); everything else needs the standalone home-manager CLI.1317    if (std.mem.eql(u8, ctx.sub, "apply")) return homeApply(ctx, mode);1318    // edit just opens the local home.nix — fine in module mode too.1319    if (std.mem.eql(u8, ctx.sub, "edit")) return homeEdit(ctx);13201321    if (mode == .module) {1322        output.homeModuleManaged();1323        return;1324    }13251326    if (std.mem.eql(u8, ctx.sub, "back")) return homeBack(ctx);1327    if (std.mem.eql(u8, ctx.sub, "history")) return homeHistory(ctx);1328    if (std.mem.eql(u8, ctx.sub, "check")) return homeCheck(ctx);1329    if (std.mem.eql(u8, ctx.sub, "diff")) return homeDiff(ctx);1330    if (std.mem.eql(u8, ctx.sub, "packages")) return homePackages(ctx);13311332    return output.subcommandHelp("home", &home_help, null);1333}13341335fn homePackages(ctx: Ctx) !void {1336    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1337    defer ctx.gpa.free(out);1338    const gens = try parseHomeGenerations(ctx.gpa, out);1339    defer freeHomeGens(ctx.gpa, gens);13401341    output.homePackagesHeader(ctx.machine.name);1342    if (gens.len == 0 or gens[0].path.len == 0) return;13431344    // The generation's OWN references are home-manager's activation deps1345    // (bash, coreutils, ...), not what the user installed. The user's packages1346    // live one level down, in the `…-home-manager-path` env the generation1347    // references — descend into it and list ITS references. Fall back to the1348    // generation refs if that env isn't present (older home-manager layouts).1349    const gen_refs = exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, gens[0].path) catch return;1350    defer ctx.gpa.free(gen_refs);13511352    var refs = gen_refs;1353    var env_refs: ?[]u8 = null;1354    defer if (env_refs) |e| ctx.gpa.free(e);1355    if (findHomeManagerPath(gen_refs)) |pkg_path| {1356        if (exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, pkg_path)) |e| {1357            env_refs = e;1358            refs = e;1359        } else |_| {}1360    }13611362    // Dedup by name: multi-output derivations (jq, jq-lib, jq-doc) collapse to1363    // the same name after the output suffix is stripped. Keys are slices into1364    // `refs`, valid for this function's lifetime.1365    var seen = std.StringHashMap(void).init(ctx.gpa);1366    defer seen.deinit();1367    var lines = std.mem.splitScalar(u8, refs, '\n');1368    while (lines.next()) |line| {1369        const t = std.mem.trim(u8, line, " \t\r");1370        if (t.len == 0) continue;1371        const row = pkgFromStorePath(t);1372        if (row.version.len == 0) continue;1373        if (std.mem.indexOf(u8, row.name, "home-manager") != null) continue;1374        if (seen.contains(row.name)) continue;1375        seen.put(row.name, {}) catch {};1376        output.listPkg(row.name, row.version);1377    }1378}13791380// The `…-home-manager-path` env among a generation's references — the buildEnv1381// of the user's home.packages. Returns the full store-path line, or null.1382fn findHomeManagerPath(refs: []const u8) ?[]const u8 {1383    var lines = std.mem.splitScalar(u8, refs, '\n');1384    while (lines.next()) |line| {1385        const t = std.mem.trim(u8, line, " \t\r");1386        if (std.mem.indexOf(u8, t, "home-manager-path") != null) return t;1387    }1388    return null;1389}13901391test "findHomeManagerPath picks the env, not the generation or infra" {1392    const refs =1393        \\/nix/store/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-bash-5.31394        \\/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path1395        \\/nix/store/cccccccccccccccccccccccccccccccc-coreutils-9.111396    ;1397    try std.testing.expectEqualStrings(1398        "/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path",1399        findHomeManagerPath(refs).?,1400    );1401    try std.testing.expectEqual(@as(?[]const u8, null), findHomeManagerPath("/nix/store/x-bash-5.3\n"));1402}14031404fn homeDiff(ctx: Ctx) !void {1405    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1406    defer ctx.gpa.free(out);1407    const gens = try parseHomeGenerations(ctx.gpa, out);1408    defer freeHomeGens(ctx.gpa, gens);14091410    // Need two generations and both their store paths to diff their closures.1411    if (gens.len < 2 or gens[0].path.len == 0 or gens[1].path.len == 0) {1412        output.homeNothingToDiff();1413        return;1414    }1415    const newer = gens[0];1416    const older = gens[1];1417    output.homeDiffHeader(older.number, newer.number, ctx.machine.name);1418    if (try exec.diffClosuresPaths(ctx.io, &ctx.machine, ctx.gpa, older.path, newer.path) != 0)1419        return error.ProcessFailed;1420}14211422fn homeCheck(ctx: Ctx) !void {1423    output.homeCheckStart(ctx.machine.name);1424    const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa);1425    if (code != 0) return error.BuildFailed;1426    output.homeCheckOk();1427}14281429fn homeEdit(ctx: Ctx) !void {1430    // Standalone home config lives at ~/.config/home-manager/home.nix; the same1431    // path is what detection keys on for module mode, so it resolves for both.1432    const path = exec.homeNixPath(ctx.gpa, ctx.environ) orelse {1433        errors.error_info.setMessage("could not resolve ~/.config/home-manager/home.nix", .{});1434        return error.ConfigNotFound;1435    };1436    defer ctx.gpa.free(path);1437    output.homeEditOpen(path, ctx.cfg.editor);1438    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);1439}14401441fn homeHistory(ctx: Ctx) !void {1442    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1443    defer ctx.gpa.free(out);1444    const gens = try parseHomeGenerations(ctx.gpa, out);1445    defer freeHomeGens(ctx.gpa, gens);1446    output.homeHistoryHeader(ctx.machine.name);1447    // Newest-first from home-manager; the first row is the current generation.1448    for (gens, 0..) |g, i| output.homeHistoryRow(g.number, g.date, g.time, i == 0);1449}14501451fn homeBack(ctx: Ctx) !void {1452    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1453    defer ctx.gpa.free(out);1454    const gens = try parseHomeGenerations(ctx.gpa, out);1455    defer freeHomeGens(ctx.gpa, gens);14561457    // Newest-first: [0] is current, [1] is the generation to roll back to.1458    if (gens.len < 2) {1459        output.alreadyOldest();1460        return;1461    }1462    const current = gens[0].number;1463    const prev = gens[1].number;14641465    output.homeBackStart(ctx.machine.name, current, prev);1466    if (ctx.cfg.confirm and !output.confirm("")) return;1467    const code = try exec.homeManagerRollback(ctx.io, &ctx.machine, ctx.gpa);1468    if (code != 0) return error.BuildFailed;1469    output.homeBackDone(prev);1470}14711472fn homeInitCmd(ctx: Ctx) !void {1473    var switch_on_init = false;1474    var dir: ?[]const u8 = null;1475    for (ctx.args) |arg| {1476        if (std.mem.eql(u8, arg, "--switch")) {1477            switch_on_init = true;1478        } else if (!std.mem.startsWith(u8, arg, "-")) {1479            dir = arg;1480        }1481    }14821483    // Guard only the default location — a custom dir is the user's call, and1484    // home-manager creates it. Never clobber an existing ~/.config/home-manager.1485    if (dir == null) {1486        if (exec.homeNixPath(ctx.gpa, ctx.environ)) |path| {1487            defer ctx.gpa.free(path);1488            if (exec.pathExists(ctx.io, path)) {1489                output.homeInitExists(path);1490                return;1491            }1492        }1493    }14941495    output.homeInitStart(switch_on_init, dir);1496    const code = try exec.homeManagerInit(ctx.io, &ctx.machine, ctx.gpa, switch_on_init, dir);1497    if (code != 0) return error.BuildFailed;1498    output.homeInitDone(switch_on_init);1499}15001501fn homeApply(ctx: Ctx, mode: exec.HomeManagerMode) !void {1502    // NixOS/flake module: home config is rebuilt by nixos-rebuild — redirect.1503    if (mode == .module) {1504        output.homeModuleManaged();1505        return;1506    }1507    if (ctx.dry) {1508        output.homeApplyDry(ctx.machine.name);1509        const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa);1510        if (code != 0) return error.BuildFailed;1511        output.homeApplyDryDone();1512        return;1513    }15141515    if (!try runPreHook(ctx, "pre-home")) {1516        output.aborted();1517        return error.HookAborted;1518    }15191520    output.homeApplyStart(ctx.machine.name);15211522    // Flake-based home config: switch by attribute with a graceful fallback1523    // chain. A channel-based config (no flake.nix) uses a plain switch.1524    const dir = exec.homeFlakeDir(ctx.gpa, ctx.io, ctx.environ);1525    defer if (dir) |d| ctx.gpa.free(d);1526    if (dir) |d| return homeApplyFlake(ctx, d);15271528    output.printSubstep("home-manager switch", .{});1529    const start = std.Io.Clock.awake.now(ctx.io);1530    const code = try exec.homeManagerSwitch(ctx.io, &ctx.machine, ctx.gpa);1531    if (code != 0) return error.BuildFailed;15321533    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());1534    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));1535    output.homeApplyDone(homeCurrentGen(ctx), elapsed);1536    runPostHook(ctx, "post-home");1537}15381539// Switch a flake-based home config, trying the most specific attribute first:1540//   <dir>#<user>-<arch>-<os>  →  <dir>#<user>  →  <dir>  (home-manager resolves)1541// Each fallback fires only on a missing-attribute error, never on a real build1542// failure. Mirrors how ${USER}-${system} homeConfigurations keys are written.1543fn homeApplyFlake(ctx: Ctx, dir: []const u8) !void {1544    const user = ctx.environ.get("USER") orelse "default";15451546    var refs: std.ArrayList([]const u8) = .empty;1547    defer {1548        for (refs.items) |r| ctx.gpa.free(r);1549        refs.deinit(ctx.gpa);1550    }1551    if (exec.homeManagerAttr(ctx.gpa, ctx.io, &ctx.machine, ctx.environ) catch null) |attr| {1552        defer ctx.gpa.free(attr);1553        try refs.append(ctx.gpa, try std.fmt.allocPrint(ctx.gpa, "{s}#{s}", .{ dir, attr }));1554    }1555    try refs.append(ctx.gpa, try std.fmt.allocPrint(ctx.gpa, "{s}#{s}", .{ dir, user }));1556    try refs.append(ctx.gpa, try ctx.gpa.dupe(u8, dir));15571558    const start = std.Io.Clock.awake.now(ctx.io);1559    for (refs.items, 0..) |ref, i| {1560        output.printSubstep("home-manager switch --flake {s}", .{ref});1561        switch (try exec.homeManagerSwitchFlake(ctx.io, &ctx.machine, ctx.gpa, ref)) {1562            .ok => {1563                const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());1564                const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));1565                output.homeApplyDone(homeCurrentGen(ctx), elapsed);1566                runPostHook(ctx, "post-home");1567                return;1568            },1569            // Attr not defined by the flake — drop to the next candidate.1570            .attr_missing => {1571                if (i + 1 < refs.items.len) output.homeAttrFallback(ref);1572                continue;1573            },1574            .failed => return error.BuildFailed,1575        }1576    }1577    return error.BuildFailed;1578}15791580// --- Service commands ---15811582const service_help = [_][2][]const u8{1583    .{ "list", "list running services" },1584    .{ "logs <svc>", "show service logs" },1585    .{ "status <svc>", "service status" },1586    .{ "start <svc>", "start a service" },1587    .{ "stop <svc>", "stop a service" },1588    .{ "restart <svc>", "restart a service" },1589    .{ "enable <svc>", "enable at boot" },1590    .{ "disable <svc>", "disable at boot" },1591};15921593pub fn service(ctx: Ctx) !void {1594    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");1595    if (std.mem.eql(u8, ctx.sub, "list")) {1596        output.serviceListHeader(ctx.machine.name);1597        const svcs = exec.serviceList(ctx.gpa, ctx.io, &ctx.machine, ctx.user) catch &.{};1598        defer ctx.gpa.free(svcs);1599        for (svcs) |s| output.serviceRow(s);1600        return;1601    }1602    if (std.mem.eql(u8, ctx.sub, "logs")) {1603        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1604        const follow = ctx.args.len > 1 and std.mem.eql(u8, ctx.args[1], "-f");1605        output.serviceLogsHeader(name, ctx.last, ctx.machine.name);1606        _ = try exec.serviceLogs(ctx.io, &ctx.machine, ctx.gpa, name, ctx.last, follow, ctx.user);1607        return;1608    }1609    if (std.mem.eql(u8, ctx.sub, "status")) {1610        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1611        output.serviceVerb("status", name, ctx.machine.name);1612        _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, "status", name, ctx.user);1613        return;1614    }1615    // start/stop/restart/enable/disable1616    const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1617    if (ctx.cfg.confirm and (std.mem.eql(u8, ctx.sub, "stop") or std.mem.eql(u8, ctx.sub, "disable"))) {1618        if (!output.confirm("")) return;1619    }1620    output.serviceVerb(ctx.sub, name, ctx.machine.name);1621    _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, ctx.sub, name, ctx.user);1622    output.serviceDone();1623}16241625// --- Flake commands ---16261627const flake_help = [_][2][]const u8{1628    .{ "init", "create a new flake.nix" },1629    .{ "update", "update flake inputs" },1630    .{ "update <in>", "update a specific input" },1631    .{ "check", "validate the flake" },1632    .{ "show", "inspect flake outputs" },1633    .{ "lock", "regenerate flake.lock" },1634    .{ "clone <url>", "clone a flake repository" },1635};16361637pub fn flake(ctx: Ctx) !void {1638    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("flake", &flake_help, null);1639    if (std.mem.eql(u8, ctx.sub, "update")) {1640        output.flakeUpdateStart();1641        const input: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1642        _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1643        output.flakeLockWritten();1644        return;1645    }1646    if (std.mem.eql(u8, ctx.sub, "check")) {1647        output.flakeCheckStart();1648        const code = try exec.flakeCheck(ctx.io, &ctx.machine, ctx.gpa);1649        if (code == 0) output.flakeValid() else output.checkFailed("");1650        return;1651    }1652    if (std.mem.eql(u8, ctx.sub, "show")) {1653        const json_out = exec.flakeShow(ctx.gpa, ctx.io, &ctx.machine) catch null;1654        if (json_out) |j| {1655            defer ctx.gpa.free(j);1656            output.flakeShowHeader("flake outputs");1657            // Parse and display the flake outputs1658            const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, j, .{}) catch return;1659            defer parsed.deinit();1660            if (parsed.value == .object) {1661                var it = parsed.value.object.iterator();1662                while (it.next()) |entry| {1663                    if (entry.value_ptr.* == .object) {1664                        var inner = entry.value_ptr.object.iterator();1665                        while (inner.next()) |e2| {1666                            const desc = if (e2.value_ptr.* == .object)1667                                if (e2.value_ptr.object.get("description")) |d|1668                                    if (d == .string) d.string else ""1669                                else1670                                    ""1671                            else1672                                "";1673                            output.flakeShowEntry(entry.key_ptr.*, e2.key_ptr.*, desc);1674                        }1675                    }1676                }1677            }1678        }1679        return;1680    }1681    if (std.mem.eql(u8, ctx.sub, "init")) {1682        _ = try exec.flakeInit(ctx.io, &ctx.machine, ctx.gpa);1683        return;1684    }1685    if (std.mem.eql(u8, ctx.sub, "lock")) {1686        _ = try exec.flakeLock(ctx.io, &ctx.machine, ctx.gpa);1687        return;1688    }1689    if (std.mem.eql(u8, ctx.sub, "clone")) {1690        const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1691        _ = try exec.flakeClone(ctx.io, &ctx.machine, ctx.gpa, url);1692        return;1693    }1694}16951696// --- Store commands ---16971698const store_help = [_][2][]const u8{1699    .{ "info", "store size and counts" },1700    .{ "path <attr>", "store path of a package" },1701    .{ "gc", "collect garbage" },1702    .{ "optimise", "deduplicate store paths with hard links" },1703    .{ "verify", "verify store integrity" },1704    .{ "repair", "repair corrupted paths" },1705};17061707pub fn store(ctx: Ctx) !void {1708    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("store", &store_help, null);1709    if (std.mem.eql(u8, ctx.sub, "gc")) {1710        _ = try exec.storeGc(ctx.io, &ctx.machine, ctx.gpa);1711        return;1712    }1713    // Accept both spellings — optimise (en) and optimize (us).1714    if (std.mem.eql(u8, ctx.sub, "optimise") or std.mem.eql(u8, ctx.sub, "optimize")) {1715        output.storeOptimiseStart(ctx.machine.name);1716        _ = try exec.storeOptimise(ctx.io, &ctx.machine, ctx.gpa);1717        output.storeOptimiseDone();1718        return;1719    }1720    if (std.mem.eql(u8, ctx.sub, "verify")) {1721        output.storeVerifyStart();1722        _ = try exec.storeVerify(ctx.io, &ctx.machine, ctx.gpa);1723        return;1724    }1725    if (std.mem.eql(u8, ctx.sub, "repair")) {1726        if (ctx.cfg.confirm and !output.confirm("")) return;1727        output.storeRepairStart();1728        _ = try exec.storeRepair(ctx.io, &ctx.machine, ctx.gpa);1729        return;1730    }1731    if (std.mem.eql(u8, ctx.sub, "info")) {1732        const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1733        output.storeInfo(si);1734        return;1735    }1736    if (std.mem.eql(u8, ctx.sub, "path")) {1737        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1738        const path = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, attr);1739        defer ctx.gpa.free(path);1740        output.storePath(path);1741        return;1742    }1743    // default: info1744    const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1745    output.storeInfo(si);1746}17471748// --- Channel commands ---17491750const channel_help = [_][2][]const u8{1751    .{ "list", "list channels" },1752    .{ "add <url> [name]", "add a channel" },1753    .{ "remove <name>", "remove a channel" },1754    .{ "update", "update all channels" },1755};17561757pub fn channel(ctx: Ctx) !void {1758    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("channel", &channel_help, null);1759    // On a flake-managed system, nix-channel operations generally don't apply.1760    if (flakeSystem(ctx)) output.flakeChannelNote();1761    if (std.mem.eql(u8, ctx.sub, "list")) {1762        output.channelListHeader(ctx.machine.name);1763        const chans = try exec.channelList(ctx.gpa, ctx.io, &ctx.machine);1764        defer ctx.gpa.free(chans);1765        for (chans) |ch| output.channelRow(ch);1766        return;1767    }1768    if (std.mem.eql(u8, ctx.sub, "add")) {1769        const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1770        const name = if (ctx.args.len > 1) ctx.args[1] else "";1771        _ = try exec.channelAdd(ctx.io, &ctx.machine, ctx.gpa, url, name);1772        output.channelDone();1773        return;1774    }1775    if (std.mem.eql(u8, ctx.sub, "remove")) {1776        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1777        _ = try exec.channelRemove(ctx.io, &ctx.machine, ctx.gpa, name);1778        output.channelDone();1779        return;1780    }1781    if (std.mem.eql(u8, ctx.sub, "update")) {1782        return channelUpdateCmd(ctx);1783    }1784}17851786// --- Profile commands ---17871788pub fn profile(ctx: Ctx) !void {1789    if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {1790        output.profileListHeader();1791        const out = exec.profileList(ctx.gpa, ctx.io, &ctx.machine) catch null;1792        if (out) |o| {1793            defer ctx.gpa.free(o);1794            var lines = std.mem.splitScalar(u8, o, '\n');1795            while (lines.next()) |line| {1796                const t = std.mem.trim(u8, line, " \t\r");1797                if (t.len == 0) continue;1798                output.profileRow(t, "", "");1799            }1800        }1801        return;1802    }1803    if (std.mem.eql(u8, ctx.sub, "install")) {1804        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1805        _ = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, attr);1806        output.done();1807        return;1808    }1809    if (std.mem.eql(u8, ctx.sub, "remove")) {1810        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1811        _ = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, attr);1812        output.done();1813        return;1814    }1815    if (std.mem.eql(u8, ctx.sub, "upgrade")) {1816        _ = try exec.profileUpgrade(ctx.io, &ctx.machine, ctx.gpa);1817        output.done();1818        return;1819    }1820}18211822// --- Pkg commands ---18231824const pkg_help = [_][2][]const u8{1825    .{ "why <pkg>", "what pulled it in" },1826    .{ "deps <pkg>", "direct dependencies" },1827    .{ "size <pkg>", "closure size" },1828    .{ "path <pkg>", "store path" },1829    .{ "closure <pkg>", "full closure" },1830};18311832pub fn pkg(ctx: Ctx) !void {1833    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("pkg", &pkg_help, null);1834    const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1835    if (std.mem.eql(u8, ctx.sub, "why")) {1836        if (try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1837        return;1838    }1839    if (std.mem.eql(u8, ctx.sub, "deps")) {1840        if (try exec.pkgDeps(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1841        return;1842    }1843    if (std.mem.eql(u8, ctx.sub, "size")) {1844        const s = try exec.pkgSize(ctx.gpa, ctx.io, &ctx.machine, name);1845        defer ctx.gpa.free(s);1846        output.pkgResult("size", s);1847        return;1848    }1849    if (std.mem.eql(u8, ctx.sub, "path")) {1850        const p = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, name);1851        defer ctx.gpa.free(p);1852        output.pkgResult("path", p);1853        return;1854    }1855    if (std.mem.eql(u8, ctx.sub, "closure")) {1856        if (try exec.pkgClosure(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1857        return;1858    }1859}18601861// Top-level alias for `nina pkg why <pkg>` — surfaces what pulled a package in1862// without the user needing to know about the `pkg` subgroup.1863pub fn why(ctx: Ctx) !void {1864    const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1865    if (try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1866}18671868// --- Pin / Unpin ---18691870pub fn pin(ctx: Ctx) !void {1871    const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1872    const commit = if (ctx.args.len > 1) ctx.args[1] else return error.Internal;1873    exec.editFlakeLock(ctx.gpa, input, commit) catch return error.ProcessFailed;1874    output.pinDone(input, commit);1875}18761877pub fn unpin(ctx: Ctx) !void {1878    const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1879    _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1880    output.unpinDone(input);1881}18821883// --- Hash / Fetch ---18841885pub fn hash(ctx: Ctx) !void {1886    const path = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1887    const h = try exec.nixHash(ctx.gpa, ctx.io, &ctx.machine, path);1888    defer ctx.gpa.free(h);1889    output.hashResult(std.mem.trim(u8, h, " \t\n\r"));1890}18911892pub fn fetch(ctx: Ctx) !void {1893    const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1894    const h = try exec.nixFetch(ctx.gpa, ctx.io, &ctx.machine, url);1895    defer ctx.gpa.free(h);1896    output.fetchResult(std.mem.trim(u8, h, " \t\n\r"), url);1897}18981899// --- Build / Run ---19001901pub fn build(ctx: Ctx) !void {1902    const attr: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1903    output.buildStart(attr orelse "default");1904    const code = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, attr);1905    if (code != 0) return error.BuildFailed;1906    output.buildDone();1907}19081909pub fn runCmd(ctx: Ctx) !void {1910    const pkg_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1911    output.runStart(pkg_arg);1912    _ = try exec.nixRun(ctx.io, &ctx.machine, ctx.gpa, pkg_arg);1913}19141915// --- Hello ---19161917pub fn hello(ctx: Ctx) !void {1918    output.hello(ctx.cfg.machines);1919}19201921const ConfigKind = enum { flake, channel, none };19221923// Scan the conventional /etc/nixos for a flake.nix (flake-based) or a1924// configuration.nix (channel-based) to pre-fill the wizard's defaults.1925fn scanConfig(io: std.Io) ConfigKind {1926    if (exec.pathExists(io, "/etc/nixos/flake.nix")) return .flake;1927    if (exec.pathExists(io, "/etc/nixos/configuration.nix")) return .channel;1928    return .none;1929}19301931// Runs when the config is absent on first invocation (interactive TTY only).1932// Scans for an existing nixos config, detects flake vs channel, and offers a1933// smart default path — flake-ness is detected, never asked.1934pub fn firstRunWizard(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1935    output.firstRunBanner();1936    output.firstRunNoConfig();19371938    var name_buf: [256]u8 = undefined;1939    var path_buf: [256]u8 = undefined;19401941    const machine_name = output.firstRunPrompt("machine name", "my-machine", &name_buf);19421943    output.firstRunScanning();1944    const kind = scanConfig(io);1945    switch (kind) {1946        .flake => output.firstRunDetected("/etc/nixos/flake.nix", true),1947        .channel => output.firstRunDetected("/etc/nixos/configuration.nix", false),1948        .none => output.firstRunNoneFound(),1949    }19501951    // Detected systems default to /etc/nixos (press enter to confirm); when1952    // nothing was found, leave the default empty so the user must type a path.1953    const default_path: []const u8 = if (kind == .none) "" else "/etc/nixos";1954    const config_path = output.firstRunPromptDefault("config path", default_path, kind != .none, &path_buf);19551956    // Re-detect at the chosen path in case the user pointed elsewhere — flake.nix1957    // there means a flake system, recorded so channel commands warn appropriately.1958    const use_flakes = exec.dirHasFlake(gpa, io, config_path);19591960    const conf_path = try config.configPath(gpa, environ);1961    defer gpa.free(conf_path);1962    if (std.fs.path.dirname(conf_path)) |dir| exec.ensureDir(gpa, io, dir);19631964    // `flake` is a top-level config field, so it must precede the [machine] block.1965    const flake_line = if (use_flakes) "flake = true\n" else "";1966    var content_buf: [1024]u8 = undefined;1967    const content = try std.fmt.bufPrint(1968        &content_buf,1969        "{s}[machine]\nname = {s}\nconfig = {s}\nlocal = true\n",1970        .{ flake_line, machine_name, config_path },1971    );19721973    const file = std.Io.Dir.createFile(.cwd(), io, conf_path, .{}) catch {1974        errors.error_info.setMessage("could not write {s}", .{conf_path});1975        return error.Internal;1976    };1977    defer file.close(io);1978    file.writePositionalAll(io, content, 0) catch {1979        errors.error_info.setMessage("could not write {s}", .{conf_path});1980        return error.Internal;1981    };19821983    output.firstRunWritten(conf_path);1984}19851986pub fn setup(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1987    // Create the config first if it doesn't exist. This makes `nina setup`1988    // a complete onboarding command — not just a nix-features check. Any legacy1989    // ~/.nina.conf is migrated to the XDG path before we decide to run the wizard.1990    config.migrateLegacyConfig(gpa, io, environ);1991    if (config.configPath(gpa, environ)) |conf_path| {1992        defer gpa.free(conf_path);1993        if (std.Io.Dir.openFile(.cwd(), io, conf_path, .{})) |f| {1994            f.close(io);1995        } else |_| {1996            try firstRunWizard(gpa, io, environ);1997            errors.error_info.reset();1998        }1999    } else |_| {}20002001    output.setupCheck();2002    const status = exec.checkNixFeatures(gpa, io, environ);2003    output.setupFeatures(status.nix_command, status.flakes);20042005    if (status.allEnabled()) {2006        output.setupAllSet();2007        api.ensureRegistryPinned(gpa, io, environ);2008        return;2009    }20102011    // On NixOS the features belong in configuration.nix (the declarative,2012    // permanent home), not ~/.config/nix/nix.conf. Offer to add the one line;2013    // the user runs the rebuild. We don't pin the registry here because the2014    // features aren't live until that rebuild lands.2015    if (exec.isNixOS(io)) {2016        const conf_path = "/etc/nixos/configuration.nix";2017        if (exec.nixosConfigEnablesFeatures(gpa, io, conf_path)) {2018            output.setupNixosNeedsRebuild(conf_path);2019            return;2020        }2021        output.setupNixosOffer(exec.NIXOS_FEATURES_LINE, conf_path);2022        if (output.confirmDefaultNo("add it now?")) {2023            if (exec.appendFeaturesToNixosConfig(gpa, io, environ, conf_path)) |_| {2024                output.setupNixosWrote(conf_path);2025            } else |_| {2026                output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);2027            }2028        } else {2029            output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);2030        }2031        return;2032    }20332034    // Non-NixOS: a user-level nix.conf takes effect immediately, no sudo needed.2035    output.setupEnabling();2036    const path = try exec.enableNixFeatures(gpa, io, environ);2037    defer gpa.free(path);20382039    output.setupDone(path);2040    api.ensureRegistryPinned(gpa, io, environ);2041}20422043// --- Log helper ---20442045fn logAction(ctx: Ctx, action: []const u8, gen: u32) void {2046    var ts_buf: [32]u8 = undefined;2047    const ts = nowIso(ctx.io, &ts_buf);2048    var buf: [256]u8 = undefined;2049    const entry = std.fmt.bufPrint(&buf, "{{\"ts\":\"{s}\",\"machine\":\"{s}\",\"command\":\"{s}\",\"outcome\":\"success\",\"gen_before\":null,\"gen_after\":{d},\"duration_ms\":0}}\n", .{2050        ts, ctx.machine.name, action, gen,2051    }) catch return;2052    exec.appendNinaLog(ctx.io, ctx.environ, entry);2053}20542055// Wall-clock UTC as ISO-8601. Uses Io.Clock.real (the settable Unix-epoch clock);2056// Io.Clock.awake is monotonic and unsuitable for timestamps. Falls back to epoch 0.2057fn nowIso(io: std.Io, buf: []u8) []const u8 {2058    const fallback = "1970-01-01T00:00:00Z";2059    const ns = std.Io.Clock.real.now(io).toNanoseconds();2060    if (ns <= 0) return fallback;2061    const secs: u64 = @intCast(@divFloor(ns, 1_000_000_000));2062    const es = std.time.epoch.EpochSeconds{ .secs = secs };2063    const ed = es.getEpochDay();2064    const yd = ed.calculateYearDay();2065    const md = yd.calculateMonthDay();2066    const ds = es.getDaySeconds();2067    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", .{2068        yd.year,              md.month.numeric(),      @as(u32, md.day_index) + 1,2069        ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(),2070    }) catch return fallback;2071}