commands.zig

82.3 KB · raw

1// commands.zig — all command handlers2// Orchestrates exec/api/output. Zero direct stdout writes.3const std = @import("std");4const builtin = @import("builtin");5const types = @import("types.zig");6const errors = @import("errors.zig");7const config = @import("config.zig");8const output = @import("output.zig");9const exec = @import("exec.zig");10const api = @import("api.zig");11const search_tui = @import("search.zig");12const version = @import("version.zig");1314const UPDATE_URL = "https://kepr.uk/api/nina/releases/latest";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// `nix profile upgrade` exits 0 even when its match argument names nothing —346// it just prints one of these warnings and does no work. Detecting them keeps347// `nina update` from reporting a false "updated" line on a no-op upgrade.348fn nixUpgradeNoOp(s: []const u8) bool {349    return std.mem.indexOf(u8, s, "No packages to upgrade") != null or350        std.mem.indexOf(u8, s, "does not match any packages") != null;351}352353// nina update — kepr self-update for the nina binary itself.354pub fn update(ctx: Ctx) !void {355    output.updateSelfStart();356357    if (comptime std.mem.eql(u8, version.PLATFORM, "unsupported")) {358        output.updateSelfNoPlatform(@tagName(builtin.cpu.arch) ++ "-" ++ @tagName(builtin.os.tag));359        return error.Internal;360    }361362    const env_url = ctx.environ.get("NINA_UPDATE_SOURCE");363    const source_url = env_url orelse UPDATE_URL;364365    const body = exec.fetchUrl(ctx.gpa, ctx.io, source_url) catch |e| switch (e) {366        error.NetworkError, error.HttpError => {367            output.updateSelfNetworkError();368            return;369        },370        else => return e,371    };372    defer ctx.gpa.free(body);373374    const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, body, .{}) catch {375        output.printWarning("could not parse release metadata");376        return;377    };378    defer parsed.deinit();379380    const root = parsed.value;381    if (root != .object) {382        output.printWarning("malformed release metadata");383        return;384    }385386    const remote_ver = blk: {387        const v = root.object.get("version") orelse {388            output.printWarning("malformed release metadata");389            return;390        };391        break :blk switch (v) {392            .string => |s| s,393            else => {394                output.printWarning("malformed release metadata");395                return;396            },397        };398    };399    if (!remoteVersionNewer(version.VERSION, remote_ver)) {400        output.updateSelfCurrent(version.VERSION);401        return;402    }403404    const release_notes = try updateReleaseNotes(ctx.gpa, ctx.io, root, source_url, version.VERSION, remote_ver);405    defer ctx.gpa.free(release_notes);406407    output.updateSelfAvailable(version.VERSION, remote_ver);408    output.updateSelfReleaseNotes(release_notes);409    if (ctx.check) return;410411    var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;412    const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {413        errors.error_info.setMessage("could not determine install path", .{});414        return error.Internal;415    };416417    // When running from the nix store, defer to nix profile upgrade so nix418    // manages the transition (the store is read-only; binary replacement fails).419    // A NixOS system install also resolves into the store but isn't a profile420    // element, so check the profile to avoid a no-op `upgrade` — it updates with421    // the next nixos-rebuild instead.422    if (std.mem.startsWith(u8, install_path, "/nix/store/")) {423        const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);424        defer if (nina_element) |n| ctx.gpa.free(n);425        if (nina_element == null) {426            output.updateSelfNotInProfile();427            return;428        }429        const element = nina_element.?;430        output.updateSelfNixManaged(remote_ver);431        if (ctx.cfg.confirm and !output.confirm("")) return;432        // `nix profile upgrade` matches its argument against the profile element433        // NAME, then re-fetches that element's own originalUrl. The name is the434        // only thing that matches — passing the URL matches nothing and nix then435        // exits 0 with a "No packages to upgrade" warning, so success must be436        // judged on nix's output, not the exit code alone, or we report a false437        // "updated" line for an upgrade that never happened.438        const r = exec.capture(ctx.gpa, ctx.io, &ctx.machine, &.{ "nix", "profile", "upgrade", element }) catch {439            output.updateSelfNixFailed();440            return;441        };442        defer ctx.gpa.free(r.stdout);443        defer ctx.gpa.free(r.stderr);444        output.raw(r.stdout);445        output.raw(r.stderr);446        if (r.exit_code != 0 or nixUpgradeNoOp(r.stdout) or nixUpgradeNoOp(r.stderr)) {447            output.updateSelfNixFailed();448            return;449        }450        output.updateSelfDone(version.VERSION, remote_ver);451        output.updateSelfNixRehash();452        return;453    }454455    const plat_info = blk: {456        const pv = root.object.get("platforms") orelse break :blk null;457        if (pv != .object) break :blk null;458        break :blk pv.object.get(version.PLATFORM);459    };460    if (plat_info == null) {461        output.updateSelfNoPlatform(version.PLATFORM);462        return;463    }464465    const dl_url = blk: {466        const v = plat_info.?.object.get("url") orelse {467            output.printWarning("malformed release metadata");468            return;469        };470        break :blk switch (v) {471            .string => |s| s,472            else => {473                output.printWarning("malformed release metadata");474                return;475            },476        };477    };478479    const raw_cksum = blk: {480        if (plat_info.?.object.get("blake3")) |v|481            break :blk switch (v) {482                .string => |s| s,483                else => {484                    output.printWarning("malformed release metadata");485                    return;486                },487            };488        if (plat_info.?.object.get("checksum")) |v|489            break :blk switch (v) {490                .string => |s| s,491                else => {492                    output.printWarning("malformed release metadata");493                    return;494                },495            };496        output.printWarning("missing checksum in release metadata");497        return;498    };499    const expected_hex = if (std.mem.startsWith(u8, raw_cksum, "blake3:")) raw_cksum["blake3:".len..] else raw_cksum;500501    if (ctx.cfg.confirm and !output.confirm("")) return;502503    output.updateSelfDownloading(remote_ver, version.PLATFORM);504    const tmp_path = exec.downloadToTemp(ctx.gpa, ctx.io, dl_url) catch {505        output.printWarning("download failed — check your connection and try again");506        return;507    };508    defer ctx.gpa.free(tmp_path);509510    output.updateSelfVerifying();511    exec.verifyAndInstall(ctx.gpa, ctx.io, tmp_path, expected_hex, install_path) catch |e| switch (e) {512        error.ChecksumMismatch => {513            output.updateSelfChecksumFailed();514            return;515        },516        else => return e,517    };518519    output.updateSelfDone(version.VERSION, remote_ver);520}521522fn updateReleaseNotes(gpa: std.mem.Allocator, io: std.Io, root: std.json.Value, source_url: []const u8, current: []const u8, latest: []const u8) ![]u8 {523    if (releaseNotesFromMetadata(gpa, root)) |notes| {524        if (std.mem.trim(u8, notes, " \t\r\n").len > 0) return notes;525        gpa.free(notes);526    }527    return buildKeprArchiveReleaseNotes(gpa, io, source_url, current, latest) catch gpa.dupe(u8, "");528}529530fn releaseNotesFromMetadata(gpa: std.mem.Allocator, root: std.json.Value) ?[]u8 {531    if (root != .object) return null;532    // `notes` is the one canonical manifest field. The retired `release_notes`533    // and `changelog` fallbacks are gone — Kepr now emits `notes` everywhere, and534    // releases that predate `--notes` fall back to archives.json in the caller.535    const v = root.object.get("notes") orelse return null;536    return switch (v) {537        .string => |s| gpa.dupe(u8, s) catch null,538        else => null,539    };540}541542fn buildKeprArchiveReleaseNotes(gpa: std.mem.Allocator, io: std.Io, source_url: []const u8, current: []const u8, latest: []const u8) ![]u8 {543    const archive_url = try keprArchiveUrl(gpa, source_url);544    defer gpa.free(archive_url);545546    const body = exec.fetchUrl(gpa, io, archive_url) catch return gpa.dupe(u8, "");547    defer gpa.free(body);548549    return releaseNotesFromArchiveJson(gpa, body, current, latest);550}551552fn keprArchiveUrl(gpa: std.mem.Allocator, source_url: []const u8) ![]u8 {553    const scheme = std.mem.indexOf(u8, source_url, "://") orelse return error.InvalidUpdateSource;554    const path_start = std.mem.indexOfScalarPos(u8, source_url, scheme + 3, '/') orelse return error.InvalidUpdateSource;555    const origin = source_url[0..path_start];556    const path = source_url[path_start..];557    if (!std.mem.startsWith(u8, path, "/api/")) return error.InvalidUpdateSource;558559    const after_api = path["/api/".len..];560    const repo_end = std.mem.indexOfScalar(u8, after_api, '/') orelse return error.InvalidUpdateSource;561    const repo = after_api[0..repo_end];562    if (repo.len == 0) return error.InvalidUpdateSource;563564    return std.fmt.allocPrint(gpa, "{s}/{s}/archives.json?limit=100", .{ origin, repo });565}566567// Saves arrive newest-first. For each version in the update range we want the OLDEST568// save message (the one that introduced that version), not a follow-up cleanup/docs save.569// We overwrite the tracked message on each occurrence, so the final stored value per570// version is always the oldest (last-seen in a newest-first stream).571fn releaseNotesFromArchiveJson(gpa: std.mem.Allocator, body: []const u8, current: []const u8, latest: []const u8) ![]u8 {572    const parsed = std.json.parseFromSlice(std.json.Value, gpa, body, .{}) catch return gpa.dupe(u8, "");573    defer parsed.deinit();574575    if (parsed.value != .object) return gpa.dupe(u8, "");576    const saves_v = parsed.value.object.get("saves") orelse return gpa.dupe(u8, "");577    if (saves_v != .array) return gpa.dupe(u8, "");578579    // version string → oldest message seen (both slice into parsed JSON, valid until deinit)580    var best_msg = std.StringHashMap([]const u8).init(gpa);581    defer best_msg.deinit();582    var order: std.ArrayList([]const u8) = .empty;583    defer order.deinit(gpa);584585    for (saves_v.array.items) |save| {586        if (save != .object) continue;587        const ver_v = save.object.get("version") orelse continue;588        const msg_v = save.object.get("message") orelse continue;589        if (ver_v != .string or msg_v != .string) continue;590        const ver = ver_v.string;591        const msg = std.mem.trim(u8, msg_v.string, " \t\r\n");592        if (msg.len == 0 or !versionInUpdateRange(ver, current, latest)) continue;593594        const entry = try best_msg.getOrPut(ver);595        if (!entry.found_existing) try order.append(gpa, ver);596        // Always overwrite: saves are newest-first, so last write = oldest save = version-intro message597        entry.value_ptr.* = msg;598    }599600    if (order.items.len == 0) return gpa.dupe(u8, "");601602    var out: std.ArrayList(u8) = .empty;603    errdefer out.deinit(gpa);604    for (order.items) |ver| {605        const msg = best_msg.get(ver).?;606        // Use only the first line as the summary; multi-line saves may have implementation details below607        const summary_end = std.mem.indexOf(u8, msg, "\n") orelse msg.len;608        const summary = std.mem.trim(u8, msg[0..summary_end], " \t\r");609        if (summary.len == 0) continue;610        try appendLine(&out, gpa, "## {s}\n", .{ver});611        try appendLine(&out, gpa, "- {s}\n\n", .{summary});612    }613614    if (out.items.len == 0) {615        out.deinit(gpa);616        return gpa.dupe(u8, "");617    }618    return out.toOwnedSlice(gpa);619}620621fn appendLine(out: *std.ArrayList(u8), gpa: std.mem.Allocator, comptime template: []const u8, args: anytype) !void {622    const line = try std.fmt.allocPrint(gpa, template, args);623    defer gpa.free(line);624    try out.appendSlice(gpa, line);625}626627fn versionInUpdateRange(candidate: []const u8, current: []const u8, latest: []const u8) bool {628    const cand = parseSemver(candidate) orelse return std.mem.eql(u8, candidate, latest);629    const cur = parseSemver(current) orelse return std.mem.eql(u8, candidate, latest);630    const lat = parseSemver(latest) orelse return std.mem.eql(u8, candidate, latest);631    return compareSemver(cand, cur) == .gt and compareSemver(cand, lat) != .gt;632}633634fn remoteVersionNewer(current: []const u8, remote: []const u8) bool {635    const cur = parseSemver(current) orelse return !std.mem.eql(u8, current, remote);636    const rem = parseSemver(remote) orelse return !std.mem.eql(u8, current, remote);637    return compareSemver(rem, cur) == .gt;638}639640const VersionOrder = enum { lt, eq, gt };641642fn compareSemver(a: Semver, b: Semver) VersionOrder {643    if (a.major != b.major) return if (a.major < b.major) .lt else .gt;644    if (a.minor != b.minor) return if (a.minor < b.minor) .lt else .gt;645    if (a.patch != b.patch) return if (a.patch < b.patch) .lt else .gt;646    return .eq;647}648649fn parseSemver(raw: []const u8) ?Semver {650    const v = if (std.mem.startsWith(u8, raw, "v")) raw[1..] else raw;651    var it = std.mem.splitScalar(u8, v, '.');652    const major_s = it.next() orelse return null;653    const minor_s = it.next() orelse return null;654    const patch_s = it.next() orelse return null;655    if (it.next() != null) return null;656    return .{657        .major = std.fmt.parseInt(u32, major_s, 10) catch return null,658        .minor = std.fmt.parseInt(u32, minor_s, 10) catch return null,659        .patch = std.fmt.parseInt(u32, patch_s, 10) catch return null,660    };661}662663test "versionInUpdateRange includes only newer versions through latest" {664    try std.testing.expect(versionInUpdateRange("3.2.3", "3.1.9", "3.2.3"));665    try std.testing.expect(versionInUpdateRange("3.2.0", "3.1.9", "3.2.3"));666    try std.testing.expect(!versionInUpdateRange("3.1.9", "3.1.9", "3.2.3"));667    try std.testing.expect(!versionInUpdateRange("3.2.4", "3.1.9", "3.2.3"));668}669670test "nixUpgradeNoOp catches nix's exit-0 no-op warnings" {671    // The exact strings from the screenshotted false-success bug.672    try std.testing.expect(nixUpgradeNoOp("warning: No packages to upgrade. Use 'nix profile list'..."));673    try std.testing.expect(nixUpgradeNoOp("warning: Package name 'https://kepr.uk/nina/archive/HEAD.tar.gz' does not match any packages in the profile."));674    // A genuine upgrade's output must not be mistaken for a no-op.675    try std.testing.expect(!nixUpgradeNoOp("building '/nix/store/...-nina-3.4.1.drv'...\n"));676    try std.testing.expect(!nixUpgradeNoOp(""));677}678679test "remoteVersionNewer does not offer downgrades" {680    try std.testing.expect(remoteVersionNewer("3.2.3", "3.2.4"));681    try std.testing.expect(!remoteVersionNewer("3.2.4", "3.2.3"));682    try std.testing.expect(!remoteVersionNewer("3.2.4", "3.2.4"));683}684685test "releaseNotesFromArchiveJson uses oldest save per version" {686    // Saves arrive newest-first. For 3.2.3, the newest save is a CONTINUITY update;687    // the oldest is the version-intro message. We expect the intro message in the output.688    const body =689        \\{690        \\  "saves": [691        \\    {"version":"3.2.3","message":"wip: record verification in CONTINUITY"},692        \\    {"version":"3.2.1","message":"old release"},693        \\    {"version":"3.2.3","message":"add streaming deflate path"}694        \\  ]695        \\}696    ;697    const notes = try releaseNotesFromArchiveJson(std.testing.allocator, body, "3.2.1", "3.2.3");698    defer std.testing.allocator.free(notes);699700    try std.testing.expect(std.mem.indexOf(u8, notes, "## 3.2.3") != null);701    try std.testing.expect(std.mem.indexOf(u8, notes, "- add streaming deflate path") != null);702    try std.testing.expect(std.mem.indexOf(u8, notes, "CONTINUITY") == null);703    try std.testing.expect(std.mem.indexOf(u8, notes, "old release") == null);704}705706test "releaseNotesFromMetadata reads canonical notes and ignores retired keys" {707    const a = std.testing.allocator;708709    // Canonical field is read.710    {711        var parsed = try std.json.parseFromSlice(std.json.Value, a, "{\"notes\":\"colored progress bar\"}", .{});712        defer parsed.deinit();713        const got = releaseNotesFromMetadata(a, parsed.value).?;714        defer a.free(got);715        try std.testing.expectEqualStrings("colored progress bar", got);716    }717718    // Retired field names are no longer honoured — they fall through to null so719    // the caller drops to the archives.json derivation instead.720    {721        var parsed = try std.json.parseFromSlice(std.json.Value, a, "{\"release_notes\":\"x\",\"changelog\":\"y\"}", .{});722        defer parsed.deinit();723        try std.testing.expect(releaseNotesFromMetadata(a, parsed.value) == null);724    }725}726727// nina goodbye — clean uninstall. Three install paths:728// - nix profile (binary in nix store with a profile element) → nix profile remove729// - koh build or source build (plain binary on PATH) → delete the file730pub fn goodbye(ctx: Ctx) !void {731    output.goodbyeStart();732733    var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;734    const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {735        errors.error_info.setMessage("could not determine install path", .{});736        return error.Internal;737    };738739    // A binary outside the nix store is a koh build or source build — delete it.740    if (!std.mem.startsWith(u8, install_path, "/nix/store/")) {741        output.goodbyeFile(install_path);742        if (ctx.cfg.confirm and !output.confirm("")) return;743        std.Io.Dir.deleteFileAbsolute(ctx.io, install_path) catch |e| {744            errors.error_info.setMessage("could not remove {s}", .{install_path});745            return e;746        };747        output.goodbyeDone();748        return;749    }750751    // Binary is in the nix store — find and remove the profile element.752    const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);753    defer {754        if (nina_element) |n| ctx.gpa.free(n);755    }756757    if (nina_element == null) {758        errors.error_info.setMessage("nina not found in nix profile — was it installed via 'nix profile add'?", .{});759        return error.Internal;760    }761762    output.goodbyeNix();763    if (ctx.cfg.confirm and !output.confirm("")) return;764    const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "remove", nina_element.? }) catch {765        output.goodbyeFailed("nix profile remove failed");766        return;767    };768    if (ec != 0) {769        output.goodbyeFailed("nix profile remove failed");770        return;771    }772    output.goodbyeDone();773}774775fn channelUpdateCmd(ctx: Ctx) !void {776    output.updateStart(ctx.machine.name);777    _ = try exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa);778    output.updateDone();779}780781pub fn upgrade(ctx: Ctx) !void {782    if (!try runPreHook(ctx, "pre-upgrade")) {783        output.aborted();784        return error.HookAborted;785    }786787    output.upgradeStart(ctx.machine.name);788    // Flake systems update inputs (flake.lock); channel systems update channels.789    // Running nix-channel --update on a flake system is a no-op at best. The790    // rebuild below is already flake-aware via exec.nixosRebuildSwitch.791    if (flakeSystem(ctx)) {792        output.printSubstep("updating flake inputs", .{});793        _ = exec.flakeUpdateAt(ctx.io, &ctx.machine, ctx.gpa, ctx.machine.config_path) catch {};794    } else {795        output.printSubstep("updating channels", .{});796        _ = exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa) catch {};797    }798    output.printSubstep("rebuilding", .{});799    output.buildPanelInit();800    const start = std.Io.Clock.awake.now(ctx.io);801    var panel = output.BuildPanel{};802    const code = exec.nixosRebuildSwitchWithPanel(ctx.io, &ctx.machine, ctx.gpa, &panel) catch |e| {803        output.buildPanelClear();804        return e;805    };806    output.buildPanelClear();807    if (code != 0) {808        output.applyFailed("");809        return error.BuildFailed;810    }811    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());812    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));813    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;814    output.applyDone(gen, elapsed, false);815    runPostHook(ctx, "post-upgrade");816}817818pub fn log(ctx: Ctx) !void {819    output.logHeader(ctx.machine.name);820    const content = exec.readNinaLog(ctx.gpa, ctx.io, ctx.environ, ctx.last) catch {821        // No log yet — that's fine822        return;823    };824    defer ctx.gpa.free(content);825    var lines = std.mem.splitScalar(u8, content, '\n');826    while (lines.next()) |line| {827        const t = std.mem.trim(u8, line, " \t\r");828        if (t.len == 0) continue;829        if (t[0] == '{') {830            renderJsonLogLine(ctx.gpa, t);831        } else {832            // legacy tab-separated format833            var parts = std.mem.tokenizeScalar(u8, t, '\t');834            const date = parts.next() orelse continue;835            const time = parts.next() orelse "";836            const action = parts.next() orelse "";837            const detail = parts.next() orelse "";838            output.logRow(date, time, action, detail);839        }840    }841}842843// The on-disk log is JSON Lines: {"ts","machine","command","outcome","gen_after",...}.844// Render ts -> date/time columns, command -> action, outcome(+gen) -> detail.845fn renderJsonLogLine(gpa: std.mem.Allocator, line: []const u8) void {846    const parsed = std.json.parseFromSlice(std.json.Value, gpa, line, .{}) catch {847        output.logRow(line, "", "", ""); // unparseable — show raw rather than drop848        return;849    };850    defer parsed.deinit();851    if (parsed.value != .object) return;852    const o = parsed.value.object;853854    const ts = jsonStr(o, "ts");855    const date = if (ts.len >= 10) ts[0..10] else ts;856    const time = if (ts.len >= 16) ts[11..16] else "";857    const action = jsonStr(o, "command");858    const outcome = jsonStr(o, "outcome");859860    var buf: [160]u8 = undefined;861    var detail: []const u8 = outcome;862    if (o.get("gen_after")) |g| {863        if (g == .integer) {864            detail = std.fmt.bufPrint(&buf, "{s}   -> gen {d}", .{ outcome, g.integer }) catch outcome;865        }866    }867    output.logRow(date, time, action, detail);868}869870fn jsonStr(o: std.json.ObjectMap, key: []const u8) []const u8 {871    if (o.get(key)) |v| {872        if (v == .string) return v.string;873    }874    return "";875}876877pub fn edit(ctx: Ctx) !void {878    // `edit` is multi-word, so a bare positional ("hardware") arrives as ctx.sub.879    // hardware-configuration.nix is generated by nixos-generate-config and warns880    // against hand-editing — refuse rather than silently opening the wrong file.881    if (std.mem.eql(u8, ctx.sub, "hardware")) {882        output.editHardwareWarning();883        return;884    }885886    // --dir opens the whole config directory (for editors that work better with887    // a folder open), as root so root-owned config trees like /etc/nixos work.888    var open_dir = false;889    for (ctx.args) |arg| {890        if (std.mem.eql(u8, arg, "--dir")) open_dir = true;891    }892    if (open_dir) {893        output.editOpen(ctx.machine.config_path, ctx.cfg.editor);894        _ = try exec.openEditorSudo(ctx.io, ctx.gpa, ctx.cfg.editor, ctx.machine.config_path);895        return;896    }897898    const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});899    defer ctx.gpa.free(path);900    output.editOpen(path, ctx.cfg.editor);901    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);902}903904pub fn fmt(ctx: Ctx) !void {905    const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});906    defer ctx.gpa.free(path);907    if (ctx.check) {908        const code = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, true);909        if (code != 0) output.fmtNeedsFormat() else output.fmtDone();910        return;911    }912    output.fmtStart(path);913    _ = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, false);914    output.fmtDone();915}916917pub fn repl(ctx: Ctx) !void {918    output.replStart();919    _ = try exec.nixRepl(ctx.io, &ctx.machine, ctx.gpa);920}921922pub fn develop(ctx: Ctx) !void {923    if (std.mem.eql(u8, ctx.sub, "show")) {924        _ = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, null);925        return;926    }927    const run_cmd: ?[]const u8 = if (ctx.args.len > 0 and std.mem.eql(u8, ctx.sub, "run"))928        ctx.args[0]929    else930        null;931    output.developStart(&.{});932    _ = try exec.nixDevelopPs1(ctx.io, &ctx.machine, ctx.gpa, run_cmd, ctx.environ);933    output.developDone();934}935936pub fn info(ctx: Ctx) !void {937    output.infoHeader(ctx.machine.name);938    const nixos_ver = exec.systemInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");939    defer ctx.gpa.free(nixos_ver);940    output.infoRow("nixos", std.mem.trim(u8, nixos_ver, " \t\n\r"));941942    const kernel = exec.kernelInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");943    defer ctx.gpa.free(kernel);944    output.infoRow("kernel", std.mem.trim(u8, kernel, " \t\n\r"));945946    const uptime = exec.uptimeInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");947    defer ctx.gpa.free(uptime);948    output.infoRow("uptime", std.mem.trim(u8, uptime, " \t\n\r"));949}950951pub fn boot(ctx: Ctx) !void {952    output.bootHeader(ctx.machine.name);953    const entries = exec.bootEntries(ctx.gpa, ctx.io, &ctx.machine) catch &.{};954    defer ctx.gpa.free(entries);955    for (entries, 0..) |entry, i| output.bootEntry(entry, i);956}957958pub fn searchCmd(ctx: Ctx) !void {959    const query = if (ctx.args.len > 0) ctx.args[0] else "";960    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);961    const selected = try search_tui.run(ctx.gpa, ctx.io, query, .packages);962    if (selected) |npkg| try selectAndInstall(ctx, npkg);963}964965pub fn optionCmd(ctx: Ctx) !void {966    const query = if (ctx.args.len > 0) ctx.args[0] else "";967    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);968    _ = try search_tui.run(ctx.gpa, ctx.io, query, .options);969}970971pub fn install(ctx: Ctx) !void {972    const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;973974    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);975976    // Search for the package to get the attr977    const pkgs = api.searchPackages(ctx.gpa, ctx.io, pkg_name) catch {978        errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});979        errors.error_info.setSuggestion("nina search {s}", .{pkg_name});980        return error.PackageNotFound;981    };982983    if (pkgs.len == 0) {984        // No matches — likely a typo. Suggest the closest real package and offer it.985        if (closestPackage(ctx, pkg_name)) |sugg| {986            output.didYouMean(pkg_name, sugg.pname);987            if (output.confirm("")) try selectAndInstall(ctx, sugg);988            return;989        }990        errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});991        errors.error_info.setSuggestion("nina search {s}", .{pkg_name});992        return error.PackageNotFound;993    }994995    // Prefer an exact name match over the first search result — `install ripgrep`996    // must pick "ripgrep", not the alphabetically-first match like "repgrep".997    var found = pkgs[0];998    for (pkgs) |p| {999        if (std.mem.eql(u8, p.pname, pkg_name)) {1000            found = p;1001            break;1002        }1003    }1004    try selectAndInstall(ctx, found);1005}10061007// Find the real package whose name is closest to a not-found query (typo help).1008// Typos usually keep the leading characters, so gather candidates with a prefix1009// search and rank by edit distance; return the best only if it's typo-close.1010fn closestPackage(ctx: Ctx, query: []const u8) ?types.NixPackage {1011    if (query.len < 2) return null;1012    var candidates = api.searchPackages(ctx.gpa, ctx.io, query[0..@min(query.len, 4)]) catch &.{};1013    if (candidates.len == 0 and query.len > 2) {1014        candidates = api.searchPackages(ctx.gpa, ctx.io, query[0..2]) catch &.{};1015    }1016    if (candidates.len == 0) return null;10171018    var best: ?types.NixPackage = null;1019    var best_dist: usize = std.math.maxInt(usize);1020    for (candidates) |p| {1021        const d = editDistance(query, p.pname);1022        if (d > 0 and d < best_dist) {1023            best_dist = d;1024            best = p;1025        }1026    }1027    // Only suggest a genuinely close name, scaled to query length.1028    const threshold = @max(@as(usize, 2), query.len / 3);1029    return if (best_dist <= threshold) best else null;1030}10311032// Case-insensitive Levenshtein distance. Names longer than the row buffer are1033// treated as far away (never suggested).1034fn editDistance(a: []const u8, b: []const u8) usize {1035    const n = b.len;1036    if (a.len == 0) return n;1037    if (n == 0) return a.len;1038    if (n + 1 > 128) return std.math.maxInt(usize);1039    var prev: [128]usize = undefined;1040    var curr: [128]usize = undefined;1041    var j: usize = 0;1042    while (j <= n) : (j += 1) prev[j] = j;1043    var i: usize = 1;1044    while (i <= a.len) : (i += 1) {1045        curr[0] = i;1046        j = 1;1047        while (j <= n) : (j += 1) {1048            const cost: usize = if (std.ascii.toLower(a[i - 1]) == std.ascii.toLower(b[j - 1])) 0 else 1;1049            curr[j] = @min(prev[j] + 1, @min(curr[j - 1] + 1, prev[j - 1] + cost));1050        }1051        @memcpy(prev[0 .. n + 1], curr[0 .. n + 1]);1052    }1053    return prev[n];1054}10551056test "editDistance is case-insensitive Levenshtein" {1057    try std.testing.expectEqual(@as(usize, 1), editDistance("firefux", "firefox"));1058    try std.testing.expectEqual(@as(usize, 0), editDistance("git", "GIT"));1059    try std.testing.expectEqual(@as(usize, 2), editDistance("fierfox", "firefox"));1060    try std.testing.expectEqual(@as(usize, 7), editDistance("", "firefox"));1061}10621063// Prompt for the install method (profile / system / try) and dispatch. Shared by1064// `nina install <pkg>` and the search widget's Enter-to-select — the letter keys1065// are read here, after the search widget's raw mode is gone, so they don't1066// collide with typing a query.1067fn selectAndInstall(ctx: Ctx, npkg: types.NixPackage) !void {1068    output.installSelectPrompt(npkg.pname, npkg.version);10691070    var choice_buf: [8]u8 = undefined;1071    var choice_len: usize = 0;1072    while (choice_len < choice_buf.len) {1073        const n = std.posix.read(std.posix.STDIN_FILENO, choice_buf[choice_len .. choice_len + 1]) catch break;1074        if (n == 0) break;1075        if (choice_buf[choice_len] == '\n') break;1076        choice_len += 1;1077    }1078    const choice = std.mem.trim(u8, choice_buf[0..choice_len], " \t");10791080    if (choice.len == 0 or choice[0] == 'i' or choice[0] == 'I') {1081        try profileInstallPkg(ctx, npkg);1082    } else if (choice[0] == 's' or choice[0] == 'S') {1083        try systemInstallPkg(ctx, npkg);1084    } else if (choice[0] == 't' or choice[0] == 'T') {1085        try tryPkg(ctx, npkg);1086    }1087}10881089fn profileInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {1090    output.installStart(npkg.pname, .profile);1091    output.printSubstep("nix profile add nixpkgs#{s}", .{npkg.attr});1092    output.printTeach(try std.fmt.allocPrint(ctx.gpa, "nix profile add nixpkgs#{s}", .{npkg.attr}));1093    const code = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, npkg.attr);1094    if (code != 0) return error.ProcessFailed;1095    output.installDone(npkg.pname);1096}10971098fn systemInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {1099    const config_path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});1100    defer ctx.gpa.free(config_path);1101    const line = api.findSystemPackagesLine(ctx.io, config_path) orelse 1;1102    output.installEditorPrompt(npkg.pname, config_path, line, ctx.cfg.editor);1103    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, config_path, line);1104    if (ctx.cfg.confirm) {1105        if (output.confirm("apply now? ")) {1106            try apply(ctx);1107        }1108    }1109}11101111fn tryPkg(ctx: Ctx, npkg: types.NixPackage) !void {1112    output.tryStart(npkg.pname);1113    output.printSubstep("nix shell nixpkgs#{s}", .{npkg.attr});1114    output.tryExitHint();1115    _ = try exec.nixShellPs1(ctx.io, &ctx.machine, ctx.gpa, npkg.attr, ctx.environ);1116    output.tryDone();1117}11181119pub fn remove(ctx: Ctx) !void {1120    const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1121    output.removeStart(pkg_name);1122    const code = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, pkg_name);1123    if (code != 0) return error.ProcessFailed;1124    output.done();1125}11261127pub fn list(ctx: Ctx) !void {1128    output.listHeader(ctx.machine.name);11291130    // Profile packages: parse `nix profile list --json` into clean name+version1131    // rows instead of dumping nix's verbose multi-line "Name:/Flake attribute:"1132    // blocks.1133    if (exec.profileListJson(ctx.gpa, ctx.io, &ctx.machine) catch null) |json| {1134        defer ctx.gpa.free(json);1135        output.listSection("profile");1136        renderProfileJson(ctx.gpa, json);1137    }11381139    // System packages: the references of /run/current-system/sw, each a1140    // <hash>-<name>-<version> store path.1141    if (exec.systemPackagePaths(ctx.gpa, ctx.io, &ctx.machine) catch null) |paths| {1142        defer ctx.gpa.free(paths);1143        output.blankLine();1144        output.listSection("system");1145        var lines = std.mem.splitScalar(u8, paths, '\n');1146        while (lines.next()) |line| {1147            const t = std.mem.trim(u8, line, " \t\r");1148            if (t.len == 0) continue;1149            const row = pkgFromStorePath(t);1150            // Skip support paths with no parseable version (man pages, wrappers).1151            if (row.version.len == 0) continue;1152            output.listPkg(row.name, row.version);1153        }1154    }1155}11561157const PkgRow = struct { name: []const u8, version: []const u8 };11581159// Split a nix store path basename (<hash>-<name>-<version>) into name + version.1160// Version begins at the first '-' followed by a digit, which reliably lands on1161// the name/version boundary since the 32-char hash and package names start with1162// non-digits.1163fn pkgFromStorePath(path: []const u8) PkgRow {1164    const base = std.fs.path.basename(path);1165    const after_hash = if (base.len > 33 and base[32] == '-') base[33..] else base;1166    var i: usize = 0;1167    while (i + 1 < after_hash.len) : (i += 1) {1168        if (after_hash[i] == '-' and std.ascii.isDigit(after_hash[i + 1])) {1169            return .{ .name = after_hash[0..i], .version = stripOutputSuffix(after_hash[i + 1 ..]) };1170        }1171    }1172    return .{ .name = after_hash, .version = "" };1173}11741175// Multi-output derivations append the output name to the store path (e.g.1176// curl-8.20.0-bin, less-692-man). Strip that suffix so the version column reads1177// as just the version.1178fn stripOutputSuffix(ver: []const u8) []const u8 {1179    const suffixes = [_][]const u8{ "-bin", "-man", "-dev", "-doc", "-lib", "-info", "-out", "-static", "-devdoc" };1180    for (suffixes) |s| {1181        if (std.mem.endsWith(u8, ver, s)) return ver[0 .. ver.len - s.len];1182    }1183    return ver;1184}11851186test "pkgFromStorePath splits name and version at first dash-digit" {1187    const a = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-ripgrep-15.1.0");1188    try std.testing.expectEqualStrings("ripgrep", a.name);1189    try std.testing.expectEqualStrings("15.1.0", a.version);11901191    const b = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-helix-25.01");1192    try std.testing.expectEqualStrings("helix", b.name);1193    try std.testing.expectEqualStrings("25.01", b.version);11941195    // multi-output store paths drop their output-name suffix1196    const c = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-curl-8.20.0-bin");1197    try std.testing.expectEqualStrings("curl", c.name);1198    try std.testing.expectEqualStrings("8.20.0", c.version);1199}12001201fn firstStorePath(el: std.json.Value) ?[]const u8 {1202    if (el != .object) return null;1203    const sp = el.object.get("storePaths") orelse return null;1204    if (sp != .array or sp.array.items.len == 0) return null;1205    const first = sp.array.items[0];1206    return if (first == .string) first.string else null;1207}12081209// `nix profile list --json` has two shapes across nix versions: newer keys each1210// element by name (object), older lists them positionally (array). Handle both.1211fn renderProfileJson(gpa: std.mem.Allocator, json: []const u8) void {1212    const parsed = std.json.parseFromSlice(std.json.Value, gpa, json, .{}) catch return;1213    defer parsed.deinit();1214    if (parsed.value != .object) return;1215    const elements = parsed.value.object.get("elements") orelse return;1216    switch (elements) {1217        .object => |obj| {1218            var it = obj.iterator();1219            while (it.next()) |entry| {1220                const ver = if (firstStorePath(entry.value_ptr.*)) |p| pkgFromStorePath(p).version else "";1221                output.listPkg(entry.key_ptr.*, ver);1222            }1223        },1224        .array => |arr| {1225            for (arr.items) |el| {1226                const path = firstStorePath(el) orelse continue;1227                const row = pkgFromStorePath(path);1228                output.listPkg(row.name, row.version);1229            }1230        },1231        else => {},1232    }1233}12341235pub fn tryCmd(ctx: Ctx) !void {1236    const pkg_name_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1237    const shell_pkg = types.NixPackage{ .attr = pkg_name_arg, .pname = pkg_name_arg, .version = "", .description = "" };1238    try tryPkg(ctx, shell_pkg);1239}12401241// --- Home Manager commands ---12421243const home_help = [_][2][]const u8{1244    .{ "init", "set up home manager for the first time" },1245    .{ "init --switch", "set up and activate immediately" },1246    .{ "apply", "apply home-manager configuration" },1247    .{ "apply --dry", "preview changes without activating" },1248    .{ "back", "roll back one generation" },1249    .{ "history", "list all generations" },1250    .{ "edit", "open home.nix" },1251    .{ "check", "validate without applying" },1252    .{ "diff", "compare the latest two generations" },1253    .{ "packages", "list managed packages" },1254};12551256const HomeGen = struct {1257    number: u32,1258    date: []const u8,1259    time: []const u8,1260    path: []const u8,1261};12621263// `home-manager generations` lines read:1264//   2026-06-01 11:56 : id 765 -> /nix/store/<hash>-home-manager-generation1265// Newest first, so index 0 is the current generation.1266fn parseHomeGenerations(gpa: std.mem.Allocator, out_str: []const u8) ![]HomeGen {1267    var gens: std.ArrayList(HomeGen) = .empty;1268    var lines = std.mem.splitScalar(u8, out_str, '\n');1269    while (lines.next()) |line| {1270        const t = std.mem.trim(u8, line, " \t\r");1271        if (t.len == 0) continue;1272        var it = std.mem.tokenizeAny(u8, t, " \t");1273        const date = it.next() orelse continue;1274        const time = it.next() orelse continue;1275        var number: ?u32 = null;1276        var path: []const u8 = "";1277        while (it.next()) |tok| {1278            if (std.mem.eql(u8, tok, "id")) {1279                if (it.next()) |n| number = std.fmt.parseInt(u32, n, 10) catch null;1280            } else if (std.mem.startsWith(u8, tok, "/nix/store/")) {1281                path = tok;1282            }1283        }1284        const num = number orelse continue;1285        try gens.append(gpa, .{1286            .number = num,1287            .date = try gpa.dupe(u8, date),1288            .time = try gpa.dupe(u8, time),1289            .path = try gpa.dupe(u8, path),1290        });1291    }1292    return gens.toOwnedSlice(gpa);1293}12941295fn freeHomeGens(gpa: std.mem.Allocator, gens: []HomeGen) void {1296    for (gens) |g| {1297        gpa.free(g.date);1298        gpa.free(g.time);1299        gpa.free(g.path);1300    }1301    gpa.free(gens);1302}13031304test "parseHomeGenerations reads id, date and store path" {1305    const a = std.testing.allocator;1306    const sample =1307        \\2026-06-01 11:56 : id 765 -> /nix/store/aaaa-home-manager-generation1308        \\2026-05-31 10:29 : id 764 -> /nix/store/bbbb-home-manager-generation1309    ;1310    const gens = try parseHomeGenerations(a, sample);1311    defer freeHomeGens(a, gens);1312    try std.testing.expectEqual(@as(usize, 2), gens.len);1313    try std.testing.expectEqual(@as(u32, 765), gens[0].number);1314    try std.testing.expectEqualStrings("2026-06-01", gens[0].date);1315    try std.testing.expectEqualStrings("11:56", gens[0].time);1316    try std.testing.expectEqualStrings("/nix/store/aaaa-home-manager-generation", gens[0].path);1317    try std.testing.expectEqual(@as(u32, 764), gens[1].number);1318}13191320// Current (newest) home generation number, or 0 if unavailable.1321fn homeCurrentGen(ctx: Ctx) u32 {1322    const out = exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine) catch return 0;1323    defer ctx.gpa.free(out);1324    const gens = parseHomeGenerations(ctx.gpa, out) catch return 0;1325    defer freeHomeGens(ctx.gpa, gens);1326    return if (gens.len > 0) gens[0].number else 0;1327}13281329pub fn home(ctx: Ctx) !void {1330    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help"))1331        return output.subcommandHelp("home", &home_help, null);13321333    // Home Manager manages the local user's environment. Detection (which binary,1334    // ~/.config/home-manager, $HOME/$USER for the flake ref) all read the LOCAL1335    // host, while exec routes over SSH for a remote machine — so `home --on1336    // <remote>` would decide mode/flake-ref from the wrong box. Refuse it cleanly1337    // rather than acting on a mismatch.1338    if (!ctx.machine.local) {1339        output.homeLocalOnly(ctx.machine.name);1340        return;1341    }13421343    // init runs before mode detection: its whole purpose is bootstrapping a host1344    // that has no home-manager yet, so a .none mode must not short-circuit it.1345    if (std.mem.eql(u8, ctx.sub, "init")) return homeInitCmd(ctx);13461347    const mode = exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ);1348    if (mode == .none) {1349        output.homeNotInstalled();1350        return;1351    }13521353    // apply is the only command meaningful in module mode (it redirects to1354    // `nina apply`); everything else needs the standalone home-manager CLI.1355    if (std.mem.eql(u8, ctx.sub, "apply")) return homeApply(ctx, mode);1356    // edit just opens the local home.nix — fine in module mode too.1357    if (std.mem.eql(u8, ctx.sub, "edit")) return homeEdit(ctx);13581359    if (mode == .module) {1360        output.homeModuleManaged();1361        return;1362    }13631364    if (std.mem.eql(u8, ctx.sub, "back")) return homeBack(ctx);1365    if (std.mem.eql(u8, ctx.sub, "history")) return homeHistory(ctx);1366    if (std.mem.eql(u8, ctx.sub, "check")) return homeCheck(ctx);1367    if (std.mem.eql(u8, ctx.sub, "diff")) return homeDiff(ctx);1368    if (std.mem.eql(u8, ctx.sub, "packages")) return homePackages(ctx);13691370    return output.subcommandHelp("home", &home_help, null);1371}13721373fn homePackages(ctx: Ctx) !void {1374    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1375    defer ctx.gpa.free(out);1376    const gens = try parseHomeGenerations(ctx.gpa, out);1377    defer freeHomeGens(ctx.gpa, gens);13781379    output.homePackagesHeader(ctx.machine.name);1380    if (gens.len == 0 or gens[0].path.len == 0) return;13811382    // The generation's OWN references are home-manager's activation deps1383    // (bash, coreutils, ...), not what the user installed. The user's packages1384    // live one level down, in the `…-home-manager-path` env the generation1385    // references — descend into it and list ITS references. Fall back to the1386    // generation refs if that env isn't present (older home-manager layouts).1387    const gen_refs = exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, gens[0].path) catch return;1388    defer ctx.gpa.free(gen_refs);13891390    var refs = gen_refs;1391    var env_refs: ?[]u8 = null;1392    defer if (env_refs) |e| ctx.gpa.free(e);1393    if (findHomeManagerPath(gen_refs)) |pkg_path| {1394        if (exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, pkg_path)) |e| {1395            env_refs = e;1396            refs = e;1397        } else |_| {}1398    }13991400    // Dedup by name: multi-output derivations (jq, jq-lib, jq-doc) collapse to1401    // the same name after the output suffix is stripped. Keys are slices into1402    // `refs`, valid for this function's lifetime.1403    var seen = std.StringHashMap(void).init(ctx.gpa);1404    defer seen.deinit();1405    var lines = std.mem.splitScalar(u8, refs, '\n');1406    while (lines.next()) |line| {1407        const t = std.mem.trim(u8, line, " \t\r");1408        if (t.len == 0) continue;1409        const row = pkgFromStorePath(t);1410        if (row.version.len == 0) continue;1411        if (std.mem.indexOf(u8, row.name, "home-manager") != null) continue;1412        if (seen.contains(row.name)) continue;1413        seen.put(row.name, {}) catch {};1414        output.listPkg(row.name, row.version);1415    }1416}14171418// The `…-home-manager-path` env among a generation's references — the buildEnv1419// of the user's home.packages. Returns the full store-path line, or null.1420fn findHomeManagerPath(refs: []const u8) ?[]const u8 {1421    var lines = std.mem.splitScalar(u8, refs, '\n');1422    while (lines.next()) |line| {1423        const t = std.mem.trim(u8, line, " \t\r");1424        if (std.mem.indexOf(u8, t, "home-manager-path") != null) return t;1425    }1426    return null;1427}14281429test "findHomeManagerPath picks the env, not the generation or infra" {1430    const refs =1431        \\/nix/store/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-bash-5.31432        \\/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path1433        \\/nix/store/cccccccccccccccccccccccccccccccc-coreutils-9.111434    ;1435    try std.testing.expectEqualStrings(1436        "/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path",1437        findHomeManagerPath(refs).?,1438    );1439    try std.testing.expectEqual(@as(?[]const u8, null), findHomeManagerPath("/nix/store/x-bash-5.3\n"));1440}14411442fn homeDiff(ctx: Ctx) !void {1443    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1444    defer ctx.gpa.free(out);1445    const gens = try parseHomeGenerations(ctx.gpa, out);1446    defer freeHomeGens(ctx.gpa, gens);14471448    // Need two generations and both their store paths to diff their closures.1449    if (gens.len < 2 or gens[0].path.len == 0 or gens[1].path.len == 0) {1450        output.homeNothingToDiff();1451        return;1452    }1453    const newer = gens[0];1454    const older = gens[1];1455    output.homeDiffHeader(older.number, newer.number, ctx.machine.name);1456    if (try exec.diffClosuresPaths(ctx.io, &ctx.machine, ctx.gpa, older.path, newer.path) != 0)1457        return error.ProcessFailed;1458}14591460fn homeCheck(ctx: Ctx) !void {1461    output.homeCheckStart(ctx.machine.name);1462    const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa);1463    if (code != 0) return error.BuildFailed;1464    output.homeCheckOk();1465}14661467fn homeEdit(ctx: Ctx) !void {1468    // Standalone home config lives at ~/.config/home-manager/home.nix; the same1469    // path is what detection keys on for module mode, so it resolves for both.1470    const path = exec.homeNixPath(ctx.gpa, ctx.environ) orelse {1471        errors.error_info.setMessage("could not resolve ~/.config/home-manager/home.nix", .{});1472        return error.ConfigNotFound;1473    };1474    defer ctx.gpa.free(path);1475    output.homeEditOpen(path, ctx.cfg.editor);1476    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);1477}14781479fn homeHistory(ctx: Ctx) !void {1480    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1481    defer ctx.gpa.free(out);1482    const gens = try parseHomeGenerations(ctx.gpa, out);1483    defer freeHomeGens(ctx.gpa, gens);1484    output.homeHistoryHeader(ctx.machine.name);1485    // Newest-first from home-manager; the first row is the current generation.1486    for (gens, 0..) |g, i| output.homeHistoryRow(g.number, g.date, g.time, i == 0);1487}14881489fn homeBack(ctx: Ctx) !void {1490    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1491    defer ctx.gpa.free(out);1492    const gens = try parseHomeGenerations(ctx.gpa, out);1493    defer freeHomeGens(ctx.gpa, gens);14941495    // Newest-first: [0] is current, [1] is the generation to roll back to.1496    if (gens.len < 2) {1497        output.alreadyOldest();1498        return;1499    }1500    const current = gens[0].number;1501    const prev = gens[1].number;15021503    output.homeBackStart(ctx.machine.name, current, prev);1504    if (ctx.cfg.confirm and !output.confirm("")) return;1505    const code = try exec.homeManagerRollback(ctx.io, &ctx.machine, ctx.gpa);1506    if (code != 0) return error.BuildFailed;1507    output.homeBackDone(prev);1508}15091510fn homeInitCmd(ctx: Ctx) !void {1511    var switch_on_init = false;1512    var dir: ?[]const u8 = null;1513    for (ctx.args) |arg| {1514        if (std.mem.eql(u8, arg, "--switch")) {1515            switch_on_init = true;1516        } else if (!std.mem.startsWith(u8, arg, "-")) {1517            dir = arg;1518        }1519    }15201521    // Guard only the default location — a custom dir is the user's call, and1522    // home-manager creates it. Never clobber an existing ~/.config/home-manager.1523    if (dir == null) {1524        if (exec.homeNixPath(ctx.gpa, ctx.environ)) |path| {1525            defer ctx.gpa.free(path);1526            if (exec.pathExists(ctx.io, path)) {1527                output.homeInitExists(path);1528                return;1529            }1530        }1531    }15321533    output.homeInitStart(switch_on_init, dir);1534    const code = try exec.homeManagerInit(ctx.io, &ctx.machine, ctx.gpa, switch_on_init, dir);1535    if (code != 0) return error.BuildFailed;1536    output.homeInitDone(switch_on_init);1537}15381539fn homeApply(ctx: Ctx, mode: exec.HomeManagerMode) !void {1540    // NixOS/flake module: home config is rebuilt by nixos-rebuild — redirect.1541    if (mode == .module) {1542        output.homeModuleManaged();1543        return;1544    }1545    if (ctx.dry) {1546        output.homeApplyDry(ctx.machine.name);1547        const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa);1548        if (code != 0) return error.BuildFailed;1549        output.homeApplyDryDone();1550        return;1551    }15521553    if (!try runPreHook(ctx, "pre-home")) {1554        output.aborted();1555        return error.HookAborted;1556    }15571558    output.homeApplyStart(ctx.machine.name);15591560    // Flake-based home config: switch by attribute with a graceful fallback1561    // chain. A channel-based config (no flake.nix) uses a plain switch.1562    const dir = exec.homeFlakeDir(ctx.gpa, ctx.io, ctx.environ);1563    defer if (dir) |d| ctx.gpa.free(d);1564    if (dir) |d| return homeApplyFlake(ctx, d);15651566    output.printSubstep("home-manager switch", .{});1567    const start = std.Io.Clock.awake.now(ctx.io);1568    const code = try exec.homeManagerSwitch(ctx.io, &ctx.machine, ctx.gpa);1569    if (code != 0) return error.BuildFailed;15701571    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());1572    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));1573    output.homeApplyDone(homeCurrentGen(ctx), elapsed);1574    runPostHook(ctx, "post-home");1575}15761577// Switch a flake-based home config, trying the most specific attribute first:1578//   <dir>#<user>-<arch>-<os>  →  <dir>#<user>  →  <dir>  (home-manager resolves)1579// Each fallback fires only on a missing-attribute error, never on a real build1580// failure. Mirrors how ${USER}-${system} homeConfigurations keys are written.1581fn homeApplyFlake(ctx: Ctx, dir: []const u8) !void {1582    const user = ctx.environ.get("USER") orelse "default";15831584    var refs: std.ArrayList([]const u8) = .empty;1585    defer {1586        for (refs.items) |r| ctx.gpa.free(r);1587        refs.deinit(ctx.gpa);1588    }1589    if (exec.homeManagerAttr(ctx.gpa, ctx.io, &ctx.machine, ctx.environ) catch null) |attr| {1590        defer ctx.gpa.free(attr);1591        try refs.append(ctx.gpa, try std.fmt.allocPrint(ctx.gpa, "{s}#{s}", .{ dir, attr }));1592    }1593    try refs.append(ctx.gpa, try std.fmt.allocPrint(ctx.gpa, "{s}#{s}", .{ dir, user }));1594    try refs.append(ctx.gpa, try ctx.gpa.dupe(u8, dir));15951596    const start = std.Io.Clock.awake.now(ctx.io);1597    for (refs.items, 0..) |ref, i| {1598        output.printSubstep("home-manager switch --flake {s}", .{ref});1599        switch (try exec.homeManagerSwitchFlake(ctx.io, &ctx.machine, ctx.gpa, ref)) {1600            .ok => {1601                const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());1602                const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));1603                output.homeApplyDone(homeCurrentGen(ctx), elapsed);1604                runPostHook(ctx, "post-home");1605                return;1606            },1607            // Attr not defined by the flake — drop to the next candidate.1608            .attr_missing => {1609                if (i + 1 < refs.items.len) output.homeAttrFallback(ref);1610                continue;1611            },1612            .failed => return error.BuildFailed,1613        }1614    }1615    return error.BuildFailed;1616}16171618// --- Service commands ---16191620const service_help = [_][2][]const u8{1621    .{ "list", "list running services" },1622    .{ "logs <svc>", "show service logs" },1623    .{ "status <svc>", "service status" },1624    .{ "start <svc>", "start a service" },1625    .{ "stop <svc>", "stop a service" },1626    .{ "restart <svc>", "restart a service" },1627    .{ "enable <svc>", "enable at boot" },1628    .{ "disable <svc>", "disable at boot" },1629};16301631pub fn service(ctx: Ctx) !void {1632    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");1633    if (std.mem.eql(u8, ctx.sub, "list")) {1634        output.serviceListHeader(ctx.machine.name);1635        const svcs = exec.serviceList(ctx.gpa, ctx.io, &ctx.machine, ctx.user) catch &.{};1636        defer ctx.gpa.free(svcs);1637        for (svcs) |s| output.serviceRow(s);1638        return;1639    }1640    if (std.mem.eql(u8, ctx.sub, "logs")) {1641        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1642        const follow = ctx.args.len > 1 and std.mem.eql(u8, ctx.args[1], "-f");1643        output.serviceLogsHeader(name, ctx.last, ctx.machine.name);1644        _ = try exec.serviceLogs(ctx.io, &ctx.machine, ctx.gpa, name, ctx.last, follow, ctx.user);1645        return;1646    }1647    if (std.mem.eql(u8, ctx.sub, "status")) {1648        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1649        output.serviceVerb("status", name, ctx.machine.name);1650        _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, "status", name, ctx.user);1651        return;1652    }1653    // start/stop/restart/enable/disable1654    const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1655    if (ctx.cfg.confirm and (std.mem.eql(u8, ctx.sub, "stop") or std.mem.eql(u8, ctx.sub, "disable"))) {1656        if (!output.confirm("")) return;1657    }1658    output.serviceVerb(ctx.sub, name, ctx.machine.name);1659    _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, ctx.sub, name, ctx.user);1660    output.serviceDone();1661}16621663// --- Flake commands ---16641665const flake_help = [_][2][]const u8{1666    .{ "init", "create a new flake.nix" },1667    .{ "update", "update flake inputs" },1668    .{ "update <in>", "update a specific input" },1669    .{ "check", "validate the flake" },1670    .{ "show", "inspect flake outputs" },1671    .{ "lock", "regenerate flake.lock" },1672    .{ "clone <url>", "clone a flake repository" },1673};16741675pub fn flake(ctx: Ctx) !void {1676    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("flake", &flake_help, null);1677    if (std.mem.eql(u8, ctx.sub, "update")) {1678        output.flakeUpdateStart();1679        const input: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1680        _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1681        output.flakeLockWritten();1682        return;1683    }1684    if (std.mem.eql(u8, ctx.sub, "check")) {1685        output.flakeCheckStart();1686        const code = try exec.flakeCheck(ctx.io, &ctx.machine, ctx.gpa);1687        if (code == 0) output.flakeValid() else output.checkFailed("");1688        return;1689    }1690    if (std.mem.eql(u8, ctx.sub, "show")) {1691        const json_out = exec.flakeShow(ctx.gpa, ctx.io, &ctx.machine) catch null;1692        if (json_out) |j| {1693            defer ctx.gpa.free(j);1694            output.flakeShowHeader("flake outputs");1695            // Parse and display the flake outputs1696            const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, j, .{}) catch return;1697            defer parsed.deinit();1698            if (parsed.value == .object) {1699                var it = parsed.value.object.iterator();1700                while (it.next()) |entry| {1701                    if (entry.value_ptr.* == .object) {1702                        var inner = entry.value_ptr.object.iterator();1703                        while (inner.next()) |e2| {1704                            const desc = if (e2.value_ptr.* == .object)1705                                if (e2.value_ptr.object.get("description")) |d|1706                                    if (d == .string) d.string else ""1707                                else1708                                    ""1709                            else1710                                "";1711                            output.flakeShowEntry(entry.key_ptr.*, e2.key_ptr.*, desc);1712                        }1713                    }1714                }1715            }1716        }1717        return;1718    }1719    if (std.mem.eql(u8, ctx.sub, "init")) {1720        _ = try exec.flakeInit(ctx.io, &ctx.machine, ctx.gpa);1721        return;1722    }1723    if (std.mem.eql(u8, ctx.sub, "lock")) {1724        _ = try exec.flakeLock(ctx.io, &ctx.machine, ctx.gpa);1725        return;1726    }1727    if (std.mem.eql(u8, ctx.sub, "clone")) {1728        const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1729        _ = try exec.flakeClone(ctx.io, &ctx.machine, ctx.gpa, url);1730        return;1731    }1732}17331734// --- Store commands ---17351736const store_help = [_][2][]const u8{1737    .{ "info", "store size and counts" },1738    .{ "path <attr>", "store path of a package" },1739    .{ "gc", "collect garbage" },1740    .{ "optimise", "deduplicate store paths with hard links" },1741    .{ "verify", "verify store integrity" },1742    .{ "repair", "repair corrupted paths" },1743};17441745pub fn store(ctx: Ctx) !void {1746    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("store", &store_help, null);1747    if (std.mem.eql(u8, ctx.sub, "gc")) {1748        _ = try exec.storeGc(ctx.io, &ctx.machine, ctx.gpa);1749        return;1750    }1751    // Accept both spellings — optimise (en) and optimize (us).1752    if (std.mem.eql(u8, ctx.sub, "optimise") or std.mem.eql(u8, ctx.sub, "optimize")) {1753        output.storeOptimiseStart(ctx.machine.name);1754        _ = try exec.storeOptimise(ctx.io, &ctx.machine, ctx.gpa);1755        output.storeOptimiseDone();1756        return;1757    }1758    if (std.mem.eql(u8, ctx.sub, "verify")) {1759        output.storeVerifyStart();1760        _ = try exec.storeVerify(ctx.io, &ctx.machine, ctx.gpa);1761        return;1762    }1763    if (std.mem.eql(u8, ctx.sub, "repair")) {1764        if (ctx.cfg.confirm and !output.confirm("")) return;1765        output.storeRepairStart();1766        _ = try exec.storeRepair(ctx.io, &ctx.machine, ctx.gpa);1767        return;1768    }1769    if (std.mem.eql(u8, ctx.sub, "info")) {1770        const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1771        output.storeInfo(si);1772        return;1773    }1774    if (std.mem.eql(u8, ctx.sub, "path")) {1775        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1776        const path = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, attr);1777        defer ctx.gpa.free(path);1778        output.storePath(path);1779        return;1780    }1781    // default: info1782    const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1783    output.storeInfo(si);1784}17851786// --- Channel commands ---17871788const channel_help = [_][2][]const u8{1789    .{ "list", "list channels" },1790    .{ "add <url> [name]", "add a channel" },1791    .{ "remove <name>", "remove a channel" },1792    .{ "update", "update all channels" },1793};17941795pub fn channel(ctx: Ctx) !void {1796    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("channel", &channel_help, null);1797    // On a flake-managed system, nix-channel operations generally don't apply.1798    if (flakeSystem(ctx)) output.flakeChannelNote();1799    if (std.mem.eql(u8, ctx.sub, "list")) {1800        output.channelListHeader(ctx.machine.name);1801        const chans = try exec.channelList(ctx.gpa, ctx.io, &ctx.machine);1802        defer ctx.gpa.free(chans);1803        for (chans) |ch| output.channelRow(ch);1804        return;1805    }1806    if (std.mem.eql(u8, ctx.sub, "add")) {1807        const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1808        const name = if (ctx.args.len > 1) ctx.args[1] else "";1809        _ = try exec.channelAdd(ctx.io, &ctx.machine, ctx.gpa, url, name);1810        output.channelDone();1811        return;1812    }1813    if (std.mem.eql(u8, ctx.sub, "remove")) {1814        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1815        _ = try exec.channelRemove(ctx.io, &ctx.machine, ctx.gpa, name);1816        output.channelDone();1817        return;1818    }1819    if (std.mem.eql(u8, ctx.sub, "update")) {1820        return channelUpdateCmd(ctx);1821    }1822}18231824// --- Profile commands ---18251826pub fn profile(ctx: Ctx) !void {1827    if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {1828        output.profileListHeader();1829        const out = exec.profileList(ctx.gpa, ctx.io, &ctx.machine) catch null;1830        if (out) |o| {1831            defer ctx.gpa.free(o);1832            var lines = std.mem.splitScalar(u8, o, '\n');1833            while (lines.next()) |line| {1834                const t = std.mem.trim(u8, line, " \t\r");1835                if (t.len == 0) continue;1836                output.profileRow(t, "", "");1837            }1838        }1839        return;1840    }1841    if (std.mem.eql(u8, ctx.sub, "install")) {1842        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1843        _ = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, attr);1844        output.done();1845        return;1846    }1847    if (std.mem.eql(u8, ctx.sub, "remove")) {1848        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1849        _ = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, attr);1850        output.done();1851        return;1852    }1853    if (std.mem.eql(u8, ctx.sub, "upgrade")) {1854        _ = try exec.profileUpgrade(ctx.io, &ctx.machine, ctx.gpa);1855        output.done();1856        return;1857    }1858}18591860// --- Pkg commands ---18611862const pkg_help = [_][2][]const u8{1863    .{ "why <pkg>", "what pulled it in" },1864    .{ "deps <pkg>", "direct dependencies" },1865    .{ "size <pkg>", "closure size" },1866    .{ "path <pkg>", "store path" },1867    .{ "closure <pkg>", "full closure" },1868};18691870pub fn pkg(ctx: Ctx) !void {1871    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("pkg", &pkg_help, null);1872    const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1873    if (std.mem.eql(u8, ctx.sub, "why")) {1874        if (try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1875        return;1876    }1877    if (std.mem.eql(u8, ctx.sub, "deps")) {1878        if (try exec.pkgDeps(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1879        return;1880    }1881    if (std.mem.eql(u8, ctx.sub, "size")) {1882        const s = try exec.pkgSize(ctx.gpa, ctx.io, &ctx.machine, name);1883        defer ctx.gpa.free(s);1884        output.pkgResult("size", s);1885        return;1886    }1887    if (std.mem.eql(u8, ctx.sub, "path")) {1888        const p = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, name);1889        defer ctx.gpa.free(p);1890        output.pkgResult("path", p);1891        return;1892    }1893    if (std.mem.eql(u8, ctx.sub, "closure")) {1894        if (try exec.pkgClosure(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1895        return;1896    }1897}18981899// Top-level alias for `nina pkg why <pkg>` — surfaces what pulled a package in1900// without the user needing to know about the `pkg` subgroup.1901pub fn why(ctx: Ctx) !void {1902    const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1903    if (try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1904}19051906// --- Pin / Unpin ---19071908pub fn pin(ctx: Ctx) !void {1909    const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1910    const commit = if (ctx.args.len > 1) ctx.args[1] else return error.Internal;1911    exec.editFlakeLock(ctx.gpa, input, commit) catch return error.ProcessFailed;1912    output.pinDone(input, commit);1913}19141915pub fn unpin(ctx: Ctx) !void {1916    const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1917    _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1918    output.unpinDone(input);1919}19201921// --- Hash / Fetch ---19221923pub fn hash(ctx: Ctx) !void {1924    const path = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1925    const h = try exec.nixHash(ctx.gpa, ctx.io, &ctx.machine, path);1926    defer ctx.gpa.free(h);1927    output.hashResult(std.mem.trim(u8, h, " \t\n\r"));1928}19291930pub fn fetch(ctx: Ctx) !void {1931    const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1932    const h = try exec.nixFetch(ctx.gpa, ctx.io, &ctx.machine, url);1933    defer ctx.gpa.free(h);1934    output.fetchResult(std.mem.trim(u8, h, " \t\n\r"), url);1935}19361937// --- Build / Run ---19381939pub fn build(ctx: Ctx) !void {1940    const attr: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1941    output.buildStart(attr orelse "default");1942    const code = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, attr);1943    if (code != 0) return error.BuildFailed;1944    output.buildDone();1945}19461947pub fn runCmd(ctx: Ctx) !void {1948    const pkg_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1949    output.runStart(pkg_arg);1950    _ = try exec.nixRun(ctx.io, &ctx.machine, ctx.gpa, pkg_arg);1951}19521953// --- Hello ---19541955pub fn hello(ctx: Ctx) !void {1956    output.hello(ctx.cfg.machines);1957}19581959const ConfigKind = enum { flake, channel, none };19601961// Scan the conventional /etc/nixos for a flake.nix (flake-based) or a1962// configuration.nix (channel-based) to pre-fill the wizard's defaults.1963fn scanConfig(io: std.Io) ConfigKind {1964    if (exec.pathExists(io, "/etc/nixos/flake.nix")) return .flake;1965    if (exec.pathExists(io, "/etc/nixos/configuration.nix")) return .channel;1966    return .none;1967}19681969// Runs when the config is absent on first invocation (interactive TTY only).1970// Scans for an existing nixos config, detects flake vs channel, and offers a1971// smart default path — flake-ness is detected, never asked.1972pub fn firstRunWizard(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1973    output.firstRunBanner();1974    output.firstRunNoConfig();19751976    var name_buf: [256]u8 = undefined;1977    var path_buf: [256]u8 = undefined;19781979    const machine_name = output.firstRunPrompt("machine name", "my-machine", &name_buf);19801981    output.firstRunScanning();1982    const kind = scanConfig(io);1983    switch (kind) {1984        .flake => output.firstRunDetected("/etc/nixos/flake.nix", true),1985        .channel => output.firstRunDetected("/etc/nixos/configuration.nix", false),1986        .none => output.firstRunNoneFound(),1987    }19881989    // Detected systems default to /etc/nixos (press enter to confirm); when1990    // nothing was found, leave the default empty so the user must type a path.1991    const default_path: []const u8 = if (kind == .none) "" else "/etc/nixos";1992    const config_path = output.firstRunPromptDefault("config path", default_path, kind != .none, &path_buf);19931994    // Re-detect at the chosen path in case the user pointed elsewhere — flake.nix1995    // there means a flake system, recorded so channel commands warn appropriately.1996    const use_flakes = exec.dirHasFlake(gpa, io, config_path);19971998    const conf_path = try config.configPath(gpa, environ);1999    defer gpa.free(conf_path);2000    if (std.fs.path.dirname(conf_path)) |dir| exec.ensureDir(gpa, io, dir);20012002    // `flake` is a top-level config field, so it must precede the [machine] block.2003    const flake_line = if (use_flakes) "flake = true\n" else "";2004    var content_buf: [1024]u8 = undefined;2005    const content = try std.fmt.bufPrint(2006        &content_buf,2007        "{s}[machine]\nname = {s}\nconfig = {s}\nlocal = true\n",2008        .{ flake_line, machine_name, config_path },2009    );20102011    const file = std.Io.Dir.createFile(.cwd(), io, conf_path, .{}) catch {2012        errors.error_info.setMessage("could not write {s}", .{conf_path});2013        return error.Internal;2014    };2015    defer file.close(io);2016    file.writePositionalAll(io, content, 0) catch {2017        errors.error_info.setMessage("could not write {s}", .{conf_path});2018        return error.Internal;2019    };20202021    output.firstRunWritten(conf_path);2022}20232024pub fn setup(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {2025    // Create the config first if it doesn't exist. This makes `nina setup`2026    // a complete onboarding command — not just a nix-features check. Any legacy2027    // ~/.nina.conf is migrated to the XDG path before we decide to run the wizard.2028    config.migrateLegacyConfig(gpa, io, environ);2029    if (config.configPath(gpa, environ)) |conf_path| {2030        defer gpa.free(conf_path);2031        if (std.Io.Dir.openFile(.cwd(), io, conf_path, .{})) |f| {2032            f.close(io);2033        } else |_| {2034            try firstRunWizard(gpa, io, environ);2035            errors.error_info.reset();2036        }2037    } else |_| {}20382039    output.setupCheck();2040    const status = exec.checkNixFeatures(gpa, io, environ);2041    output.setupFeatures(status.nix_command, status.flakes);20422043    if (status.allEnabled()) {2044        output.setupAllSet();2045        api.ensureRegistryPinned(gpa, io, environ);2046        return;2047    }20482049    // On NixOS the features belong in configuration.nix (the declarative,2050    // permanent home), not ~/.config/nix/nix.conf. Offer to add the one line;2051    // the user runs the rebuild. We don't pin the registry here because the2052    // features aren't live until that rebuild lands.2053    if (exec.isNixOS(io)) {2054        const conf_path = "/etc/nixos/configuration.nix";2055        if (exec.nixosConfigEnablesFeatures(gpa, io, conf_path)) {2056            output.setupNixosNeedsRebuild(conf_path);2057            return;2058        }2059        output.setupNixosOffer(exec.NIXOS_FEATURES_LINE, conf_path);2060        if (output.confirmDefaultNo("add it now?")) {2061            if (exec.appendFeaturesToNixosConfig(gpa, io, environ, conf_path)) |_| {2062                output.setupNixosWrote(conf_path);2063            } else |_| {2064                output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);2065            }2066        } else {2067            output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);2068        }2069        return;2070    }20712072    // Non-NixOS: a user-level nix.conf takes effect immediately, no sudo needed.2073    output.setupEnabling();2074    const path = try exec.enableNixFeatures(gpa, io, environ);2075    defer gpa.free(path);20762077    output.setupDone(path);2078    api.ensureRegistryPinned(gpa, io, environ);2079}20802081// --- Log helper ---20822083fn logAction(ctx: Ctx, action: []const u8, gen: u32) void {2084    var ts_buf: [32]u8 = undefined;2085    const ts = nowIso(ctx.io, &ts_buf);2086    var buf: [256]u8 = undefined;2087    const entry = std.fmt.bufPrint(&buf, "{{\"ts\":\"{s}\",\"machine\":\"{s}\",\"command\":\"{s}\",\"outcome\":\"success\",\"gen_before\":null,\"gen_after\":{d},\"duration_ms\":0}}\n", .{2088        ts, ctx.machine.name, action, gen,2089    }) catch return;2090    exec.appendNinaLog(ctx.io, ctx.environ, entry);2091}20922093// Wall-clock UTC as ISO-8601. Uses Io.Clock.real (the settable Unix-epoch clock);2094// Io.Clock.awake is monotonic and unsuitable for timestamps. Falls back to epoch 0.2095fn nowIso(io: std.Io, buf: []u8) []const u8 {2096    const fallback = "1970-01-01T00:00:00Z";2097    const ns = std.Io.Clock.real.now(io).toNanoseconds();2098    if (ns <= 0) return fallback;2099    const secs: u64 = @intCast(@divFloor(ns, 1_000_000_000));2100    const es = std.time.epoch.EpochSeconds{ .secs = secs };2101    const ed = es.getEpochDay();2102    const yd = ed.calculateYearDay();2103    const md = yd.calculateMonthDay();2104    const ds = es.getDaySeconds();2105    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", .{2106        yd.year,              md.month.numeric(),      @as(u32, md.day_index) + 1,2107        ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(),2108    }) catch return fallback;2109}