commands.zig

83.2 KB · raw

1// commands.zig — all command handlers2// Orchestrates exec/api/output. Zero direct stdout writes.3const std = @import("std");4const builtin = @import("builtin");5const types = @import("types.zig");6const errors = @import("errors.zig");7const config = @import("config.zig");8const output = @import("output.zig");9const exec = @import("exec.zig");10const api = @import("api.zig");11const search_tui = @import("search.zig");12const version = @import("version.zig");1314const UPDATE_URL = "https://kepr.uk/api/nina/releases/latest";15const FLAKE_URL = "https://kepr.uk/nina/archive/HEAD.tar.gz#nina";1617const Semver = struct {18    major: u32,19    minor: u32,20    patch: u32,21};2223pub const Ctx = struct {24    gpa: std.mem.Allocator,25    io: std.Io,26    environ: *const std.process.Environ.Map,27    machine: types.Machine,28    cfg: types.NinaConfig,29    args: []const []const u8, // positional args after subcommand30    sub: []const u8, // subcommand (e.g. "list" in "service list")31    dry: bool,32    check: bool,33    no_apply: bool,34    all: bool,35    last: u32,36    json: bool,37    user: bool, // --user: operate on user (vs system) services38};3940// A system is flake-managed when the config says so OR a flake.nix is present in41// the config dir. Detection means a fresh channel user who points nina at a flake42// dir gets the right behavior without editing config first.43fn flakeSystem(ctx: Ctx) bool {44    return ctx.cfg.flake or exec.configHasFlake(ctx.gpa, ctx.io, &ctx.machine);45}4647fn runPreHook(ctx: Ctx, hook_name: []const u8) !bool {48    const hook = try exec.runHook(ctx.gpa, ctx.io, ctx.environ, hook_name);49    defer ctx.gpa.free(hook.output);50    switch (hook.result) {51        .not_found, .ok => return true,52        .failed => {53            output.hookFailed(hook_name, hook.exit_code, hook.output);54            return output.confirmDefaultNo("continue anyway?");55        },56    }57}5859fn runPostHook(ctx: Ctx, hook_name: []const u8) void {60    const hook = exec.runHook(ctx.gpa, ctx.io, ctx.environ, hook_name) catch return;61    defer ctx.gpa.free(hook.output);62    if (hook.result == .failed) {63        output.hookWarning(hook_name, hook.exit_code, hook.output);64    }65}6667pub fn apply(ctx: Ctx) !void {68    if (ctx.dry) {69        output.applyDry(ctx.machine.name);70        const code = try exec.nixosRebuildDryActivate(ctx.io, &ctx.machine, ctx.gpa);71        if (code != 0) return error.BuildFailed;72        output.applyDryDone();73        return;74    }75    if (ctx.check) {76        return check(ctx);77    }7879    if (!try runPreHook(ctx, "pre-apply")) {80        output.aborted();81        return error.HookAborted;82    }8384    output.applyStart(ctx.machine.name);85    output.buildPanelInit();86    const start = std.Io.Clock.awake.now(ctx.io);8788    var panel = output.BuildPanel{};89    const code = exec.nixosRebuildSwitchWithPanel(ctx.io, &ctx.machine, ctx.gpa, &panel) catch |e| {90        output.buildPanelClear();91        exec.markApplyFailed(ctx.io, ctx.environ);92        return e;93    };94    output.buildPanelClear();9596    if (code != 0) {97        exec.markApplyFailed(ctx.io, ctx.environ);98        return error.BuildFailed;99    }100101    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());102    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));103    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;104    const after_failure = exec.takeApplyFailed(ctx.io, ctx.environ);105    output.applyDone(gen, elapsed, after_failure);106    // Show any nix warnings collected during the build (dim yellow, after success line).107    const warnings = errors.extractWarnings(ctx.gpa, errors.getBuildStderr()) catch &.{};108    defer {109        for (warnings) |w| ctx.gpa.free(w);110        ctx.gpa.free(warnings);111    }112    if (warnings.len > 0) output.buildWarnings(warnings);113    runPostHook(ctx, "post-apply");114    logAction(ctx, "apply", gen);115}116117pub fn check(ctx: Ctx) !void {118    output.checkStart(ctx.machine.name);119    const code = try exec.nixosRebuildBuild(ctx.io, &ctx.machine, ctx.gpa);120    if (code != 0) return error.BuildFailed;121    output.checkOk();122}123124pub fn back(ctx: Ctx) !void {125    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);126    defer ctx.gpa.free(gens);127128    var current: u32 = 0;129    for (gens) |g| if (g.current) {130        current = g.number;131    };132133    // Newest generation older than current. If there is none, we're already at the134    // oldest — stop cleanly instead of letting rollback fail with 'build failed'.135    var prev: u32 = 0;136    var has_prev = false;137    for (gens) |g| {138        if (g.number < current and (!has_prev or g.number > prev)) {139            prev = g.number;140            has_prev = true;141        }142    }143    if (!has_prev) {144        output.alreadyOldest();145        return;146    }147148    if (!try runPreHook(ctx, "pre-back")) {149        output.aborted();150        return error.HookAborted;151    }152153    output.backStart(ctx.machine.name, current, prev);154    if (ctx.cfg.confirm and !output.confirm("")) return;155156    // Flake systems don't have <nixos-config> in the Nix search path, so157    // `nixos-rebuild --rollback` fails. Switch by generation number instead158    // (same path as `nina go N`), which works for both channel and flake.159    const code = if (flakeSystem(ctx))160        try exec.switchGeneration(ctx.io, &ctx.machine, ctx.gpa, prev)161    else162        try exec.rollback(ctx.io, &ctx.machine, ctx.gpa);163    if (code != 0) return error.BuildFailed;164    output.backDone(prev);165    runPostHook(ctx, "post-back");166}167168pub fn go(ctx: Ctx) !void {169    if (ctx.args.len == 0) return error.Internal;170    const target = std.fmt.parseInt(u32, ctx.args[0], 10) catch return error.Internal;171    const current = try exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine);172173    output.goStart(ctx.machine.name, current, target);174    if (ctx.cfg.confirm and !output.confirm("")) return;175176    const code = try exec.switchGeneration(ctx.io, &ctx.machine, ctx.gpa, target);177    if (code != 0) return error.ProcessFailed;178    output.generationDone(target);179}180181pub fn history(ctx: Ctx) !void {182    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);183    defer ctx.gpa.free(gens);184    output.historyHeader(ctx.machine.name);185    for (gens) |g| output.historyRow(g);186}187188const gen_help = [_][2][]const u8{189    .{ "list", "list generations" },190    .{ "current", "show current generation" },191    .{ "delete <n>", "delete generation n" },192    .{ "delete old", "delete old generations" },193};194195pub fn genCmd(ctx: Ctx) !void {196    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("gen", &gen_help, null);197    if (std.mem.eql(u8, ctx.sub, "list")) return history(ctx);198    if (std.mem.eql(u8, ctx.sub, "current")) {199        const n = try exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine);200        output.genCurrent(n);201        return;202    }203    if (std.mem.eql(u8, ctx.sub, "delete")) {204        if (ctx.args.len == 0) return error.Internal;205        if (std.mem.eql(u8, ctx.args[0], "old")) {206            if (ctx.cfg.confirm and !output.confirm("")) return;207            _ = try exec.deleteOldGenerations(ctx.io, &ctx.machine, ctx.gpa);208        } else {209            const n = std.fmt.parseInt(u32, ctx.args[0], 10) catch return error.Internal;210            if (ctx.cfg.confirm and !output.confirm("")) return;211            _ = try exec.deleteGeneration(ctx.io, &ctx.machine, ctx.gpa, n);212        }213        output.done();214        return;215    }216    return error.Internal;217}218219pub fn clean(ctx: Ctx) !void {220    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);221    defer ctx.gpa.free(gens);222    const all = ctx.all or std.mem.eql(u8, ctx.sub, "all");223    const total: u32 = @intCast(gens.len);224    // `clean all` keeps only the current generation; otherwise keep the configured225    // count. With nothing older than the keep limit, there's nothing to collect.226    const keep: u32 = if (all) 1 else ctx.cfg.generations;227    if (total <= keep) {228        output.cleanNothing(ctx.machine.name, total);229        return;230    }231    output.cleanStart(ctx.machine.name, keep, total);232    if (ctx.cfg.confirm and !output.confirm("removing — cannot be undone")) return;233    _ = try exec.collectGarbage(ctx.io, &ctx.machine, ctx.gpa, all, ctx.cfg.generations);234    output.cleanDone();235}236237pub fn statusCmd(ctx: Ctx) !void {238    output.statusHeader();239    // --all renders every configured machine; remotes route through the same SSH240    // path as exec.capture. An unreachable machine is shown in red, not fatal.241    if (ctx.all and ctx.cfg.machines.len > 0) {242        for (ctx.cfg.machines) |m| statusRowFor(ctx, &m);243    } else {244        statusRowFor(ctx, &ctx.machine);245    }246    homeStatusLine(ctx);247}248249// When standalone Home Manager is present, show its current generation as a dim250// line indented under the machine rows. Gated on standalone mode (the only mode251// where we can read a generation), so a machine without HM is unaffected.252fn homeStatusLine(ctx: Ctx) void {253    if (exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ) != .standalone) return;254    const out = exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine) catch return;255    defer ctx.gpa.free(out);256    const gens = parseHomeGenerations(ctx.gpa, out) catch return;257    defer freeHomeGens(ctx.gpa, gens);258    if (gens.len == 0) return;259    output.statusHomeRow(gens[0].number, gens[0].date);260}261262fn statusRowFor(ctx: Ctx, machine: *const types.Machine) void {263    // A failure to read the current generation means we couldn't reach or query264    // the machine — mark it unreachable rather than reporting a bogus gen 0.265    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, machine) catch {266        output.statusRow(machine.name, 0, "", "", false);267        return;268    };269    const st = exec.systemStatus(ctx.gpa, ctx.io, machine);270    defer ctx.gpa.free(st.size);271    defer ctx.gpa.free(st.age);272    output.statusRow(machine.name, gen, st.age, st.size, true);273}274275pub fn diff(ctx: Ctx) !void {276    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);277    defer ctx.gpa.free(gens);278    var current: u32 = 0;279    var prev: u32 = 0;280    for (gens) |g| {281        if (g.current) current = g.number;282        if (!g.current and g.number > prev and g.number < current) prev = g.number;283    }284    if (ctx.args.len >= 2) {285        const a = std.fmt.parseInt(u32, ctx.args[0], 10) catch current - 1;286        const b = std.fmt.parseInt(u32, ctx.args[1], 10) catch current;287        output.diffHeader(a, b, ctx.machine.name);288        if (try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, a, b) != 0) return error.ProcessFailed;289    } else {290        output.diffHeader(if (prev > 0) prev else current - 1, current, ctx.machine.name);291        if (try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, if (prev > 0) prev else current - 1, current) != 0) return error.ProcessFailed;292    }293}294295pub fn mood(ctx: Ctx) !void {296    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;297    const st = exec.systemStatus(ctx.gpa, ctx.io, &ctx.machine);298    defer ctx.gpa.free(st.size);299    defer ctx.gpa.free(st.age);300    const state = exec.systemRunningState(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");301    defer ctx.gpa.free(state);302    output.mood(ctx.machine.name, state, gen, st.age, st.size);303}304305pub fn doctor(ctx: Ctx) !void {306    output.doctorHeader(ctx.machine.name);307    const checks = try exec.runDoctorChecks(ctx.gpa, ctx.io, &ctx.machine);308    defer ctx.gpa.free(checks);309    var warnings: u32 = 0;310    var failures: u32 = 0;311    for (checks) |ch| {312        output.doctorRow(ch);313        if (ch.status == .warn) warnings += 1;314        if (ch.status == .fail) failures += 1;315    }316317    // Home Manager row only when present — absent on a machine without HM, so318    // doctor's table is unchanged there.319    const hm_mode = exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ);320    if (hm_mode != .none) {321        const note = homeDoctorNote(ctx, hm_mode);322        defer ctx.gpa.free(note);323        output.doctorRow(.{ .name = "home manager", .status = .ok, .note = note });324    }325326    output.doctorSummary(warnings, failures);327}328329// "standalone  gen 765" / "module" — the note shown in doctor's home manager row.330// Caller owns the returned slice.331fn homeDoctorNote(ctx: Ctx, mode: exec.HomeManagerMode) []const u8 {332    const label = switch (mode) {333        .standalone => "standalone",334        .module => "module",335        .none => "",336    };337    if (mode == .standalone) {338        const gen = homeCurrentGen(ctx);339        if (gen != 0)340            return std.fmt.allocPrint(ctx.gpa, "{s}  gen {d}", .{ label, gen }) catch341                (ctx.gpa.dupe(u8, label) catch "");342    }343    return ctx.gpa.dupe(u8, label) catch "";344}345346// nina update — kepr self-update for the nina binary itself.347pub fn update(ctx: Ctx) !void {348    output.updateSelfStart();349350    if (comptime std.mem.eql(u8, version.PLATFORM, "unsupported")) {351        output.updateSelfNoPlatform(@tagName(builtin.cpu.arch) ++ "-" ++ @tagName(builtin.os.tag));352        return error.Internal;353    }354355    const env_url = ctx.environ.get("NINA_UPDATE_SOURCE");356    const source_url = env_url orelse UPDATE_URL;357358    const body = exec.fetchUrl(ctx.gpa, ctx.io, source_url) catch |e| switch (e) {359        error.NetworkError, error.HttpError => {360            output.updateSelfNetworkError();361            return;362        },363        else => return e,364    };365    defer ctx.gpa.free(body);366367    const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, body, .{}) catch {368        output.printWarning("could not parse release metadata");369        return;370    };371    defer parsed.deinit();372373    const root = parsed.value;374    if (root != .object) {375        output.printWarning("malformed release metadata");376        return;377    }378379    const remote_ver = blk: {380        const v = root.object.get("version") orelse {381            output.printWarning("malformed release metadata");382            return;383        };384        break :blk switch (v) {385            .string => |s| s,386            else => {387                output.printWarning("malformed release metadata");388                return;389            },390        };391    };392    if (!remoteVersionNewer(version.VERSION, remote_ver)) {393        output.updateSelfCurrent(version.VERSION);394        return;395    }396397    const release_notes = try updateReleaseNotes(ctx.gpa, ctx.io, root, source_url, version.VERSION, remote_ver);398    defer ctx.gpa.free(release_notes);399400    output.updateSelfAvailable(version.VERSION, remote_ver);401    output.updateSelfReleaseNotes(release_notes);402    if (ctx.check) return;403404    var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;405    const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {406        errors.error_info.setMessage("could not determine install path", .{});407        return error.Internal;408    };409410    // When running from the nix store, defer to nix profile upgrade so nix411    // manages the transition (the store is read-only; binary replacement fails).412    // A NixOS system install also resolves into the store but isn't a profile413    // element, so check the profile to avoid a no-op `upgrade` — it updates with414    // the next nixos-rebuild instead.415    if (std.mem.startsWith(u8, install_path, "/nix/store/")) {416        const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);417        defer if (nina_element) |n| ctx.gpa.free(n);418        if (nina_element == null) {419            output.updateSelfSystemManaged();420            return;421        }422        const element = nina_element.?;423        output.updateSelfNixManaged(remote_ver);424        if (ctx.cfg.confirm and !output.confirm("")) return;425        // `nix profile upgrade` re-resolves the element's own originalUrl. The426        // archive install runs with --no-write-lock-file, so nix has nowhere to427        // persist the lock it takes at install time except baking it into that428        // originalUrl as a `?narHash=` pin — which then never changes no matter429        // how far kepr's HEAD moves. Upgrading against that pin is a permanent430        // no-op: exit 0, "upgrading from X to X", nothing installed. Remove and431        // re-add against the plain (unpinned) archive URL instead, so nix432        // actually re-resolves HEAD and picks up a fresh narHash.433        const remove_r = exec.capture(ctx.gpa, ctx.io, &ctx.machine, &.{ "nix", "profile", "remove", element }) catch {434            output.updateSelfNixFailed();435            return;436        };437        defer ctx.gpa.free(remove_r.stdout);438        defer ctx.gpa.free(remove_r.stderr);439        if (remove_r.exit_code != 0) {440            output.raw(remove_r.stdout);441            output.raw(remove_r.stderr);442            output.updateSelfNixFailed();443            return;444        }445        // Even against the plain unpinned URL, nix caches its resolution for446        // `tarball-ttl` seconds (default 3600) regardless of HTTP cache-control447        // headers — so within an hour of any prior nix operation touching this448        // URL, add would silently reuse the stale narHash and reinstall the449        // same old version. --refresh forces nix to actually re-check HEAD.450        const add_r = exec.capture(ctx.gpa, ctx.io, &ctx.machine, &.{ "nix", "profile", "add", "--no-write-lock-file", "--refresh", FLAKE_URL }) catch {451            output.updateSelfNixReinstallFailed();452            return;453        };454        defer ctx.gpa.free(add_r.stdout);455        defer ctx.gpa.free(add_r.stderr);456        if (add_r.exit_code != 0) {457            output.raw(add_r.stdout);458            output.raw(add_r.stderr);459            output.updateSelfNixReinstallFailed();460            return;461        }462        output.updateSelfDone(version.VERSION, remote_ver);463        output.updateSelfNixRehash();464        return;465    }466467    const plat_info = blk: {468        const pv = root.object.get("platforms") orelse break :blk null;469        if (pv != .object) break :blk null;470        break :blk pv.object.get(version.PLATFORM);471    };472    if (plat_info == null) {473        output.updateSelfNoPlatform(version.PLATFORM);474        return;475    }476477    const dl_url = blk: {478        const v = plat_info.?.object.get("url") orelse {479            output.printWarning("malformed release metadata");480            return;481        };482        break :blk switch (v) {483            .string => |s| s,484            else => {485                output.printWarning("malformed release metadata");486                return;487            },488        };489    };490491    const raw_cksum = blk: {492        if (plat_info.?.object.get("blake3")) |v|493            break :blk switch (v) {494                .string => |s| s,495                else => {496                    output.printWarning("malformed release metadata");497                    return;498                },499            };500        if (plat_info.?.object.get("checksum")) |v|501            break :blk switch (v) {502                .string => |s| s,503                else => {504                    output.printWarning("malformed release metadata");505                    return;506                },507            };508        output.printWarning("missing checksum in release metadata");509        return;510    };511    const expected_hex = if (std.mem.startsWith(u8, raw_cksum, "blake3:")) raw_cksum["blake3:".len..] else raw_cksum;512513    if (ctx.cfg.confirm and !output.confirm("")) return;514515    output.updateSelfDownloading(remote_ver, version.PLATFORM);516    const tmp_path = exec.downloadToTemp(ctx.gpa, ctx.io, dl_url) catch {517        output.printWarning("download failed — check your connection and try again");518        return;519    };520    defer ctx.gpa.free(tmp_path);521522    output.updateSelfVerifying();523    exec.verifyAndInstall(ctx.gpa, ctx.io, tmp_path, expected_hex, install_path) catch |e| switch (e) {524        error.ChecksumMismatch => {525            output.updateSelfChecksumFailed();526            return;527        },528        else => return e,529    };530531    output.updateSelfDone(version.VERSION, remote_ver);532}533534// archives.json covers every version between current and latest; the manifest's535// `notes` field only ever describes the single latest release. Try the full-range536// changelog first so an update spanning several versions doesn't collapse down to537// just the newest one's notes — fall back to `notes` only when the archive has538// nothing (e.g. releases predating archives.json, or the fetch failing).539fn updateReleaseNotes(gpa: std.mem.Allocator, io: std.Io, root: std.json.Value, source_url: []const u8, current: []const u8, latest: []const u8) ![]u8 {540    if (buildKeprArchiveReleaseNotes(gpa, io, source_url, current, latest) catch null) |notes| {541        if (std.mem.trim(u8, notes, " \t\r\n").len > 0) return notes;542        gpa.free(notes);543    }544    if (releaseNotesFromMetadata(gpa, root)) |notes| return notes;545    return gpa.dupe(u8, "");546}547548fn releaseNotesFromMetadata(gpa: std.mem.Allocator, root: std.json.Value) ?[]u8 {549    if (root != .object) return null;550    // `notes` is the one canonical manifest field. The retired `release_notes`551    // and `changelog` fallbacks are gone — Kepr now emits `notes` everywhere, and552    // releases that predate `--notes` fall back to archives.json in the caller.553    const v = root.object.get("notes") orelse return null;554    return switch (v) {555        .string => |s| gpa.dupe(u8, s) catch null,556        else => null,557    };558}559560fn buildKeprArchiveReleaseNotes(gpa: std.mem.Allocator, io: std.Io, source_url: []const u8, current: []const u8, latest: []const u8) ![]u8 {561    const archive_url = try keprArchiveUrl(gpa, source_url);562    defer gpa.free(archive_url);563564    const body = exec.fetchUrl(gpa, io, archive_url) catch return gpa.dupe(u8, "");565    defer gpa.free(body);566567    return releaseNotesFromArchiveJson(gpa, body, current, latest);568}569570fn keprArchiveUrl(gpa: std.mem.Allocator, source_url: []const u8) ![]u8 {571    const scheme = std.mem.indexOf(u8, source_url, "://") orelse return error.InvalidUpdateSource;572    const path_start = std.mem.indexOfScalarPos(u8, source_url, scheme + 3, '/') orelse return error.InvalidUpdateSource;573    const origin = source_url[0..path_start];574    const path = source_url[path_start..];575    if (!std.mem.startsWith(u8, path, "/api/")) return error.InvalidUpdateSource;576577    const after_api = path["/api/".len..];578    const repo_end = std.mem.indexOfScalar(u8, after_api, '/') orelse return error.InvalidUpdateSource;579    const repo = after_api[0..repo_end];580    if (repo.len == 0) return error.InvalidUpdateSource;581582    return std.fmt.allocPrint(gpa, "{s}/{s}/archives.json?limit=100", .{ origin, repo });583}584585// Saves arrive newest-first. For each version in the update range we want the OLDEST586// save message (the one that introduced that version), not a follow-up cleanup/docs save.587// We overwrite the tracked message on each occurrence, so the final stored value per588// version is always the oldest (last-seen in a newest-first stream).589fn releaseNotesFromArchiveJson(gpa: std.mem.Allocator, body: []const u8, current: []const u8, latest: []const u8) ![]u8 {590    const parsed = std.json.parseFromSlice(std.json.Value, gpa, body, .{}) catch return gpa.dupe(u8, "");591    defer parsed.deinit();592593    if (parsed.value != .object) return gpa.dupe(u8, "");594    const saves_v = parsed.value.object.get("saves") orelse return gpa.dupe(u8, "");595    if (saves_v != .array) return gpa.dupe(u8, "");596597    // version string → oldest message seen (both slice into parsed JSON, valid until deinit)598    var best_msg = std.StringHashMap([]const u8).init(gpa);599    defer best_msg.deinit();600    var order: std.ArrayList([]const u8) = .empty;601    defer order.deinit(gpa);602603    for (saves_v.array.items) |save| {604        if (save != .object) continue;605        const ver_v = save.object.get("version") orelse continue;606        const msg_v = save.object.get("message") orelse continue;607        if (ver_v != .string or msg_v != .string) continue;608        const ver = ver_v.string;609        const msg = std.mem.trim(u8, msg_v.string, " \t\r\n");610        if (msg.len == 0 or !versionInUpdateRange(ver, current, latest)) continue;611612        const entry = try best_msg.getOrPut(ver);613        if (!entry.found_existing) try order.append(gpa, ver);614        // Always overwrite: saves are newest-first, so last write = oldest save = version-intro message615        entry.value_ptr.* = msg;616    }617618    if (order.items.len == 0) return gpa.dupe(u8, "");619620    var out: std.ArrayList(u8) = .empty;621    errdefer out.deinit(gpa);622    for (order.items) |ver| {623        const msg = best_msg.get(ver).?;624        // Use only the first line as the summary; multi-line saves may have implementation details below625        const summary_end = std.mem.indexOf(u8, msg, "\n") orelse msg.len;626        const summary = std.mem.trim(u8, msg[0..summary_end], " \t\r");627        if (summary.len == 0) continue;628        try appendLine(&out, gpa, "## {s}\n", .{ver});629        try appendLine(&out, gpa, "- {s}\n\n", .{summary});630    }631632    if (out.items.len == 0) {633        out.deinit(gpa);634        return gpa.dupe(u8, "");635    }636    return out.toOwnedSlice(gpa);637}638639fn appendLine(out: *std.ArrayList(u8), gpa: std.mem.Allocator, comptime template: []const u8, args: anytype) !void {640    const line = try std.fmt.allocPrint(gpa, template, args);641    defer gpa.free(line);642    try out.appendSlice(gpa, line);643}644645fn versionInUpdateRange(candidate: []const u8, current: []const u8, latest: []const u8) bool {646    const cand = parseSemver(candidate) orelse return std.mem.eql(u8, candidate, latest);647    const cur = parseSemver(current) orelse return std.mem.eql(u8, candidate, latest);648    const lat = parseSemver(latest) orelse return std.mem.eql(u8, candidate, latest);649    return compareSemver(cand, cur) == .gt and compareSemver(cand, lat) != .gt;650}651652fn remoteVersionNewer(current: []const u8, remote: []const u8) bool {653    const cur = parseSemver(current) orelse return !std.mem.eql(u8, current, remote);654    const rem = parseSemver(remote) orelse return !std.mem.eql(u8, current, remote);655    return compareSemver(rem, cur) == .gt;656}657658const VersionOrder = enum { lt, eq, gt };659660fn compareSemver(a: Semver, b: Semver) VersionOrder {661    if (a.major != b.major) return if (a.major < b.major) .lt else .gt;662    if (a.minor != b.minor) return if (a.minor < b.minor) .lt else .gt;663    if (a.patch != b.patch) return if (a.patch < b.patch) .lt else .gt;664    return .eq;665}666667fn parseSemver(raw: []const u8) ?Semver {668    const v = if (std.mem.startsWith(u8, raw, "v")) raw[1..] else raw;669    var it = std.mem.splitScalar(u8, v, '.');670    const major_s = it.next() orelse return null;671    const minor_s = it.next() orelse return null;672    const patch_s = it.next() orelse return null;673    if (it.next() != null) return null;674    return .{675        .major = std.fmt.parseInt(u32, major_s, 10) catch return null,676        .minor = std.fmt.parseInt(u32, minor_s, 10) catch return null,677        .patch = std.fmt.parseInt(u32, patch_s, 10) catch return null,678    };679}680681test "versionInUpdateRange includes only newer versions through latest" {682    try std.testing.expect(versionInUpdateRange("3.2.3", "3.1.9", "3.2.3"));683    try std.testing.expect(versionInUpdateRange("3.2.0", "3.1.9", "3.2.3"));684    try std.testing.expect(!versionInUpdateRange("3.1.9", "3.1.9", "3.2.3"));685    try std.testing.expect(!versionInUpdateRange("3.2.4", "3.1.9", "3.2.3"));686}687688test "remoteVersionNewer does not offer downgrades" {689    try std.testing.expect(remoteVersionNewer("3.2.3", "3.2.4"));690    try std.testing.expect(!remoteVersionNewer("3.2.4", "3.2.3"));691    try std.testing.expect(!remoteVersionNewer("3.2.4", "3.2.4"));692}693694test "releaseNotesFromArchiveJson uses oldest save per version" {695    // Saves arrive newest-first. For 3.2.3, the newest save is a CONTINUITY update;696    // the oldest is the version-intro message. We expect the intro message in the output.697    const body =698        \\{699        \\  "saves": [700        \\    {"version":"3.2.3","message":"wip: record verification in CONTINUITY"},701        \\    {"version":"3.2.1","message":"old release"},702        \\    {"version":"3.2.3","message":"add streaming deflate path"}703        \\  ]704        \\}705    ;706    const notes = try releaseNotesFromArchiveJson(std.testing.allocator, body, "3.2.1", "3.2.3");707    defer std.testing.allocator.free(notes);708709    try std.testing.expect(std.mem.indexOf(u8, notes, "## 3.2.3") != null);710    try std.testing.expect(std.mem.indexOf(u8, notes, "- add streaming deflate path") != null);711    try std.testing.expect(std.mem.indexOf(u8, notes, "CONTINUITY") == null);712    try std.testing.expect(std.mem.indexOf(u8, notes, "old release") == null);713}714715test "releaseNotesFromMetadata reads canonical notes and ignores retired keys" {716    const a = std.testing.allocator;717718    // Canonical field is read.719    {720        var parsed = try std.json.parseFromSlice(std.json.Value, a, "{\"notes\":\"colored progress bar\"}", .{});721        defer parsed.deinit();722        const got = releaseNotesFromMetadata(a, parsed.value).?;723        defer a.free(got);724        try std.testing.expectEqualStrings("colored progress bar", got);725    }726727    // Retired field names are no longer honoured — they fall through to null so728    // the caller drops to the archives.json derivation instead.729    {730        var parsed = try std.json.parseFromSlice(std.json.Value, a, "{\"release_notes\":\"x\",\"changelog\":\"y\"}", .{});731        defer parsed.deinit();732        try std.testing.expect(releaseNotesFromMetadata(a, parsed.value) == null);733    }734}735736// nina goodbye — clean uninstall. Three install paths:737// - nix profile (binary in nix store with a profile element) → nix profile remove738// - koh build or source build (plain binary on PATH) → delete the file739pub fn goodbye(ctx: Ctx) !void {740    output.goodbyeStart();741742    var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;743    const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {744        errors.error_info.setMessage("could not determine install path", .{});745        return error.Internal;746    };747748    // A binary outside the nix store is a koh build or source build — delete it.749    if (!std.mem.startsWith(u8, install_path, "/nix/store/")) {750        output.goodbyeFile(install_path);751        if (ctx.cfg.confirm and !output.confirm("")) return;752        std.Io.Dir.deleteFileAbsolute(ctx.io, install_path) catch |e| {753            errors.error_info.setMessage("could not remove {s}", .{install_path});754            return e;755        };756        output.goodbyeDone();757        return;758    }759760    // Binary is in the nix store — find and remove the profile element.761    const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);762    defer {763        if (nina_element) |n| ctx.gpa.free(n);764    }765766    if (nina_element == null) {767        errors.error_info.setMessage("nina not found in nix profile — was it installed via 'nix profile add'?", .{});768        return error.Internal;769    }770771    output.goodbyeNix();772    if (ctx.cfg.confirm and !output.confirm("")) return;773    const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "remove", nina_element.? }) catch {774        output.goodbyeFailed("nix profile remove failed");775        return;776    };777    if (ec != 0) {778        output.goodbyeFailed("nix profile remove failed");779        return;780    }781    output.goodbyeDone();782}783784fn channelUpdateCmd(ctx: Ctx) !void {785    output.updateStart(ctx.machine.name);786    _ = try exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa);787    output.updateDone();788}789790pub fn upgrade(ctx: Ctx) !void {791    if (!try runPreHook(ctx, "pre-upgrade")) {792        output.aborted();793        return error.HookAborted;794    }795796    output.upgradeStart(ctx.machine.name);797    // Flake systems update inputs (flake.lock); channel systems update channels.798    // Running nix-channel --update on a flake system is a no-op at best. The799    // rebuild below is already flake-aware via exec.nixosRebuildSwitch.800    if (flakeSystem(ctx)) {801        output.printSubstep("updating flake inputs", .{});802        _ = exec.flakeUpdateAt(ctx.io, &ctx.machine, ctx.gpa, ctx.machine.config_path) catch {};803    } else {804        output.printSubstep("updating channels", .{});805        _ = exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa) catch {};806    }807    output.printSubstep("rebuilding", .{});808    output.buildPanelInit();809    const start = std.Io.Clock.awake.now(ctx.io);810    var panel = output.BuildPanel{};811    const code = exec.nixosRebuildSwitchWithPanel(ctx.io, &ctx.machine, ctx.gpa, &panel) catch |e| {812        output.buildPanelClear();813        return e;814    };815    output.buildPanelClear();816    if (code != 0) {817        output.applyFailed("");818        return error.BuildFailed;819    }820    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());821    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));822    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;823    output.applyDone(gen, elapsed, false);824    runPostHook(ctx, "post-upgrade");825}826827pub fn log(ctx: Ctx) !void {828    output.logHeader(ctx.machine.name);829    const content = exec.readNinaLog(ctx.gpa, ctx.io, ctx.environ, ctx.last) catch {830        // No log yet — that's fine831        return;832    };833    defer ctx.gpa.free(content);834    var lines = std.mem.splitScalar(u8, content, '\n');835    while (lines.next()) |line| {836        const t = std.mem.trim(u8, line, " \t\r");837        if (t.len == 0) continue;838        if (t[0] == '{') {839            renderJsonLogLine(ctx.gpa, t);840        } else {841            // legacy tab-separated format842            var parts = std.mem.tokenizeScalar(u8, t, '\t');843            const date = parts.next() orelse continue;844            const time = parts.next() orelse "";845            const action = parts.next() orelse "";846            const detail = parts.next() orelse "";847            output.logRow(date, time, action, detail);848        }849    }850}851852// The on-disk log is JSON Lines: {"ts","machine","command","outcome","gen_after",...}.853// Render ts -> date/time columns, command -> action, outcome(+gen) -> detail.854fn renderJsonLogLine(gpa: std.mem.Allocator, line: []const u8) void {855    const parsed = std.json.parseFromSlice(std.json.Value, gpa, line, .{}) catch {856        output.logRow(line, "", "", ""); // unparseable — show raw rather than drop857        return;858    };859    defer parsed.deinit();860    if (parsed.value != .object) return;861    const o = parsed.value.object;862863    const ts = jsonStr(o, "ts");864    const date = if (ts.len >= 10) ts[0..10] else ts;865    const time = if (ts.len >= 16) ts[11..16] else "";866    const action = jsonStr(o, "command");867    const outcome = jsonStr(o, "outcome");868869    var buf: [160]u8 = undefined;870    var detail: []const u8 = outcome;871    if (o.get("gen_after")) |g| {872        if (g == .integer) {873            detail = std.fmt.bufPrint(&buf, "{s}   -> gen {d}", .{ outcome, g.integer }) catch outcome;874        }875    }876    output.logRow(date, time, action, detail);877}878879fn jsonStr(o: std.json.ObjectMap, key: []const u8) []const u8 {880    if (o.get(key)) |v| {881        if (v == .string) return v.string;882    }883    return "";884}885886pub fn edit(ctx: Ctx) !void {887    // `edit` is multi-word, so a bare positional ("hardware") arrives as ctx.sub.888    // hardware-configuration.nix is generated by nixos-generate-config and warns889    // against hand-editing — refuse rather than silently opening the wrong file.890    if (std.mem.eql(u8, ctx.sub, "hardware")) {891        output.editHardwareWarning();892        return;893    }894895    // --dir opens the whole config directory (for editors that work better with896    // a folder open), as root so root-owned config trees like /etc/nixos work.897    var open_dir = false;898    for (ctx.args) |arg| {899        if (std.mem.eql(u8, arg, "--dir")) open_dir = true;900    }901    if (open_dir) {902        output.editOpen(ctx.machine.config_path, ctx.cfg.editor);903        _ = try exec.openEditorSudo(ctx.io, ctx.gpa, ctx.cfg.editor, ctx.machine.config_path);904        return;905    }906907    const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});908    defer ctx.gpa.free(path);909    output.editOpen(path, ctx.cfg.editor);910    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);911}912913pub fn fmt(ctx: Ctx) !void {914    const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});915    defer ctx.gpa.free(path);916    if (ctx.check) {917        const code = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, true);918        if (code != 0) output.fmtNeedsFormat() else output.fmtDone();919        return;920    }921    output.fmtStart(path);922    _ = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, false);923    output.fmtDone();924}925926pub fn repl(ctx: Ctx) !void {927    output.replStart();928    _ = try exec.nixRepl(ctx.io, &ctx.machine, ctx.gpa);929}930931pub fn develop(ctx: Ctx) !void {932    if (std.mem.eql(u8, ctx.sub, "show")) {933        _ = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, null);934        return;935    }936    const run_cmd: ?[]const u8 = if (ctx.args.len > 0 and std.mem.eql(u8, ctx.sub, "run"))937        ctx.args[0]938    else939        null;940    output.developStart(&.{});941    _ = try exec.nixDevelopPs1(ctx.io, &ctx.machine, ctx.gpa, run_cmd, ctx.environ);942    output.developDone();943}944945pub fn info(ctx: Ctx) !void {946    output.infoHeader(ctx.machine.name);947    const nixos_ver = exec.systemInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");948    defer ctx.gpa.free(nixos_ver);949    output.infoRow("nixos", std.mem.trim(u8, nixos_ver, " \t\n\r"));950951    const kernel = exec.kernelInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");952    defer ctx.gpa.free(kernel);953    output.infoRow("kernel", std.mem.trim(u8, kernel, " \t\n\r"));954955    const uptime = exec.uptimeInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");956    defer ctx.gpa.free(uptime);957    output.infoRow("uptime", std.mem.trim(u8, uptime, " \t\n\r"));958}959960pub fn boot(ctx: Ctx) !void {961    output.bootHeader(ctx.machine.name);962    const entries = exec.bootEntries(ctx.gpa, ctx.io, &ctx.machine) catch &.{};963    defer ctx.gpa.free(entries);964    for (entries, 0..) |entry, i| output.bootEntry(entry, i);965}966967pub fn searchCmd(ctx: Ctx) !void {968    const query = if (ctx.args.len > 0) ctx.args[0] else "";969    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);970    const selected = try search_tui.run(ctx.gpa, ctx.io, query, .packages, ctx.environ);971    if (selected) |npkg| try selectAndInstall(ctx, npkg);972}973974pub fn optionCmd(ctx: Ctx) !void {975    const query = if (ctx.args.len > 0) ctx.args[0] else "";976    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);977    _ = try search_tui.run(ctx.gpa, ctx.io, query, .options, ctx.environ);978}979980pub fn install(ctx: Ctx) !void {981    const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;982983    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);984985    // Search for the package to get the attr986    const pkgs = api.searchPackages(ctx.gpa, ctx.io, ctx.environ, pkg_name) catch {987        errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});988        errors.error_info.setSuggestion("nina search {s}", .{pkg_name});989        return error.PackageNotFound;990    };991992    if (pkgs.len == 0) {993        // No matches — likely a typo. Suggest the closest real package and offer it.994        if (closestPackage(ctx, pkg_name)) |sugg| {995            output.didYouMean(pkg_name, sugg.pname);996            if (output.confirm("")) try selectAndInstall(ctx, sugg);997            return;998        }999        errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});1000        errors.error_info.setSuggestion("nina search {s}", .{pkg_name});1001        return error.PackageNotFound;1002    }10031004    // Prefer an exact name match over the first search result — `install ripgrep`1005    // must pick "ripgrep", not the alphabetically-first match like "repgrep".1006    var found = pkgs[0];1007    for (pkgs) |p| {1008        if (std.mem.eql(u8, p.pname, pkg_name)) {1009            found = p;1010            break;1011        }1012    }1013    try selectAndInstall(ctx, found);1014}10151016// Find the real package whose name is closest to a not-found query (typo help).1017// Typos usually keep the leading characters, so gather candidates with a prefix1018// search and rank by edit distance; return the best only if it's typo-close.1019fn closestPackage(ctx: Ctx, query: []const u8) ?types.NixPackage {1020    if (query.len < 2) return null;1021    var candidates = api.searchPackages(ctx.gpa, ctx.io, ctx.environ, query[0..@min(query.len, 4)]) catch &.{};1022    if (candidates.len == 0 and query.len > 2) {1023        candidates = api.searchPackages(ctx.gpa, ctx.io, ctx.environ, query[0..2]) catch &.{};1024    }1025    if (candidates.len == 0) return null;10261027    var best: ?types.NixPackage = null;1028    var best_dist: usize = std.math.maxInt(usize);1029    for (candidates) |p| {1030        const d = editDistance(query, p.pname);1031        if (d > 0 and d < best_dist) {1032            best_dist = d;1033            best = p;1034        }1035    }1036    // Only suggest a genuinely close name, scaled to query length.1037    const threshold = @max(@as(usize, 2), query.len / 3);1038    return if (best_dist <= threshold) best else null;1039}10401041// Case-insensitive Levenshtein distance. Names longer than the row buffer are1042// treated as far away (never suggested).1043fn editDistance(a: []const u8, b: []const u8) usize {1044    const n = b.len;1045    if (a.len == 0) return n;1046    if (n == 0) return a.len;1047    if (n + 1 > 128) return std.math.maxInt(usize);1048    var prev: [128]usize = undefined;1049    var curr: [128]usize = undefined;1050    var j: usize = 0;1051    while (j <= n) : (j += 1) prev[j] = j;1052    var i: usize = 1;1053    while (i <= a.len) : (i += 1) {1054        curr[0] = i;1055        j = 1;1056        while (j <= n) : (j += 1) {1057            const cost: usize = if (std.ascii.toLower(a[i - 1]) == std.ascii.toLower(b[j - 1])) 0 else 1;1058            curr[j] = @min(prev[j] + 1, @min(curr[j - 1] + 1, prev[j - 1] + cost));1059        }1060        @memcpy(prev[0 .. n + 1], curr[0 .. n + 1]);1061    }1062    return prev[n];1063}10641065test "editDistance is case-insensitive Levenshtein" {1066    try std.testing.expectEqual(@as(usize, 1), editDistance("firefux", "firefox"));1067    try std.testing.expectEqual(@as(usize, 0), editDistance("git", "GIT"));1068    try std.testing.expectEqual(@as(usize, 2), editDistance("fierfox", "firefox"));1069    try std.testing.expectEqual(@as(usize, 7), editDistance("", "firefox"));1070}10711072// Prompt for the install method (profile / system / try) and dispatch. Shared by1073// `nina install <pkg>` and the search widget's Enter-to-select — the letter keys1074// are read here, after the search widget's raw mode is gone, so they don't1075// collide with typing a query.1076fn selectAndInstall(ctx: Ctx, npkg: types.NixPackage) !void {1077    output.installSelectPrompt(npkg.pname, npkg.version);10781079    var choice_buf: [8]u8 = undefined;1080    var choice_len: usize = 0;1081    while (choice_len < choice_buf.len) {1082        const n = std.posix.read(std.posix.STDIN_FILENO, choice_buf[choice_len .. choice_len + 1]) catch break;1083        if (n == 0) break;1084        if (choice_buf[choice_len] == '\n') break;1085        choice_len += 1;1086    }1087    const choice = std.mem.trim(u8, choice_buf[0..choice_len], " \t");10881089    if (choice.len == 0 or choice[0] == 'i' or choice[0] == 'I') {1090        try profileInstallPkg(ctx, npkg);1091    } else if (choice[0] == 's' or choice[0] == 'S') {1092        try systemInstallPkg(ctx, npkg);1093    } else if (choice[0] == 't' or choice[0] == 'T') {1094        try tryPkg(ctx, npkg);1095    }1096}10971098fn profileInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {1099    output.installStart(npkg.pname, .profile);1100    if (npkg.unfree) {1101        output.printSubstep("NIXPKGS_ALLOW_UNFREE=1 nix profile add --impure nixpkgs#{s}", .{npkg.attr});1102        output.printTeach(try std.fmt.allocPrint(ctx.gpa, "NIXPKGS_ALLOW_UNFREE=1 nix profile add --impure nixpkgs#{s}", .{npkg.attr}));1103    } else {1104        output.printSubstep("nix profile add nixpkgs#{s}", .{npkg.attr});1105        output.printTeach(try std.fmt.allocPrint(ctx.gpa, "nix profile add nixpkgs#{s}", .{npkg.attr}));1106    }1107    const code = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, ctx.environ, npkg.attr, npkg.unfree);1108    if (code != 0) return error.ProcessFailed;1109    output.installDone(npkg.pname);1110}11111112fn systemInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {1113    const config_path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});1114    defer ctx.gpa.free(config_path);1115    const line = api.findSystemPackagesLine(ctx.io, config_path) orelse 1;1116    output.installEditorPrompt(npkg.pname, config_path, line, ctx.cfg.editor);1117    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, config_path, line);1118    if (ctx.cfg.confirm) {1119        if (output.confirm("apply now? ")) {1120            try apply(ctx);1121        }1122    }1123}11241125fn tryPkg(ctx: Ctx, npkg: types.NixPackage) !void {1126    output.tryStart(npkg.pname);1127    output.printSubstep("nix shell nixpkgs#{s}", .{npkg.attr});1128    output.tryExitHint();1129    _ = try exec.nixShellPs1(ctx.io, &ctx.machine, ctx.gpa, npkg.attr, ctx.environ);1130    output.tryDone();1131}11321133pub fn remove(ctx: Ctx) !void {1134    const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1135    output.removeStart(pkg_name);1136    const code = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, pkg_name);1137    if (code != 0) return error.ProcessFailed;1138    output.done();1139}11401141pub fn list(ctx: Ctx) !void {1142    output.listHeader(ctx.machine.name);11431144    // Profile packages: parse `nix profile list --json` into clean name+version1145    // rows instead of dumping nix's verbose multi-line "Name:/Flake attribute:"1146    // blocks.1147    if (exec.profileListJson(ctx.gpa, ctx.io, &ctx.machine) catch null) |json| {1148        defer ctx.gpa.free(json);1149        output.listSection("profile");1150        renderProfileJson(ctx.gpa, json);1151    }11521153    // System packages: the references of /run/current-system/sw, each a1154    // <hash>-<name>-<version> store path.1155    if (exec.systemPackagePaths(ctx.gpa, ctx.io, &ctx.machine) catch null) |paths| {1156        defer ctx.gpa.free(paths);1157        output.blankLine();1158        output.listSection("system");1159        var lines = std.mem.splitScalar(u8, paths, '\n');1160        while (lines.next()) |line| {1161            const t = std.mem.trim(u8, line, " \t\r");1162            if (t.len == 0) continue;1163            const row = pkgFromStorePath(t);1164            // Skip support paths with no parseable version (man pages, wrappers).1165            if (row.version.len == 0) continue;1166            output.listPkg(row.name, row.version);1167        }1168    }1169}11701171const PkgRow = struct { name: []const u8, version: []const u8 };11721173// Split a nix store path basename (<hash>-<name>-<version>) into name + version.1174// Version begins at the first '-' followed by a digit, which reliably lands on1175// the name/version boundary since the 32-char hash and package names start with1176// non-digits.1177fn pkgFromStorePath(path: []const u8) PkgRow {1178    const base = std.fs.path.basename(path);1179    const after_hash = if (base.len > 33 and base[32] == '-') base[33..] else base;1180    var i: usize = 0;1181    while (i + 1 < after_hash.len) : (i += 1) {1182        if (after_hash[i] == '-' and std.ascii.isDigit(after_hash[i + 1])) {1183            return .{ .name = after_hash[0..i], .version = stripOutputSuffix(after_hash[i + 1 ..]) };1184        }1185    }1186    return .{ .name = after_hash, .version = "" };1187}11881189// Multi-output derivations append the output name to the store path (e.g.1190// curl-8.20.0-bin, less-692-man). Strip that suffix so the version column reads1191// as just the version.1192fn stripOutputSuffix(ver: []const u8) []const u8 {1193    const suffixes = [_][]const u8{ "-bin", "-man", "-dev", "-doc", "-lib", "-info", "-out", "-static", "-devdoc" };1194    for (suffixes) |s| {1195        if (std.mem.endsWith(u8, ver, s)) return ver[0 .. ver.len - s.len];1196    }1197    return ver;1198}11991200test "pkgFromStorePath splits name and version at first dash-digit" {1201    const a = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-ripgrep-15.1.0");1202    try std.testing.expectEqualStrings("ripgrep", a.name);1203    try std.testing.expectEqualStrings("15.1.0", a.version);12041205    const b = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-helix-25.01");1206    try std.testing.expectEqualStrings("helix", b.name);1207    try std.testing.expectEqualStrings("25.01", b.version);12081209    // multi-output store paths drop their output-name suffix1210    const c = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-curl-8.20.0-bin");1211    try std.testing.expectEqualStrings("curl", c.name);1212    try std.testing.expectEqualStrings("8.20.0", c.version);1213}12141215fn firstStorePath(el: std.json.Value) ?[]const u8 {1216    if (el != .object) return null;1217    const sp = el.object.get("storePaths") orelse return null;1218    if (sp != .array or sp.array.items.len == 0) return null;1219    const first = sp.array.items[0];1220    return if (first == .string) first.string else null;1221}12221223// `nix profile list --json` has two shapes across nix versions: newer keys each1224// element by name (object), older lists them positionally (array). Handle both.1225fn renderProfileJson(gpa: std.mem.Allocator, json: []const u8) void {1226    const parsed = std.json.parseFromSlice(std.json.Value, gpa, json, .{}) catch return;1227    defer parsed.deinit();1228    if (parsed.value != .object) return;1229    const elements = parsed.value.object.get("elements") orelse return;1230    switch (elements) {1231        .object => |obj| {1232            var it = obj.iterator();1233            while (it.next()) |entry| {1234                const ver = if (firstStorePath(entry.value_ptr.*)) |p| pkgFromStorePath(p).version else "";1235                output.listPkg(entry.key_ptr.*, ver);1236            }1237        },1238        .array => |arr| {1239            for (arr.items) |el| {1240                const path = firstStorePath(el) orelse continue;1241                const row = pkgFromStorePath(path);1242                output.listPkg(row.name, row.version);1243            }1244        },1245        else => {},1246    }1247}12481249pub fn tryCmd(ctx: Ctx) !void {1250    const pkg_name_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1251    const shell_pkg = types.NixPackage{ .attr = pkg_name_arg, .pname = pkg_name_arg, .version = "", .description = "" };1252    try tryPkg(ctx, shell_pkg);1253}12541255// --- Home Manager commands ---12561257const home_help = [_][2][]const u8{1258    .{ "init", "set up home manager for the first time" },1259    .{ "init --switch", "set up and activate immediately" },1260    .{ "apply", "apply home-manager configuration" },1261    .{ "apply --dry", "preview changes without activating" },1262    .{ "back", "roll back one generation" },1263    .{ "history", "list all generations" },1264    .{ "edit", "open home.nix" },1265    .{ "check", "validate without applying" },1266    .{ "diff", "compare the latest two generations" },1267    .{ "packages", "list managed packages" },1268};12691270const HomeGen = struct {1271    number: u32,1272    date: []const u8,1273    time: []const u8,1274    path: []const u8,1275};12761277// `home-manager generations` lines read:1278//   2026-06-01 11:56 : id 765 -> /nix/store/<hash>-home-manager-generation1279// Newest first, so index 0 is the current generation.1280fn parseHomeGenerations(gpa: std.mem.Allocator, out_str: []const u8) ![]HomeGen {1281    var gens: std.ArrayList(HomeGen) = .empty;1282    var lines = std.mem.splitScalar(u8, out_str, '\n');1283    while (lines.next()) |line| {1284        const t = std.mem.trim(u8, line, " \t\r");1285        if (t.len == 0) continue;1286        var it = std.mem.tokenizeAny(u8, t, " \t");1287        const date = it.next() orelse continue;1288        const time = it.next() orelse continue;1289        var number: ?u32 = null;1290        var path: []const u8 = "";1291        while (it.next()) |tok| {1292            if (std.mem.eql(u8, tok, "id")) {1293                if (it.next()) |n| number = std.fmt.parseInt(u32, n, 10) catch null;1294            } else if (std.mem.startsWith(u8, tok, "/nix/store/")) {1295                path = tok;1296            }1297        }1298        const num = number orelse continue;1299        try gens.append(gpa, .{1300            .number = num,1301            .date = try gpa.dupe(u8, date),1302            .time = try gpa.dupe(u8, time),1303            .path = try gpa.dupe(u8, path),1304        });1305    }1306    return gens.toOwnedSlice(gpa);1307}13081309fn freeHomeGens(gpa: std.mem.Allocator, gens: []HomeGen) void {1310    for (gens) |g| {1311        gpa.free(g.date);1312        gpa.free(g.time);1313        gpa.free(g.path);1314    }1315    gpa.free(gens);1316}13171318test "parseHomeGenerations reads id, date and store path" {1319    const a = std.testing.allocator;1320    const sample =1321        \\2026-06-01 11:56 : id 765 -> /nix/store/aaaa-home-manager-generation1322        \\2026-05-31 10:29 : id 764 -> /nix/store/bbbb-home-manager-generation1323    ;1324    const gens = try parseHomeGenerations(a, sample);1325    defer freeHomeGens(a, gens);1326    try std.testing.expectEqual(@as(usize, 2), gens.len);1327    try std.testing.expectEqual(@as(u32, 765), gens[0].number);1328    try std.testing.expectEqualStrings("2026-06-01", gens[0].date);1329    try std.testing.expectEqualStrings("11:56", gens[0].time);1330    try std.testing.expectEqualStrings("/nix/store/aaaa-home-manager-generation", gens[0].path);1331    try std.testing.expectEqual(@as(u32, 764), gens[1].number);1332}13331334// Current (newest) home generation number, or 0 if unavailable.1335fn homeCurrentGen(ctx: Ctx) u32 {1336    const out = exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine) catch return 0;1337    defer ctx.gpa.free(out);1338    const gens = parseHomeGenerations(ctx.gpa, out) catch return 0;1339    defer freeHomeGens(ctx.gpa, gens);1340    return if (gens.len > 0) gens[0].number else 0;1341}13421343pub fn home(ctx: Ctx) !void {1344    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help"))1345        return output.subcommandHelp("home", &home_help, null);13461347    // Home Manager manages the local user's environment. Detection (which binary,1348    // ~/.config/home-manager, $HOME/$USER for the flake ref) all read the LOCAL1349    // host, while exec routes over SSH for a remote machine — so `home --on1350    // <remote>` would decide mode/flake-ref from the wrong box. Refuse it cleanly1351    // rather than acting on a mismatch.1352    if (!ctx.machine.local) {1353        output.homeLocalOnly(ctx.machine.name);1354        return;1355    }13561357    // init runs before mode detection: its whole purpose is bootstrapping a host1358    // that has no home-manager yet, so a .none mode must not short-circuit it.1359    if (std.mem.eql(u8, ctx.sub, "init")) return homeInitCmd(ctx);13601361    const mode = exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ);1362    if (mode == .none) {1363        output.homeNotInstalled();1364        return;1365    }13661367    // apply is the only command meaningful in module mode (it redirects to1368    // `nina apply`); everything else needs the standalone home-manager CLI.1369    if (std.mem.eql(u8, ctx.sub, "apply")) return homeApply(ctx, mode);1370    // edit just opens the local home.nix — fine in module mode too.1371    if (std.mem.eql(u8, ctx.sub, "edit")) return homeEdit(ctx);13721373    if (mode == .module) {1374        output.homeModuleManaged();1375        return;1376    }13771378    if (std.mem.eql(u8, ctx.sub, "back")) return homeBack(ctx);1379    if (std.mem.eql(u8, ctx.sub, "history")) return homeHistory(ctx);1380    if (std.mem.eql(u8, ctx.sub, "check")) return homeCheck(ctx);1381    if (std.mem.eql(u8, ctx.sub, "diff")) return homeDiff(ctx);1382    if (std.mem.eql(u8, ctx.sub, "packages")) return homePackages(ctx);13831384    return output.subcommandHelp("home", &home_help, null);1385}13861387fn homePackages(ctx: Ctx) !void {1388    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1389    defer ctx.gpa.free(out);1390    const gens = try parseHomeGenerations(ctx.gpa, out);1391    defer freeHomeGens(ctx.gpa, gens);13921393    output.homePackagesHeader(ctx.machine.name);1394    if (gens.len == 0 or gens[0].path.len == 0) return;13951396    // The generation's OWN references are home-manager's activation deps1397    // (bash, coreutils, ...), not what the user installed. The user's packages1398    // live one level down, in the `…-home-manager-path` env the generation1399    // references — descend into it and list ITS references. Fall back to the1400    // generation refs if that env isn't present (older home-manager layouts).1401    const gen_refs = exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, gens[0].path) catch return;1402    defer ctx.gpa.free(gen_refs);14031404    var refs = gen_refs;1405    var env_refs: ?[]u8 = null;1406    defer if (env_refs) |e| ctx.gpa.free(e);1407    if (findHomeManagerPath(gen_refs)) |pkg_path| {1408        if (exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, pkg_path)) |e| {1409            env_refs = e;1410            refs = e;1411        } else |_| {}1412    }14131414    // Dedup by name: multi-output derivations (jq, jq-lib, jq-doc) collapse to1415    // the same name after the output suffix is stripped. Keys are slices into1416    // `refs`, valid for this function's lifetime.1417    var seen = std.StringHashMap(void).init(ctx.gpa);1418    defer seen.deinit();1419    var lines = std.mem.splitScalar(u8, refs, '\n');1420    while (lines.next()) |line| {1421        const t = std.mem.trim(u8, line, " \t\r");1422        if (t.len == 0) continue;1423        const row = pkgFromStorePath(t);1424        if (row.version.len == 0) continue;1425        if (std.mem.indexOf(u8, row.name, "home-manager") != null) continue;1426        if (seen.contains(row.name)) continue;1427        seen.put(row.name, {}) catch {};1428        output.listPkg(row.name, row.version);1429    }1430}14311432// The `…-home-manager-path` env among a generation's references — the buildEnv1433// of the user's home.packages. Returns the full store-path line, or null.1434fn findHomeManagerPath(refs: []const u8) ?[]const u8 {1435    var lines = std.mem.splitScalar(u8, refs, '\n');1436    while (lines.next()) |line| {1437        const t = std.mem.trim(u8, line, " \t\r");1438        if (std.mem.indexOf(u8, t, "home-manager-path") != null) return t;1439    }1440    return null;1441}14421443test "findHomeManagerPath picks the env, not the generation or infra" {1444    const refs =1445        \\/nix/store/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-bash-5.31446        \\/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path1447        \\/nix/store/cccccccccccccccccccccccccccccccc-coreutils-9.111448    ;1449    try std.testing.expectEqualStrings(1450        "/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path",1451        findHomeManagerPath(refs).?,1452    );1453    try std.testing.expectEqual(@as(?[]const u8, null), findHomeManagerPath("/nix/store/x-bash-5.3\n"));1454}14551456fn homeDiff(ctx: Ctx) !void {1457    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1458    defer ctx.gpa.free(out);1459    const gens = try parseHomeGenerations(ctx.gpa, out);1460    defer freeHomeGens(ctx.gpa, gens);14611462    // Need two generations and both their store paths to diff their closures.1463    if (gens.len < 2 or gens[0].path.len == 0 or gens[1].path.len == 0) {1464        output.homeNothingToDiff();1465        return;1466    }1467    const newer = gens[0];1468    const older = gens[1];1469    output.homeDiffHeader(older.number, newer.number, ctx.machine.name);1470    if (try exec.diffClosuresPaths(ctx.io, &ctx.machine, ctx.gpa, older.path, newer.path) != 0)1471        return error.ProcessFailed;1472}14731474fn homeCheck(ctx: Ctx) !void {1475    output.homeCheckStart(ctx.machine.name);1476    const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa);1477    if (code != 0) return error.BuildFailed;1478    output.homeCheckOk();1479}14801481fn homeEdit(ctx: Ctx) !void {1482    // Standalone home config lives at ~/.config/home-manager/home.nix; the same1483    // path is what detection keys on for module mode, so it resolves for both.1484    const path = exec.homeNixPath(ctx.gpa, ctx.environ) orelse {1485        errors.error_info.setMessage("could not resolve ~/.config/home-manager/home.nix", .{});1486        return error.ConfigNotFound;1487    };1488    defer ctx.gpa.free(path);1489    output.homeEditOpen(path, ctx.cfg.editor);1490    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);1491}14921493fn homeHistory(ctx: Ctx) !void {1494    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1495    defer ctx.gpa.free(out);1496    const gens = try parseHomeGenerations(ctx.gpa, out);1497    defer freeHomeGens(ctx.gpa, gens);1498    output.homeHistoryHeader(ctx.machine.name);1499    // Newest-first from home-manager; the first row is the current generation.1500    for (gens, 0..) |g, i| output.homeHistoryRow(g.number, g.date, g.time, i == 0);1501}15021503fn homeBack(ctx: Ctx) !void {1504    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1505    defer ctx.gpa.free(out);1506    const gens = try parseHomeGenerations(ctx.gpa, out);1507    defer freeHomeGens(ctx.gpa, gens);15081509    // Newest-first: [0] is current, [1] is the generation to roll back to.1510    if (gens.len < 2) {1511        output.alreadyOldest();1512        return;1513    }1514    const current = gens[0].number;1515    const prev = gens[1].number;15161517    output.homeBackStart(ctx.machine.name, current, prev);1518    if (ctx.cfg.confirm and !output.confirm("")) return;1519    const code = try exec.homeManagerRollback(ctx.io, &ctx.machine, ctx.gpa);1520    if (code != 0) return error.BuildFailed;1521    output.homeBackDone(prev);1522}15231524fn homeInitCmd(ctx: Ctx) !void {1525    var switch_on_init = false;1526    var dir: ?[]const u8 = null;1527    for (ctx.args) |arg| {1528        if (std.mem.eql(u8, arg, "--switch")) {1529            switch_on_init = true;1530        } else if (!std.mem.startsWith(u8, arg, "-")) {1531            dir = arg;1532        }1533    }15341535    // Guard only the default location — a custom dir is the user's call, and1536    // home-manager creates it. Never clobber an existing ~/.config/home-manager.1537    if (dir == null) {1538        if (exec.homeNixPath(ctx.gpa, ctx.environ)) |path| {1539            defer ctx.gpa.free(path);1540            if (exec.pathExists(ctx.io, path)) {1541                output.homeInitExists(path);1542                return;1543            }1544        }1545    }15461547    output.homeInitStart(switch_on_init, dir);1548    const code = try exec.homeManagerInit(ctx.io, &ctx.machine, ctx.gpa, switch_on_init, dir);1549    if (code != 0) return error.BuildFailed;1550    output.homeInitDone(switch_on_init);1551}15521553fn homeApply(ctx: Ctx, mode: exec.HomeManagerMode) !void {1554    // NixOS/flake module: home config is rebuilt by nixos-rebuild — redirect.1555    if (mode == .module) {1556        output.homeModuleManaged();1557        return;1558    }1559    if (ctx.dry) {1560        output.homeApplyDry(ctx.machine.name);1561        const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa);1562        if (code != 0) return error.BuildFailed;1563        output.homeApplyDryDone();1564        return;1565    }15661567    if (!try runPreHook(ctx, "pre-home")) {1568        output.aborted();1569        return error.HookAborted;1570    }15711572    output.homeApplyStart(ctx.machine.name);15731574    // Flake-based home config: switch by attribute with a graceful fallback1575    // chain. A channel-based config (no flake.nix) uses a plain switch.1576    const dir = exec.homeFlakeDir(ctx.gpa, ctx.io, ctx.environ);1577    defer if (dir) |d| ctx.gpa.free(d);1578    if (dir) |d| return homeApplyFlake(ctx, d);15791580    output.printSubstep("home-manager switch", .{});1581    const start = std.Io.Clock.awake.now(ctx.io);1582    const code = try exec.homeManagerSwitch(ctx.io, &ctx.machine, ctx.gpa);1583    if (code != 0) return error.BuildFailed;15841585    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());1586    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));1587    output.homeApplyDone(homeCurrentGen(ctx), elapsed);1588    runPostHook(ctx, "post-home");1589}15901591// Switch a flake-based home config, trying the most specific attribute first:1592//   <dir>#<user>-<arch>-<os>  →  <dir>#<user>  →  <dir>  (home-manager resolves)1593// Each fallback fires only on a missing-attribute error, never on a real build1594// failure. Mirrors how ${USER}-${system} homeConfigurations keys are written.1595fn homeApplyFlake(ctx: Ctx, dir: []const u8) !void {1596    const user = ctx.environ.get("USER") orelse "default";15971598    var refs: std.ArrayList([]const u8) = .empty;1599    defer {1600        for (refs.items) |r| ctx.gpa.free(r);1601        refs.deinit(ctx.gpa);1602    }1603    if (exec.homeManagerAttr(ctx.gpa, ctx.io, &ctx.machine, ctx.environ) catch null) |attr| {1604        defer ctx.gpa.free(attr);1605        try refs.append(ctx.gpa, try std.fmt.allocPrint(ctx.gpa, "{s}#{s}", .{ dir, attr }));1606    }1607    try refs.append(ctx.gpa, try std.fmt.allocPrint(ctx.gpa, "{s}#{s}", .{ dir, user }));1608    try refs.append(ctx.gpa, try ctx.gpa.dupe(u8, dir));16091610    const start = std.Io.Clock.awake.now(ctx.io);1611    for (refs.items, 0..) |ref, i| {1612        output.printSubstep("home-manager switch --flake {s}", .{ref});1613        switch (try exec.homeManagerSwitchFlake(ctx.io, &ctx.machine, ctx.gpa, ref)) {1614            .ok => {1615                const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());1616                const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));1617                output.homeApplyDone(homeCurrentGen(ctx), elapsed);1618                runPostHook(ctx, "post-home");1619                return;1620            },1621            // Attr not defined by the flake — drop to the next candidate.1622            .attr_missing => {1623                if (i + 1 < refs.items.len) output.homeAttrFallback(ref);1624                continue;1625            },1626            .failed => return error.BuildFailed,1627        }1628    }1629    return error.BuildFailed;1630}16311632// --- Service commands ---16331634const service_help = [_][2][]const u8{1635    .{ "list", "list running services" },1636    .{ "logs <svc>", "show service logs" },1637    .{ "status <svc>", "service status" },1638    .{ "start <svc>", "start a service" },1639    .{ "stop <svc>", "stop a service" },1640    .{ "restart <svc>", "restart a service" },1641    .{ "enable <svc>", "enable at boot" },1642    .{ "disable <svc>", "disable at boot" },1643};16441645pub fn service(ctx: Ctx) !void {1646    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");1647    if (std.mem.eql(u8, ctx.sub, "list")) {1648        output.serviceListHeader(ctx.machine.name);1649        const svcs = exec.serviceList(ctx.gpa, ctx.io, &ctx.machine, ctx.user) catch &.{};1650        defer ctx.gpa.free(svcs);1651        for (svcs) |s| output.serviceRow(s);1652        return;1653    }1654    if (std.mem.eql(u8, ctx.sub, "logs")) {1655        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1656        const follow = ctx.args.len > 1 and std.mem.eql(u8, ctx.args[1], "-f");1657        output.serviceLogsHeader(name, ctx.last, ctx.machine.name);1658        _ = try exec.serviceLogs(ctx.io, &ctx.machine, ctx.gpa, name, ctx.last, follow, ctx.user);1659        return;1660    }1661    if (std.mem.eql(u8, ctx.sub, "status")) {1662        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1663        output.serviceVerb("status", name, ctx.machine.name);1664        _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, "status", name, ctx.user);1665        return;1666    }1667    // start/stop/restart/enable/disable1668    const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1669    if (ctx.cfg.confirm and (std.mem.eql(u8, ctx.sub, "stop") or std.mem.eql(u8, ctx.sub, "disable"))) {1670        if (!output.confirm("")) return;1671    }1672    output.serviceVerb(ctx.sub, name, ctx.machine.name);1673    _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, ctx.sub, name, ctx.user);1674    output.serviceDone();1675}16761677// --- Flake commands ---16781679const flake_help = [_][2][]const u8{1680    .{ "init", "create a new flake.nix" },1681    .{ "update", "update flake inputs" },1682    .{ "update <in>", "update a specific input" },1683    .{ "check", "validate the flake" },1684    .{ "show", "inspect flake outputs" },1685    .{ "lock", "regenerate flake.lock" },1686    .{ "clone <url>", "clone a flake repository" },1687};16881689pub fn flake(ctx: Ctx) !void {1690    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("flake", &flake_help, null);1691    if (std.mem.eql(u8, ctx.sub, "update")) {1692        output.flakeUpdateStart();1693        const input: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1694        _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1695        output.flakeLockWritten();1696        return;1697    }1698    if (std.mem.eql(u8, ctx.sub, "check")) {1699        output.flakeCheckStart();1700        const code = try exec.flakeCheck(ctx.io, &ctx.machine, ctx.gpa);1701        if (code == 0) output.flakeValid() else output.checkFailed("");1702        return;1703    }1704    if (std.mem.eql(u8, ctx.sub, "show")) {1705        const json_out = exec.flakeShow(ctx.gpa, ctx.io, &ctx.machine) catch null;1706        if (json_out) |j| {1707            defer ctx.gpa.free(j);1708            output.flakeShowHeader("flake outputs");1709            // Parse and display the flake outputs1710            const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, j, .{}) catch return;1711            defer parsed.deinit();1712            if (parsed.value == .object) {1713                var it = parsed.value.object.iterator();1714                while (it.next()) |entry| {1715                    if (entry.value_ptr.* == .object) {1716                        var inner = entry.value_ptr.object.iterator();1717                        while (inner.next()) |e2| {1718                            const desc = if (e2.value_ptr.* == .object)1719                                if (e2.value_ptr.object.get("description")) |d|1720                                    if (d == .string) d.string else ""1721                                else1722                                    ""1723                            else1724                                "";1725                            output.flakeShowEntry(entry.key_ptr.*, e2.key_ptr.*, desc);1726                        }1727                    }1728                }1729            }1730        }1731        return;1732    }1733    if (std.mem.eql(u8, ctx.sub, "init")) {1734        _ = try exec.flakeInit(ctx.io, &ctx.machine, ctx.gpa);1735        return;1736    }1737    if (std.mem.eql(u8, ctx.sub, "lock")) {1738        _ = try exec.flakeLock(ctx.io, &ctx.machine, ctx.gpa);1739        return;1740    }1741    if (std.mem.eql(u8, ctx.sub, "clone")) {1742        const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1743        _ = try exec.flakeClone(ctx.io, &ctx.machine, ctx.gpa, url);1744        return;1745    }1746}17471748// --- Store commands ---17491750const store_help = [_][2][]const u8{1751    .{ "info", "store size and counts" },1752    .{ "path <attr>", "store path of a package" },1753    .{ "gc", "collect garbage" },1754    .{ "optimise", "deduplicate store paths with hard links" },1755    .{ "verify", "verify store integrity" },1756    .{ "repair", "repair corrupted paths" },1757};17581759pub fn store(ctx: Ctx) !void {1760    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("store", &store_help, null);1761    if (std.mem.eql(u8, ctx.sub, "gc")) {1762        _ = try exec.storeGc(ctx.io, &ctx.machine, ctx.gpa);1763        return;1764    }1765    // Accept both spellings — optimise (en) and optimize (us).1766    if (std.mem.eql(u8, ctx.sub, "optimise") or std.mem.eql(u8, ctx.sub, "optimize")) {1767        output.storeOptimiseStart(ctx.machine.name);1768        _ = try exec.storeOptimise(ctx.io, &ctx.machine, ctx.gpa);1769        output.storeOptimiseDone();1770        return;1771    }1772    if (std.mem.eql(u8, ctx.sub, "verify")) {1773        output.storeVerifyStart();1774        _ = try exec.storeVerify(ctx.io, &ctx.machine, ctx.gpa);1775        return;1776    }1777    if (std.mem.eql(u8, ctx.sub, "repair")) {1778        if (ctx.cfg.confirm and !output.confirm("")) return;1779        output.storeRepairStart();1780        _ = try exec.storeRepair(ctx.io, &ctx.machine, ctx.gpa);1781        return;1782    }1783    if (std.mem.eql(u8, ctx.sub, "info")) {1784        const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1785        output.storeInfo(si);1786        return;1787    }1788    if (std.mem.eql(u8, ctx.sub, "path")) {1789        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1790        const path = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, attr);1791        defer ctx.gpa.free(path);1792        output.storePath(path);1793        return;1794    }1795    // default: info1796    const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1797    output.storeInfo(si);1798}17991800// --- Channel commands ---18011802const channel_help = [_][2][]const u8{1803    .{ "list", "list channels" },1804    .{ "add <url> [name]", "add a channel" },1805    .{ "remove <name>", "remove a channel" },1806    .{ "update", "update all channels" },1807};18081809pub fn channel(ctx: Ctx) !void {1810    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("channel", &channel_help, null);1811    // On a flake-managed system, nix-channel operations generally don't apply.1812    if (flakeSystem(ctx)) output.flakeChannelNote();1813    if (std.mem.eql(u8, ctx.sub, "list")) {1814        output.channelListHeader(ctx.machine.name);1815        const chans = try exec.channelList(ctx.gpa, ctx.io, &ctx.machine);1816        defer ctx.gpa.free(chans);1817        for (chans) |ch| output.channelRow(ch);1818        return;1819    }1820    if (std.mem.eql(u8, ctx.sub, "add")) {1821        const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1822        const name = if (ctx.args.len > 1) ctx.args[1] else "";1823        _ = try exec.channelAdd(ctx.io, &ctx.machine, ctx.gpa, url, name);1824        output.channelDone();1825        return;1826    }1827    if (std.mem.eql(u8, ctx.sub, "remove")) {1828        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1829        _ = try exec.channelRemove(ctx.io, &ctx.machine, ctx.gpa, name);1830        output.channelDone();1831        return;1832    }1833    if (std.mem.eql(u8, ctx.sub, "update")) {1834        return channelUpdateCmd(ctx);1835    }1836}18371838// --- Profile commands ---18391840pub fn profile(ctx: Ctx) !void {1841    if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {1842        output.profileListHeader();1843        const out = exec.profileList(ctx.gpa, ctx.io, &ctx.machine) catch null;1844        if (out) |o| {1845            defer ctx.gpa.free(o);1846            var lines = std.mem.splitScalar(u8, o, '\n');1847            while (lines.next()) |line| {1848                const t = std.mem.trim(u8, line, " \t\r");1849                if (t.len == 0) continue;1850                output.profileRow(t, "", "");1851            }1852        }1853        return;1854    }1855    if (std.mem.eql(u8, ctx.sub, "install")) {1856        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1857        _ = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, ctx.environ, attr, false);1858        output.done();1859        return;1860    }1861    if (std.mem.eql(u8, ctx.sub, "remove")) {1862        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1863        _ = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, attr);1864        output.done();1865        return;1866    }1867    if (std.mem.eql(u8, ctx.sub, "upgrade")) {1868        _ = try exec.profileUpgrade(ctx.io, &ctx.machine, ctx.gpa);1869        output.done();1870        return;1871    }1872}18731874// --- Pkg commands ---18751876const pkg_help = [_][2][]const u8{1877    .{ "why <pkg>", "what pulled it in" },1878    .{ "deps <pkg>", "direct dependencies" },1879    .{ "size <pkg>", "closure size" },1880    .{ "path <pkg>", "store path" },1881    .{ "closure <pkg>", "full closure" },1882};18831884pub fn pkg(ctx: Ctx) !void {1885    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("pkg", &pkg_help, null);1886    const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1887    if (std.mem.eql(u8, ctx.sub, "why")) {1888        if (try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1889        return;1890    }1891    if (std.mem.eql(u8, ctx.sub, "deps")) {1892        if (try exec.pkgDeps(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1893        return;1894    }1895    if (std.mem.eql(u8, ctx.sub, "size")) {1896        const s = try exec.pkgSize(ctx.gpa, ctx.io, &ctx.machine, name);1897        defer ctx.gpa.free(s);1898        output.pkgResult("size", s);1899        return;1900    }1901    if (std.mem.eql(u8, ctx.sub, "path")) {1902        const p = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, name);1903        defer ctx.gpa.free(p);1904        output.pkgResult("path", p);1905        return;1906    }1907    if (std.mem.eql(u8, ctx.sub, "closure")) {1908        if (try exec.pkgClosure(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1909        return;1910    }1911}19121913// Top-level alias for `nina pkg why <pkg>` — surfaces what pulled a package in1914// without the user needing to know about the `pkg` subgroup.1915pub fn why(ctx: Ctx) !void {1916    const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1917    if (try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1918}19191920// --- Pin / Unpin ---19211922pub fn pin(ctx: Ctx) !void {1923    const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1924    const commit = if (ctx.args.len > 1) ctx.args[1] else return error.Internal;1925    exec.editFlakeLock(ctx.gpa, input, commit) catch return error.ProcessFailed;1926    output.pinDone(input, commit);1927}19281929pub fn unpin(ctx: Ctx) !void {1930    const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1931    _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1932    output.unpinDone(input);1933}19341935// --- Hash / Fetch ---19361937pub fn hash(ctx: Ctx) !void {1938    const path = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1939    const h = try exec.nixHash(ctx.gpa, ctx.io, &ctx.machine, path);1940    defer ctx.gpa.free(h);1941    output.hashResult(std.mem.trim(u8, h, " \t\n\r"));1942}19431944pub fn fetch(ctx: Ctx) !void {1945    const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1946    const h = try exec.nixFetch(ctx.gpa, ctx.io, &ctx.machine, url);1947    defer ctx.gpa.free(h);1948    output.fetchResult(std.mem.trim(u8, h, " \t\n\r"), url);1949}19501951// --- Build / Run ---19521953pub fn build(ctx: Ctx) !void {1954    const attr: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1955    output.buildStart(attr orelse "default");1956    const code = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, attr);1957    if (code != 0) return error.BuildFailed;1958    output.buildDone();1959}19601961pub fn runCmd(ctx: Ctx) !void {1962    const pkg_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1963    output.runStart(pkg_arg);1964    _ = try exec.nixRun(ctx.io, &ctx.machine, ctx.gpa, pkg_arg);1965}19661967// --- Hello ---19681969pub fn hello(ctx: Ctx) !void {1970    output.hello(ctx.cfg.machines);1971}19721973const ConfigKind = enum { flake, channel, none };19741975// Scan the conventional /etc/nixos for a flake.nix (flake-based) or a1976// configuration.nix (channel-based) to pre-fill the wizard's defaults.1977fn scanConfig(io: std.Io) ConfigKind {1978    if (exec.pathExists(io, "/etc/nixos/flake.nix")) return .flake;1979    if (exec.pathExists(io, "/etc/nixos/configuration.nix")) return .channel;1980    return .none;1981}19821983// Runs when the config is absent on first invocation (interactive TTY only).1984// Scans for an existing nixos config, detects flake vs channel, and offers a1985// smart default path — flake-ness is detected, never asked.1986pub fn firstRunWizard(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1987    output.firstRunBanner();1988    output.firstRunNoConfig();19891990    var name_buf: [256]u8 = undefined;1991    var path_buf: [256]u8 = undefined;19921993    const machine_name = output.firstRunPrompt("machine name", "my-machine", &name_buf);19941995    output.firstRunScanning();1996    const kind = scanConfig(io);1997    switch (kind) {1998        .flake => output.firstRunDetected("/etc/nixos/flake.nix", true),1999        .channel => output.firstRunDetected("/etc/nixos/configuration.nix", false),2000        .none => output.firstRunNoneFound(),2001    }20022003    // Detected systems default to /etc/nixos (press enter to confirm); when2004    // nothing was found, leave the default empty so the user must type a path.2005    const default_path: []const u8 = if (kind == .none) "" else "/etc/nixos";2006    const config_path = output.firstRunPromptDefault("config path", default_path, kind != .none, &path_buf);20072008    // Re-detect at the chosen path in case the user pointed elsewhere — flake.nix2009    // there means a flake system, recorded so channel commands warn appropriately.2010    const use_flakes = exec.dirHasFlake(gpa, io, config_path);20112012    const conf_path = try config.configPath(gpa, environ);2013    defer gpa.free(conf_path);2014    if (std.fs.path.dirname(conf_path)) |dir| exec.ensureDir(gpa, io, dir);20152016    // `flake` is a top-level config field, so it must precede the [machine] block.2017    const flake_line = if (use_flakes) "flake = true\n" else "";2018    var content_buf: [1024]u8 = undefined;2019    const content = try std.fmt.bufPrint(2020        &content_buf,2021        "{s}[machine]\nname = {s}\nconfig = {s}\nlocal = true\n",2022        .{ flake_line, machine_name, config_path },2023    );20242025    const file = std.Io.Dir.createFile(.cwd(), io, conf_path, .{}) catch {2026        errors.error_info.setMessage("could not write {s}", .{conf_path});2027        return error.Internal;2028    };2029    defer file.close(io);2030    file.writePositionalAll(io, content, 0) catch {2031        errors.error_info.setMessage("could not write {s}", .{conf_path});2032        return error.Internal;2033    };20342035    output.firstRunWritten(conf_path);2036}20372038pub fn setup(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {2039    // Create the config first if it doesn't exist. This makes `nina setup`2040    // a complete onboarding command — not just a nix-features check. Any legacy2041    // ~/.nina.conf is migrated to the XDG path before we decide to run the wizard.2042    config.migrateLegacyConfig(gpa, io, environ);2043    if (config.configPath(gpa, environ)) |conf_path| {2044        defer gpa.free(conf_path);2045        if (std.Io.Dir.openFile(.cwd(), io, conf_path, .{})) |f| {2046            f.close(io);2047        } else |_| {2048            try firstRunWizard(gpa, io, environ);2049            errors.error_info.reset();2050        }2051    } else |_| {}20522053    output.setupCheck();2054    const status = exec.checkNixFeatures(gpa, io, environ);2055    output.setupFeatures(status.nix_command, status.flakes);20562057    if (status.allEnabled()) {2058        output.setupAllSet();2059        api.ensureRegistryPinned(gpa, io, environ);2060        return;2061    }20622063    // On NixOS the features belong in configuration.nix (the declarative,2064    // permanent home), not ~/.config/nix/nix.conf. Offer to add the one line;2065    // the user runs the rebuild. We don't pin the registry here because the2066    // features aren't live until that rebuild lands.2067    if (exec.isNixOS(io)) {2068        const conf_path = "/etc/nixos/configuration.nix";2069        if (exec.nixosConfigEnablesFeatures(gpa, io, conf_path)) {2070            output.setupNixosNeedsRebuild(conf_path);2071            return;2072        }2073        output.setupNixosOffer(exec.NIXOS_FEATURES_LINE, conf_path);2074        if (output.confirmDefaultNo("add it now?")) {2075            if (exec.appendFeaturesToNixosConfig(gpa, io, environ, conf_path)) |_| {2076                output.setupNixosWrote(conf_path);2077            } else |_| {2078                output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);2079            }2080        } else {2081            output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);2082        }2083        return;2084    }20852086    // Non-NixOS: a user-level nix.conf takes effect immediately, no sudo needed.2087    output.setupEnabling();2088    const path = try exec.enableNixFeatures(gpa, io, environ);2089    defer gpa.free(path);20902091    output.setupDone(path);2092    api.ensureRegistryPinned(gpa, io, environ);2093}20942095// --- Log helper ---20962097fn logAction(ctx: Ctx, action: []const u8, gen: u32) void {2098    var ts_buf: [32]u8 = undefined;2099    const ts = nowIso(ctx.io, &ts_buf);2100    var buf: [256]u8 = undefined;2101    const entry = std.fmt.bufPrint(&buf, "{{\"ts\":\"{s}\",\"machine\":\"{s}\",\"command\":\"{s}\",\"outcome\":\"success\",\"gen_before\":null,\"gen_after\":{d},\"duration_ms\":0}}\n", .{2102        ts, ctx.machine.name, action, gen,2103    }) catch return;2104    exec.appendNinaLog(ctx.io, ctx.environ, entry);2105}21062107// Wall-clock UTC as ISO-8601. Uses Io.Clock.real (the settable Unix-epoch clock);2108// Io.Clock.awake is monotonic and unsuitable for timestamps. Falls back to epoch 0.2109fn nowIso(io: std.Io, buf: []u8) []const u8 {2110    const fallback = "1970-01-01T00:00:00Z";2111    const ns = std.Io.Clock.real.now(io).toNanoseconds();2112    if (ns <= 0) return fallback;2113    const secs: u64 = @intCast(@divFloor(ns, 1_000_000_000));2114    const es = std.time.epoch.EpochSeconds{ .secs = secs };2115    const ed = es.getEpochDay();2116    const yd = ed.calculateYearDay();2117    const md = yd.calculateMonthDay();2118    const ds = es.getDaySeconds();2119    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", .{2120        yd.year,              md.month.numeric(),      @as(u32, md.day_index) + 1,2121        ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(),2122    }) catch return fallback;2123}