commands.zig

82.8 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        const add_r = exec.capture(ctx.gpa, ctx.io, &ctx.machine, &.{ "nix", "profile", "add", "--no-write-lock-file", FLAKE_URL }) catch {446            output.updateSelfNixReinstallFailed();447            return;448        };449        defer ctx.gpa.free(add_r.stdout);450        defer ctx.gpa.free(add_r.stderr);451        if (add_r.exit_code != 0) {452            output.raw(add_r.stdout);453            output.raw(add_r.stderr);454            output.updateSelfNixReinstallFailed();455            return;456        }457        output.updateSelfDone(version.VERSION, remote_ver);458        output.updateSelfNixRehash();459        return;460    }461462    const plat_info = blk: {463        const pv = root.object.get("platforms") orelse break :blk null;464        if (pv != .object) break :blk null;465        break :blk pv.object.get(version.PLATFORM);466    };467    if (plat_info == null) {468        output.updateSelfNoPlatform(version.PLATFORM);469        return;470    }471472    const dl_url = blk: {473        const v = plat_info.?.object.get("url") orelse {474            output.printWarning("malformed release metadata");475            return;476        };477        break :blk switch (v) {478            .string => |s| s,479            else => {480                output.printWarning("malformed release metadata");481                return;482            },483        };484    };485486    const raw_cksum = blk: {487        if (plat_info.?.object.get("blake3")) |v|488            break :blk switch (v) {489                .string => |s| s,490                else => {491                    output.printWarning("malformed release metadata");492                    return;493                },494            };495        if (plat_info.?.object.get("checksum")) |v|496            break :blk switch (v) {497                .string => |s| s,498                else => {499                    output.printWarning("malformed release metadata");500                    return;501                },502            };503        output.printWarning("missing checksum in release metadata");504        return;505    };506    const expected_hex = if (std.mem.startsWith(u8, raw_cksum, "blake3:")) raw_cksum["blake3:".len..] else raw_cksum;507508    if (ctx.cfg.confirm and !output.confirm("")) return;509510    output.updateSelfDownloading(remote_ver, version.PLATFORM);511    const tmp_path = exec.downloadToTemp(ctx.gpa, ctx.io, dl_url) catch {512        output.printWarning("download failed — check your connection and try again");513        return;514    };515    defer ctx.gpa.free(tmp_path);516517    output.updateSelfVerifying();518    exec.verifyAndInstall(ctx.gpa, ctx.io, tmp_path, expected_hex, install_path) catch |e| switch (e) {519        error.ChecksumMismatch => {520            output.updateSelfChecksumFailed();521            return;522        },523        else => return e,524    };525526    output.updateSelfDone(version.VERSION, remote_ver);527}528529// archives.json covers every version between current and latest; the manifest's530// `notes` field only ever describes the single latest release. Try the full-range531// changelog first so an update spanning several versions doesn't collapse down to532// just the newest one's notes — fall back to `notes` only when the archive has533// nothing (e.g. releases predating archives.json, or the fetch failing).534fn updateReleaseNotes(gpa: std.mem.Allocator, io: std.Io, root: std.json.Value, source_url: []const u8, current: []const u8, latest: []const u8) ![]u8 {535    if (buildKeprArchiveReleaseNotes(gpa, io, source_url, current, latest) catch null) |notes| {536        if (std.mem.trim(u8, notes, " \t\r\n").len > 0) return notes;537        gpa.free(notes);538    }539    if (releaseNotesFromMetadata(gpa, root)) |notes| return notes;540    return gpa.dupe(u8, "");541}542543fn releaseNotesFromMetadata(gpa: std.mem.Allocator, root: std.json.Value) ?[]u8 {544    if (root != .object) return null;545    // `notes` is the one canonical manifest field. The retired `release_notes`546    // and `changelog` fallbacks are gone — Kepr now emits `notes` everywhere, and547    // releases that predate `--notes` fall back to archives.json in the caller.548    const v = root.object.get("notes") orelse return null;549    return switch (v) {550        .string => |s| gpa.dupe(u8, s) catch null,551        else => null,552    };553}554555fn buildKeprArchiveReleaseNotes(gpa: std.mem.Allocator, io: std.Io, source_url: []const u8, current: []const u8, latest: []const u8) ![]u8 {556    const archive_url = try keprArchiveUrl(gpa, source_url);557    defer gpa.free(archive_url);558559    const body = exec.fetchUrl(gpa, io, archive_url) catch return gpa.dupe(u8, "");560    defer gpa.free(body);561562    return releaseNotesFromArchiveJson(gpa, body, current, latest);563}564565fn keprArchiveUrl(gpa: std.mem.Allocator, source_url: []const u8) ![]u8 {566    const scheme = std.mem.indexOf(u8, source_url, "://") orelse return error.InvalidUpdateSource;567    const path_start = std.mem.indexOfScalarPos(u8, source_url, scheme + 3, '/') orelse return error.InvalidUpdateSource;568    const origin = source_url[0..path_start];569    const path = source_url[path_start..];570    if (!std.mem.startsWith(u8, path, "/api/")) return error.InvalidUpdateSource;571572    const after_api = path["/api/".len..];573    const repo_end = std.mem.indexOfScalar(u8, after_api, '/') orelse return error.InvalidUpdateSource;574    const repo = after_api[0..repo_end];575    if (repo.len == 0) return error.InvalidUpdateSource;576577    return std.fmt.allocPrint(gpa, "{s}/{s}/archives.json?limit=100", .{ origin, repo });578}579580// Saves arrive newest-first. For each version in the update range we want the OLDEST581// save message (the one that introduced that version), not a follow-up cleanup/docs save.582// We overwrite the tracked message on each occurrence, so the final stored value per583// version is always the oldest (last-seen in a newest-first stream).584fn releaseNotesFromArchiveJson(gpa: std.mem.Allocator, body: []const u8, current: []const u8, latest: []const u8) ![]u8 {585    const parsed = std.json.parseFromSlice(std.json.Value, gpa, body, .{}) catch return gpa.dupe(u8, "");586    defer parsed.deinit();587588    if (parsed.value != .object) return gpa.dupe(u8, "");589    const saves_v = parsed.value.object.get("saves") orelse return gpa.dupe(u8, "");590    if (saves_v != .array) return gpa.dupe(u8, "");591592    // version string → oldest message seen (both slice into parsed JSON, valid until deinit)593    var best_msg = std.StringHashMap([]const u8).init(gpa);594    defer best_msg.deinit();595    var order: std.ArrayList([]const u8) = .empty;596    defer order.deinit(gpa);597598    for (saves_v.array.items) |save| {599        if (save != .object) continue;600        const ver_v = save.object.get("version") orelse continue;601        const msg_v = save.object.get("message") orelse continue;602        if (ver_v != .string or msg_v != .string) continue;603        const ver = ver_v.string;604        const msg = std.mem.trim(u8, msg_v.string, " \t\r\n");605        if (msg.len == 0 or !versionInUpdateRange(ver, current, latest)) continue;606607        const entry = try best_msg.getOrPut(ver);608        if (!entry.found_existing) try order.append(gpa, ver);609        // Always overwrite: saves are newest-first, so last write = oldest save = version-intro message610        entry.value_ptr.* = msg;611    }612613    if (order.items.len == 0) return gpa.dupe(u8, "");614615    var out: std.ArrayList(u8) = .empty;616    errdefer out.deinit(gpa);617    for (order.items) |ver| {618        const msg = best_msg.get(ver).?;619        // Use only the first line as the summary; multi-line saves may have implementation details below620        const summary_end = std.mem.indexOf(u8, msg, "\n") orelse msg.len;621        const summary = std.mem.trim(u8, msg[0..summary_end], " \t\r");622        if (summary.len == 0) continue;623        try appendLine(&out, gpa, "## {s}\n", .{ver});624        try appendLine(&out, gpa, "- {s}\n\n", .{summary});625    }626627    if (out.items.len == 0) {628        out.deinit(gpa);629        return gpa.dupe(u8, "");630    }631    return out.toOwnedSlice(gpa);632}633634fn appendLine(out: *std.ArrayList(u8), gpa: std.mem.Allocator, comptime template: []const u8, args: anytype) !void {635    const line = try std.fmt.allocPrint(gpa, template, args);636    defer gpa.free(line);637    try out.appendSlice(gpa, line);638}639640fn versionInUpdateRange(candidate: []const u8, current: []const u8, latest: []const u8) bool {641    const cand = parseSemver(candidate) orelse return std.mem.eql(u8, candidate, latest);642    const cur = parseSemver(current) orelse return std.mem.eql(u8, candidate, latest);643    const lat = parseSemver(latest) orelse return std.mem.eql(u8, candidate, latest);644    return compareSemver(cand, cur) == .gt and compareSemver(cand, lat) != .gt;645}646647fn remoteVersionNewer(current: []const u8, remote: []const u8) bool {648    const cur = parseSemver(current) orelse return !std.mem.eql(u8, current, remote);649    const rem = parseSemver(remote) orelse return !std.mem.eql(u8, current, remote);650    return compareSemver(rem, cur) == .gt;651}652653const VersionOrder = enum { lt, eq, gt };654655fn compareSemver(a: Semver, b: Semver) VersionOrder {656    if (a.major != b.major) return if (a.major < b.major) .lt else .gt;657    if (a.minor != b.minor) return if (a.minor < b.minor) .lt else .gt;658    if (a.patch != b.patch) return if (a.patch < b.patch) .lt else .gt;659    return .eq;660}661662fn parseSemver(raw: []const u8) ?Semver {663    const v = if (std.mem.startsWith(u8, raw, "v")) raw[1..] else raw;664    var it = std.mem.splitScalar(u8, v, '.');665    const major_s = it.next() orelse return null;666    const minor_s = it.next() orelse return null;667    const patch_s = it.next() orelse return null;668    if (it.next() != null) return null;669    return .{670        .major = std.fmt.parseInt(u32, major_s, 10) catch return null,671        .minor = std.fmt.parseInt(u32, minor_s, 10) catch return null,672        .patch = std.fmt.parseInt(u32, patch_s, 10) catch return null,673    };674}675676test "versionInUpdateRange includes only newer versions through latest" {677    try std.testing.expect(versionInUpdateRange("3.2.3", "3.1.9", "3.2.3"));678    try std.testing.expect(versionInUpdateRange("3.2.0", "3.1.9", "3.2.3"));679    try std.testing.expect(!versionInUpdateRange("3.1.9", "3.1.9", "3.2.3"));680    try std.testing.expect(!versionInUpdateRange("3.2.4", "3.1.9", "3.2.3"));681}682683test "remoteVersionNewer does not offer downgrades" {684    try std.testing.expect(remoteVersionNewer("3.2.3", "3.2.4"));685    try std.testing.expect(!remoteVersionNewer("3.2.4", "3.2.3"));686    try std.testing.expect(!remoteVersionNewer("3.2.4", "3.2.4"));687}688689test "releaseNotesFromArchiveJson uses oldest save per version" {690    // Saves arrive newest-first. For 3.2.3, the newest save is a CONTINUITY update;691    // the oldest is the version-intro message. We expect the intro message in the output.692    const body =693        \\{694        \\  "saves": [695        \\    {"version":"3.2.3","message":"wip: record verification in CONTINUITY"},696        \\    {"version":"3.2.1","message":"old release"},697        \\    {"version":"3.2.3","message":"add streaming deflate path"}698        \\  ]699        \\}700    ;701    const notes = try releaseNotesFromArchiveJson(std.testing.allocator, body, "3.2.1", "3.2.3");702    defer std.testing.allocator.free(notes);703704    try std.testing.expect(std.mem.indexOf(u8, notes, "## 3.2.3") != null);705    try std.testing.expect(std.mem.indexOf(u8, notes, "- add streaming deflate path") != null);706    try std.testing.expect(std.mem.indexOf(u8, notes, "CONTINUITY") == null);707    try std.testing.expect(std.mem.indexOf(u8, notes, "old release") == null);708}709710test "releaseNotesFromMetadata reads canonical notes and ignores retired keys" {711    const a = std.testing.allocator;712713    // Canonical field is read.714    {715        var parsed = try std.json.parseFromSlice(std.json.Value, a, "{\"notes\":\"colored progress bar\"}", .{});716        defer parsed.deinit();717        const got = releaseNotesFromMetadata(a, parsed.value).?;718        defer a.free(got);719        try std.testing.expectEqualStrings("colored progress bar", got);720    }721722    // Retired field names are no longer honoured — they fall through to null so723    // the caller drops to the archives.json derivation instead.724    {725        var parsed = try std.json.parseFromSlice(std.json.Value, a, "{\"release_notes\":\"x\",\"changelog\":\"y\"}", .{});726        defer parsed.deinit();727        try std.testing.expect(releaseNotesFromMetadata(a, parsed.value) == null);728    }729}730731// nina goodbye — clean uninstall. Three install paths:732// - nix profile (binary in nix store with a profile element) → nix profile remove733// - koh build or source build (plain binary on PATH) → delete the file734pub fn goodbye(ctx: Ctx) !void {735    output.goodbyeStart();736737    var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;738    const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {739        errors.error_info.setMessage("could not determine install path", .{});740        return error.Internal;741    };742743    // A binary outside the nix store is a koh build or source build — delete it.744    if (!std.mem.startsWith(u8, install_path, "/nix/store/")) {745        output.goodbyeFile(install_path);746        if (ctx.cfg.confirm and !output.confirm("")) return;747        std.Io.Dir.deleteFileAbsolute(ctx.io, install_path) catch |e| {748            errors.error_info.setMessage("could not remove {s}", .{install_path});749            return e;750        };751        output.goodbyeDone();752        return;753    }754755    // Binary is in the nix store — find and remove the profile element.756    const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);757    defer {758        if (nina_element) |n| ctx.gpa.free(n);759    }760761    if (nina_element == null) {762        errors.error_info.setMessage("nina not found in nix profile — was it installed via 'nix profile add'?", .{});763        return error.Internal;764    }765766    output.goodbyeNix();767    if (ctx.cfg.confirm and !output.confirm("")) return;768    const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "remove", nina_element.? }) catch {769        output.goodbyeFailed("nix profile remove failed");770        return;771    };772    if (ec != 0) {773        output.goodbyeFailed("nix profile remove failed");774        return;775    }776    output.goodbyeDone();777}778779fn channelUpdateCmd(ctx: Ctx) !void {780    output.updateStart(ctx.machine.name);781    _ = try exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa);782    output.updateDone();783}784785pub fn upgrade(ctx: Ctx) !void {786    if (!try runPreHook(ctx, "pre-upgrade")) {787        output.aborted();788        return error.HookAborted;789    }790791    output.upgradeStart(ctx.machine.name);792    // Flake systems update inputs (flake.lock); channel systems update channels.793    // Running nix-channel --update on a flake system is a no-op at best. The794    // rebuild below is already flake-aware via exec.nixosRebuildSwitch.795    if (flakeSystem(ctx)) {796        output.printSubstep("updating flake inputs", .{});797        _ = exec.flakeUpdateAt(ctx.io, &ctx.machine, ctx.gpa, ctx.machine.config_path) catch {};798    } else {799        output.printSubstep("updating channels", .{});800        _ = exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa) catch {};801    }802    output.printSubstep("rebuilding", .{});803    output.buildPanelInit();804    const start = std.Io.Clock.awake.now(ctx.io);805    var panel = output.BuildPanel{};806    const code = exec.nixosRebuildSwitchWithPanel(ctx.io, &ctx.machine, ctx.gpa, &panel) catch |e| {807        output.buildPanelClear();808        return e;809    };810    output.buildPanelClear();811    if (code != 0) {812        output.applyFailed("");813        return error.BuildFailed;814    }815    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());816    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));817    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;818    output.applyDone(gen, elapsed, false);819    runPostHook(ctx, "post-upgrade");820}821822pub fn log(ctx: Ctx) !void {823    output.logHeader(ctx.machine.name);824    const content = exec.readNinaLog(ctx.gpa, ctx.io, ctx.environ, ctx.last) catch {825        // No log yet — that's fine826        return;827    };828    defer ctx.gpa.free(content);829    var lines = std.mem.splitScalar(u8, content, '\n');830    while (lines.next()) |line| {831        const t = std.mem.trim(u8, line, " \t\r");832        if (t.len == 0) continue;833        if (t[0] == '{') {834            renderJsonLogLine(ctx.gpa, t);835        } else {836            // legacy tab-separated format837            var parts = std.mem.tokenizeScalar(u8, t, '\t');838            const date = parts.next() orelse continue;839            const time = parts.next() orelse "";840            const action = parts.next() orelse "";841            const detail = parts.next() orelse "";842            output.logRow(date, time, action, detail);843        }844    }845}846847// The on-disk log is JSON Lines: {"ts","machine","command","outcome","gen_after",...}.848// Render ts -> date/time columns, command -> action, outcome(+gen) -> detail.849fn renderJsonLogLine(gpa: std.mem.Allocator, line: []const u8) void {850    const parsed = std.json.parseFromSlice(std.json.Value, gpa, line, .{}) catch {851        output.logRow(line, "", "", ""); // unparseable — show raw rather than drop852        return;853    };854    defer parsed.deinit();855    if (parsed.value != .object) return;856    const o = parsed.value.object;857858    const ts = jsonStr(o, "ts");859    const date = if (ts.len >= 10) ts[0..10] else ts;860    const time = if (ts.len >= 16) ts[11..16] else "";861    const action = jsonStr(o, "command");862    const outcome = jsonStr(o, "outcome");863864    var buf: [160]u8 = undefined;865    var detail: []const u8 = outcome;866    if (o.get("gen_after")) |g| {867        if (g == .integer) {868            detail = std.fmt.bufPrint(&buf, "{s}   -> gen {d}", .{ outcome, g.integer }) catch outcome;869        }870    }871    output.logRow(date, time, action, detail);872}873874fn jsonStr(o: std.json.ObjectMap, key: []const u8) []const u8 {875    if (o.get(key)) |v| {876        if (v == .string) return v.string;877    }878    return "";879}880881pub fn edit(ctx: Ctx) !void {882    // `edit` is multi-word, so a bare positional ("hardware") arrives as ctx.sub.883    // hardware-configuration.nix is generated by nixos-generate-config and warns884    // against hand-editing — refuse rather than silently opening the wrong file.885    if (std.mem.eql(u8, ctx.sub, "hardware")) {886        output.editHardwareWarning();887        return;888    }889890    // --dir opens the whole config directory (for editors that work better with891    // a folder open), as root so root-owned config trees like /etc/nixos work.892    var open_dir = false;893    for (ctx.args) |arg| {894        if (std.mem.eql(u8, arg, "--dir")) open_dir = true;895    }896    if (open_dir) {897        output.editOpen(ctx.machine.config_path, ctx.cfg.editor);898        _ = try exec.openEditorSudo(ctx.io, ctx.gpa, ctx.cfg.editor, ctx.machine.config_path);899        return;900    }901902    const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});903    defer ctx.gpa.free(path);904    output.editOpen(path, ctx.cfg.editor);905    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);906}907908pub fn fmt(ctx: Ctx) !void {909    const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});910    defer ctx.gpa.free(path);911    if (ctx.check) {912        const code = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, true);913        if (code != 0) output.fmtNeedsFormat() else output.fmtDone();914        return;915    }916    output.fmtStart(path);917    _ = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, false);918    output.fmtDone();919}920921pub fn repl(ctx: Ctx) !void {922    output.replStart();923    _ = try exec.nixRepl(ctx.io, &ctx.machine, ctx.gpa);924}925926pub fn develop(ctx: Ctx) !void {927    if (std.mem.eql(u8, ctx.sub, "show")) {928        _ = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, null);929        return;930    }931    const run_cmd: ?[]const u8 = if (ctx.args.len > 0 and std.mem.eql(u8, ctx.sub, "run"))932        ctx.args[0]933    else934        null;935    output.developStart(&.{});936    _ = try exec.nixDevelopPs1(ctx.io, &ctx.machine, ctx.gpa, run_cmd, ctx.environ);937    output.developDone();938}939940pub fn info(ctx: Ctx) !void {941    output.infoHeader(ctx.machine.name);942    const nixos_ver = exec.systemInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");943    defer ctx.gpa.free(nixos_ver);944    output.infoRow("nixos", std.mem.trim(u8, nixos_ver, " \t\n\r"));945946    const kernel = exec.kernelInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");947    defer ctx.gpa.free(kernel);948    output.infoRow("kernel", std.mem.trim(u8, kernel, " \t\n\r"));949950    const uptime = exec.uptimeInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");951    defer ctx.gpa.free(uptime);952    output.infoRow("uptime", std.mem.trim(u8, uptime, " \t\n\r"));953}954955pub fn boot(ctx: Ctx) !void {956    output.bootHeader(ctx.machine.name);957    const entries = exec.bootEntries(ctx.gpa, ctx.io, &ctx.machine) catch &.{};958    defer ctx.gpa.free(entries);959    for (entries, 0..) |entry, i| output.bootEntry(entry, i);960}961962pub fn searchCmd(ctx: Ctx) !void {963    const query = if (ctx.args.len > 0) ctx.args[0] else "";964    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);965    const selected = try search_tui.run(ctx.gpa, ctx.io, query, .packages, ctx.environ);966    if (selected) |npkg| try selectAndInstall(ctx, npkg);967}968969pub fn optionCmd(ctx: Ctx) !void {970    const query = if (ctx.args.len > 0) ctx.args[0] else "";971    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);972    _ = try search_tui.run(ctx.gpa, ctx.io, query, .options, ctx.environ);973}974975pub fn install(ctx: Ctx) !void {976    const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;977978    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);979980    // Search for the package to get the attr981    const pkgs = api.searchPackages(ctx.gpa, ctx.io, ctx.environ, pkg_name) catch {982        errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});983        errors.error_info.setSuggestion("nina search {s}", .{pkg_name});984        return error.PackageNotFound;985    };986987    if (pkgs.len == 0) {988        // No matches — likely a typo. Suggest the closest real package and offer it.989        if (closestPackage(ctx, pkg_name)) |sugg| {990            output.didYouMean(pkg_name, sugg.pname);991            if (output.confirm("")) try selectAndInstall(ctx, sugg);992            return;993        }994        errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});995        errors.error_info.setSuggestion("nina search {s}", .{pkg_name});996        return error.PackageNotFound;997    }998999    // Prefer an exact name match over the first search result — `install ripgrep`1000    // must pick "ripgrep", not the alphabetically-first match like "repgrep".1001    var found = pkgs[0];1002    for (pkgs) |p| {1003        if (std.mem.eql(u8, p.pname, pkg_name)) {1004            found = p;1005            break;1006        }1007    }1008    try selectAndInstall(ctx, found);1009}10101011// Find the real package whose name is closest to a not-found query (typo help).1012// Typos usually keep the leading characters, so gather candidates with a prefix1013// search and rank by edit distance; return the best only if it's typo-close.1014fn closestPackage(ctx: Ctx, query: []const u8) ?types.NixPackage {1015    if (query.len < 2) return null;1016    var candidates = api.searchPackages(ctx.gpa, ctx.io, ctx.environ, query[0..@min(query.len, 4)]) catch &.{};1017    if (candidates.len == 0 and query.len > 2) {1018        candidates = api.searchPackages(ctx.gpa, ctx.io, ctx.environ, query[0..2]) catch &.{};1019    }1020    if (candidates.len == 0) return null;10211022    var best: ?types.NixPackage = null;1023    var best_dist: usize = std.math.maxInt(usize);1024    for (candidates) |p| {1025        const d = editDistance(query, p.pname);1026        if (d > 0 and d < best_dist) {1027            best_dist = d;1028            best = p;1029        }1030    }1031    // Only suggest a genuinely close name, scaled to query length.1032    const threshold = @max(@as(usize, 2), query.len / 3);1033    return if (best_dist <= threshold) best else null;1034}10351036// Case-insensitive Levenshtein distance. Names longer than the row buffer are1037// treated as far away (never suggested).1038fn editDistance(a: []const u8, b: []const u8) usize {1039    const n = b.len;1040    if (a.len == 0) return n;1041    if (n == 0) return a.len;1042    if (n + 1 > 128) return std.math.maxInt(usize);1043    var prev: [128]usize = undefined;1044    var curr: [128]usize = undefined;1045    var j: usize = 0;1046    while (j <= n) : (j += 1) prev[j] = j;1047    var i: usize = 1;1048    while (i <= a.len) : (i += 1) {1049        curr[0] = i;1050        j = 1;1051        while (j <= n) : (j += 1) {1052            const cost: usize = if (std.ascii.toLower(a[i - 1]) == std.ascii.toLower(b[j - 1])) 0 else 1;1053            curr[j] = @min(prev[j] + 1, @min(curr[j - 1] + 1, prev[j - 1] + cost));1054        }1055        @memcpy(prev[0 .. n + 1], curr[0 .. n + 1]);1056    }1057    return prev[n];1058}10591060test "editDistance is case-insensitive Levenshtein" {1061    try std.testing.expectEqual(@as(usize, 1), editDistance("firefux", "firefox"));1062    try std.testing.expectEqual(@as(usize, 0), editDistance("git", "GIT"));1063    try std.testing.expectEqual(@as(usize, 2), editDistance("fierfox", "firefox"));1064    try std.testing.expectEqual(@as(usize, 7), editDistance("", "firefox"));1065}10661067// Prompt for the install method (profile / system / try) and dispatch. Shared by1068// `nina install <pkg>` and the search widget's Enter-to-select — the letter keys1069// are read here, after the search widget's raw mode is gone, so they don't1070// collide with typing a query.1071fn selectAndInstall(ctx: Ctx, npkg: types.NixPackage) !void {1072    output.installSelectPrompt(npkg.pname, npkg.version);10731074    var choice_buf: [8]u8 = undefined;1075    var choice_len: usize = 0;1076    while (choice_len < choice_buf.len) {1077        const n = std.posix.read(std.posix.STDIN_FILENO, choice_buf[choice_len .. choice_len + 1]) catch break;1078        if (n == 0) break;1079        if (choice_buf[choice_len] == '\n') break;1080        choice_len += 1;1081    }1082    const choice = std.mem.trim(u8, choice_buf[0..choice_len], " \t");10831084    if (choice.len == 0 or choice[0] == 'i' or choice[0] == 'I') {1085        try profileInstallPkg(ctx, npkg);1086    } else if (choice[0] == 's' or choice[0] == 'S') {1087        try systemInstallPkg(ctx, npkg);1088    } else if (choice[0] == 't' or choice[0] == 'T') {1089        try tryPkg(ctx, npkg);1090    }1091}10921093fn profileInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {1094    output.installStart(npkg.pname, .profile);1095    if (npkg.unfree) {1096        output.printSubstep("NIXPKGS_ALLOW_UNFREE=1 nix profile add --impure nixpkgs#{s}", .{npkg.attr});1097        output.printTeach(try std.fmt.allocPrint(ctx.gpa, "NIXPKGS_ALLOW_UNFREE=1 nix profile add --impure nixpkgs#{s}", .{npkg.attr}));1098    } else {1099        output.printSubstep("nix profile add nixpkgs#{s}", .{npkg.attr});1100        output.printTeach(try std.fmt.allocPrint(ctx.gpa, "nix profile add nixpkgs#{s}", .{npkg.attr}));1101    }1102    const code = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, ctx.environ, npkg.attr, npkg.unfree);1103    if (code != 0) return error.ProcessFailed;1104    output.installDone(npkg.pname);1105}11061107fn systemInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {1108    const config_path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});1109    defer ctx.gpa.free(config_path);1110    const line = api.findSystemPackagesLine(ctx.io, config_path) orelse 1;1111    output.installEditorPrompt(npkg.pname, config_path, line, ctx.cfg.editor);1112    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, config_path, line);1113    if (ctx.cfg.confirm) {1114        if (output.confirm("apply now? ")) {1115            try apply(ctx);1116        }1117    }1118}11191120fn tryPkg(ctx: Ctx, npkg: types.NixPackage) !void {1121    output.tryStart(npkg.pname);1122    output.printSubstep("nix shell nixpkgs#{s}", .{npkg.attr});1123    output.tryExitHint();1124    _ = try exec.nixShellPs1(ctx.io, &ctx.machine, ctx.gpa, npkg.attr, ctx.environ);1125    output.tryDone();1126}11271128pub fn remove(ctx: Ctx) !void {1129    const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1130    output.removeStart(pkg_name);1131    const code = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, pkg_name);1132    if (code != 0) return error.ProcessFailed;1133    output.done();1134}11351136pub fn list(ctx: Ctx) !void {1137    output.listHeader(ctx.machine.name);11381139    // Profile packages: parse `nix profile list --json` into clean name+version1140    // rows instead of dumping nix's verbose multi-line "Name:/Flake attribute:"1141    // blocks.1142    if (exec.profileListJson(ctx.gpa, ctx.io, &ctx.machine) catch null) |json| {1143        defer ctx.gpa.free(json);1144        output.listSection("profile");1145        renderProfileJson(ctx.gpa, json);1146    }11471148    // System packages: the references of /run/current-system/sw, each a1149    // <hash>-<name>-<version> store path.1150    if (exec.systemPackagePaths(ctx.gpa, ctx.io, &ctx.machine) catch null) |paths| {1151        defer ctx.gpa.free(paths);1152        output.blankLine();1153        output.listSection("system");1154        var lines = std.mem.splitScalar(u8, paths, '\n');1155        while (lines.next()) |line| {1156            const t = std.mem.trim(u8, line, " \t\r");1157            if (t.len == 0) continue;1158            const row = pkgFromStorePath(t);1159            // Skip support paths with no parseable version (man pages, wrappers).1160            if (row.version.len == 0) continue;1161            output.listPkg(row.name, row.version);1162        }1163    }1164}11651166const PkgRow = struct { name: []const u8, version: []const u8 };11671168// Split a nix store path basename (<hash>-<name>-<version>) into name + version.1169// Version begins at the first '-' followed by a digit, which reliably lands on1170// the name/version boundary since the 32-char hash and package names start with1171// non-digits.1172fn pkgFromStorePath(path: []const u8) PkgRow {1173    const base = std.fs.path.basename(path);1174    const after_hash = if (base.len > 33 and base[32] == '-') base[33..] else base;1175    var i: usize = 0;1176    while (i + 1 < after_hash.len) : (i += 1) {1177        if (after_hash[i] == '-' and std.ascii.isDigit(after_hash[i + 1])) {1178            return .{ .name = after_hash[0..i], .version = stripOutputSuffix(after_hash[i + 1 ..]) };1179        }1180    }1181    return .{ .name = after_hash, .version = "" };1182}11831184// Multi-output derivations append the output name to the store path (e.g.1185// curl-8.20.0-bin, less-692-man). Strip that suffix so the version column reads1186// as just the version.1187fn stripOutputSuffix(ver: []const u8) []const u8 {1188    const suffixes = [_][]const u8{ "-bin", "-man", "-dev", "-doc", "-lib", "-info", "-out", "-static", "-devdoc" };1189    for (suffixes) |s| {1190        if (std.mem.endsWith(u8, ver, s)) return ver[0 .. ver.len - s.len];1191    }1192    return ver;1193}11941195test "pkgFromStorePath splits name and version at first dash-digit" {1196    const a = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-ripgrep-15.1.0");1197    try std.testing.expectEqualStrings("ripgrep", a.name);1198    try std.testing.expectEqualStrings("15.1.0", a.version);11991200    const b = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-helix-25.01");1201    try std.testing.expectEqualStrings("helix", b.name);1202    try std.testing.expectEqualStrings("25.01", b.version);12031204    // multi-output store paths drop their output-name suffix1205    const c = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-curl-8.20.0-bin");1206    try std.testing.expectEqualStrings("curl", c.name);1207    try std.testing.expectEqualStrings("8.20.0", c.version);1208}12091210fn firstStorePath(el: std.json.Value) ?[]const u8 {1211    if (el != .object) return null;1212    const sp = el.object.get("storePaths") orelse return null;1213    if (sp != .array or sp.array.items.len == 0) return null;1214    const first = sp.array.items[0];1215    return if (first == .string) first.string else null;1216}12171218// `nix profile list --json` has two shapes across nix versions: newer keys each1219// element by name (object), older lists them positionally (array). Handle both.1220fn renderProfileJson(gpa: std.mem.Allocator, json: []const u8) void {1221    const parsed = std.json.parseFromSlice(std.json.Value, gpa, json, .{}) catch return;1222    defer parsed.deinit();1223    if (parsed.value != .object) return;1224    const elements = parsed.value.object.get("elements") orelse return;1225    switch (elements) {1226        .object => |obj| {1227            var it = obj.iterator();1228            while (it.next()) |entry| {1229                const ver = if (firstStorePath(entry.value_ptr.*)) |p| pkgFromStorePath(p).version else "";1230                output.listPkg(entry.key_ptr.*, ver);1231            }1232        },1233        .array => |arr| {1234            for (arr.items) |el| {1235                const path = firstStorePath(el) orelse continue;1236                const row = pkgFromStorePath(path);1237                output.listPkg(row.name, row.version);1238            }1239        },1240        else => {},1241    }1242}12431244pub fn tryCmd(ctx: Ctx) !void {1245    const pkg_name_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1246    const shell_pkg = types.NixPackage{ .attr = pkg_name_arg, .pname = pkg_name_arg, .version = "", .description = "" };1247    try tryPkg(ctx, shell_pkg);1248}12491250// --- Home Manager commands ---12511252const home_help = [_][2][]const u8{1253    .{ "init", "set up home manager for the first time" },1254    .{ "init --switch", "set up and activate immediately" },1255    .{ "apply", "apply home-manager configuration" },1256    .{ "apply --dry", "preview changes without activating" },1257    .{ "back", "roll back one generation" },1258    .{ "history", "list all generations" },1259    .{ "edit", "open home.nix" },1260    .{ "check", "validate without applying" },1261    .{ "diff", "compare the latest two generations" },1262    .{ "packages", "list managed packages" },1263};12641265const HomeGen = struct {1266    number: u32,1267    date: []const u8,1268    time: []const u8,1269    path: []const u8,1270};12711272// `home-manager generations` lines read:1273//   2026-06-01 11:56 : id 765 -> /nix/store/<hash>-home-manager-generation1274// Newest first, so index 0 is the current generation.1275fn parseHomeGenerations(gpa: std.mem.Allocator, out_str: []const u8) ![]HomeGen {1276    var gens: std.ArrayList(HomeGen) = .empty;1277    var lines = std.mem.splitScalar(u8, out_str, '\n');1278    while (lines.next()) |line| {1279        const t = std.mem.trim(u8, line, " \t\r");1280        if (t.len == 0) continue;1281        var it = std.mem.tokenizeAny(u8, t, " \t");1282        const date = it.next() orelse continue;1283        const time = it.next() orelse continue;1284        var number: ?u32 = null;1285        var path: []const u8 = "";1286        while (it.next()) |tok| {1287            if (std.mem.eql(u8, tok, "id")) {1288                if (it.next()) |n| number = std.fmt.parseInt(u32, n, 10) catch null;1289            } else if (std.mem.startsWith(u8, tok, "/nix/store/")) {1290                path = tok;1291            }1292        }1293        const num = number orelse continue;1294        try gens.append(gpa, .{1295            .number = num,1296            .date = try gpa.dupe(u8, date),1297            .time = try gpa.dupe(u8, time),1298            .path = try gpa.dupe(u8, path),1299        });1300    }1301    return gens.toOwnedSlice(gpa);1302}13031304fn freeHomeGens(gpa: std.mem.Allocator, gens: []HomeGen) void {1305    for (gens) |g| {1306        gpa.free(g.date);1307        gpa.free(g.time);1308        gpa.free(g.path);1309    }1310    gpa.free(gens);1311}13121313test "parseHomeGenerations reads id, date and store path" {1314    const a = std.testing.allocator;1315    const sample =1316        \\2026-06-01 11:56 : id 765 -> /nix/store/aaaa-home-manager-generation1317        \\2026-05-31 10:29 : id 764 -> /nix/store/bbbb-home-manager-generation1318    ;1319    const gens = try parseHomeGenerations(a, sample);1320    defer freeHomeGens(a, gens);1321    try std.testing.expectEqual(@as(usize, 2), gens.len);1322    try std.testing.expectEqual(@as(u32, 765), gens[0].number);1323    try std.testing.expectEqualStrings("2026-06-01", gens[0].date);1324    try std.testing.expectEqualStrings("11:56", gens[0].time);1325    try std.testing.expectEqualStrings("/nix/store/aaaa-home-manager-generation", gens[0].path);1326    try std.testing.expectEqual(@as(u32, 764), gens[1].number);1327}13281329// Current (newest) home generation number, or 0 if unavailable.1330fn homeCurrentGen(ctx: Ctx) u32 {1331    const out = exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine) catch return 0;1332    defer ctx.gpa.free(out);1333    const gens = parseHomeGenerations(ctx.gpa, out) catch return 0;1334    defer freeHomeGens(ctx.gpa, gens);1335    return if (gens.len > 0) gens[0].number else 0;1336}13371338pub fn home(ctx: Ctx) !void {1339    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help"))1340        return output.subcommandHelp("home", &home_help, null);13411342    // Home Manager manages the local user's environment. Detection (which binary,1343    // ~/.config/home-manager, $HOME/$USER for the flake ref) all read the LOCAL1344    // host, while exec routes over SSH for a remote machine — so `home --on1345    // <remote>` would decide mode/flake-ref from the wrong box. Refuse it cleanly1346    // rather than acting on a mismatch.1347    if (!ctx.machine.local) {1348        output.homeLocalOnly(ctx.machine.name);1349        return;1350    }13511352    // init runs before mode detection: its whole purpose is bootstrapping a host1353    // that has no home-manager yet, so a .none mode must not short-circuit it.1354    if (std.mem.eql(u8, ctx.sub, "init")) return homeInitCmd(ctx);13551356    const mode = exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ);1357    if (mode == .none) {1358        output.homeNotInstalled();1359        return;1360    }13611362    // apply is the only command meaningful in module mode (it redirects to1363    // `nina apply`); everything else needs the standalone home-manager CLI.1364    if (std.mem.eql(u8, ctx.sub, "apply")) return homeApply(ctx, mode);1365    // edit just opens the local home.nix — fine in module mode too.1366    if (std.mem.eql(u8, ctx.sub, "edit")) return homeEdit(ctx);13671368    if (mode == .module) {1369        output.homeModuleManaged();1370        return;1371    }13721373    if (std.mem.eql(u8, ctx.sub, "back")) return homeBack(ctx);1374    if (std.mem.eql(u8, ctx.sub, "history")) return homeHistory(ctx);1375    if (std.mem.eql(u8, ctx.sub, "check")) return homeCheck(ctx);1376    if (std.mem.eql(u8, ctx.sub, "diff")) return homeDiff(ctx);1377    if (std.mem.eql(u8, ctx.sub, "packages")) return homePackages(ctx);13781379    return output.subcommandHelp("home", &home_help, null);1380}13811382fn homePackages(ctx: Ctx) !void {1383    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1384    defer ctx.gpa.free(out);1385    const gens = try parseHomeGenerations(ctx.gpa, out);1386    defer freeHomeGens(ctx.gpa, gens);13871388    output.homePackagesHeader(ctx.machine.name);1389    if (gens.len == 0 or gens[0].path.len == 0) return;13901391    // The generation's OWN references are home-manager's activation deps1392    // (bash, coreutils, ...), not what the user installed. The user's packages1393    // live one level down, in the `…-home-manager-path` env the generation1394    // references — descend into it and list ITS references. Fall back to the1395    // generation refs if that env isn't present (older home-manager layouts).1396    const gen_refs = exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, gens[0].path) catch return;1397    defer ctx.gpa.free(gen_refs);13981399    var refs = gen_refs;1400    var env_refs: ?[]u8 = null;1401    defer if (env_refs) |e| ctx.gpa.free(e);1402    if (findHomeManagerPath(gen_refs)) |pkg_path| {1403        if (exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, pkg_path)) |e| {1404            env_refs = e;1405            refs = e;1406        } else |_| {}1407    }14081409    // Dedup by name: multi-output derivations (jq, jq-lib, jq-doc) collapse to1410    // the same name after the output suffix is stripped. Keys are slices into1411    // `refs`, valid for this function's lifetime.1412    var seen = std.StringHashMap(void).init(ctx.gpa);1413    defer seen.deinit();1414    var lines = std.mem.splitScalar(u8, refs, '\n');1415    while (lines.next()) |line| {1416        const t = std.mem.trim(u8, line, " \t\r");1417        if (t.len == 0) continue;1418        const row = pkgFromStorePath(t);1419        if (row.version.len == 0) continue;1420        if (std.mem.indexOf(u8, row.name, "home-manager") != null) continue;1421        if (seen.contains(row.name)) continue;1422        seen.put(row.name, {}) catch {};1423        output.listPkg(row.name, row.version);1424    }1425}14261427// The `…-home-manager-path` env among a generation's references — the buildEnv1428// of the user's home.packages. Returns the full store-path line, or null.1429fn findHomeManagerPath(refs: []const u8) ?[]const u8 {1430    var lines = std.mem.splitScalar(u8, refs, '\n');1431    while (lines.next()) |line| {1432        const t = std.mem.trim(u8, line, " \t\r");1433        if (std.mem.indexOf(u8, t, "home-manager-path") != null) return t;1434    }1435    return null;1436}14371438test "findHomeManagerPath picks the env, not the generation or infra" {1439    const refs =1440        \\/nix/store/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-bash-5.31441        \\/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path1442        \\/nix/store/cccccccccccccccccccccccccccccccc-coreutils-9.111443    ;1444    try std.testing.expectEqualStrings(1445        "/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path",1446        findHomeManagerPath(refs).?,1447    );1448    try std.testing.expectEqual(@as(?[]const u8, null), findHomeManagerPath("/nix/store/x-bash-5.3\n"));1449}14501451fn homeDiff(ctx: Ctx) !void {1452    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1453    defer ctx.gpa.free(out);1454    const gens = try parseHomeGenerations(ctx.gpa, out);1455    defer freeHomeGens(ctx.gpa, gens);14561457    // Need two generations and both their store paths to diff their closures.1458    if (gens.len < 2 or gens[0].path.len == 0 or gens[1].path.len == 0) {1459        output.homeNothingToDiff();1460        return;1461    }1462    const newer = gens[0];1463    const older = gens[1];1464    output.homeDiffHeader(older.number, newer.number, ctx.machine.name);1465    if (try exec.diffClosuresPaths(ctx.io, &ctx.machine, ctx.gpa, older.path, newer.path) != 0)1466        return error.ProcessFailed;1467}14681469fn homeCheck(ctx: Ctx) !void {1470    output.homeCheckStart(ctx.machine.name);1471    const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa);1472    if (code != 0) return error.BuildFailed;1473    output.homeCheckOk();1474}14751476fn homeEdit(ctx: Ctx) !void {1477    // Standalone home config lives at ~/.config/home-manager/home.nix; the same1478    // path is what detection keys on for module mode, so it resolves for both.1479    const path = exec.homeNixPath(ctx.gpa, ctx.environ) orelse {1480        errors.error_info.setMessage("could not resolve ~/.config/home-manager/home.nix", .{});1481        return error.ConfigNotFound;1482    };1483    defer ctx.gpa.free(path);1484    output.homeEditOpen(path, ctx.cfg.editor);1485    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);1486}14871488fn homeHistory(ctx: Ctx) !void {1489    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1490    defer ctx.gpa.free(out);1491    const gens = try parseHomeGenerations(ctx.gpa, out);1492    defer freeHomeGens(ctx.gpa, gens);1493    output.homeHistoryHeader(ctx.machine.name);1494    // Newest-first from home-manager; the first row is the current generation.1495    for (gens, 0..) |g, i| output.homeHistoryRow(g.number, g.date, g.time, i == 0);1496}14971498fn homeBack(ctx: Ctx) !void {1499    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1500    defer ctx.gpa.free(out);1501    const gens = try parseHomeGenerations(ctx.gpa, out);1502    defer freeHomeGens(ctx.gpa, gens);15031504    // Newest-first: [0] is current, [1] is the generation to roll back to.1505    if (gens.len < 2) {1506        output.alreadyOldest();1507        return;1508    }1509    const current = gens[0].number;1510    const prev = gens[1].number;15111512    output.homeBackStart(ctx.machine.name, current, prev);1513    if (ctx.cfg.confirm and !output.confirm("")) return;1514    const code = try exec.homeManagerRollback(ctx.io, &ctx.machine, ctx.gpa);1515    if (code != 0) return error.BuildFailed;1516    output.homeBackDone(prev);1517}15181519fn homeInitCmd(ctx: Ctx) !void {1520    var switch_on_init = false;1521    var dir: ?[]const u8 = null;1522    for (ctx.args) |arg| {1523        if (std.mem.eql(u8, arg, "--switch")) {1524            switch_on_init = true;1525        } else if (!std.mem.startsWith(u8, arg, "-")) {1526            dir = arg;1527        }1528    }15291530    // Guard only the default location — a custom dir is the user's call, and1531    // home-manager creates it. Never clobber an existing ~/.config/home-manager.1532    if (dir == null) {1533        if (exec.homeNixPath(ctx.gpa, ctx.environ)) |path| {1534            defer ctx.gpa.free(path);1535            if (exec.pathExists(ctx.io, path)) {1536                output.homeInitExists(path);1537                return;1538            }1539        }1540    }15411542    output.homeInitStart(switch_on_init, dir);1543    const code = try exec.homeManagerInit(ctx.io, &ctx.machine, ctx.gpa, switch_on_init, dir);1544    if (code != 0) return error.BuildFailed;1545    output.homeInitDone(switch_on_init);1546}15471548fn homeApply(ctx: Ctx, mode: exec.HomeManagerMode) !void {1549    // NixOS/flake module: home config is rebuilt by nixos-rebuild — redirect.1550    if (mode == .module) {1551        output.homeModuleManaged();1552        return;1553    }1554    if (ctx.dry) {1555        output.homeApplyDry(ctx.machine.name);1556        const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa);1557        if (code != 0) return error.BuildFailed;1558        output.homeApplyDryDone();1559        return;1560    }15611562    if (!try runPreHook(ctx, "pre-home")) {1563        output.aborted();1564        return error.HookAborted;1565    }15661567    output.homeApplyStart(ctx.machine.name);15681569    // Flake-based home config: switch by attribute with a graceful fallback1570    // chain. A channel-based config (no flake.nix) uses a plain switch.1571    const dir = exec.homeFlakeDir(ctx.gpa, ctx.io, ctx.environ);1572    defer if (dir) |d| ctx.gpa.free(d);1573    if (dir) |d| return homeApplyFlake(ctx, d);15741575    output.printSubstep("home-manager switch", .{});1576    const start = std.Io.Clock.awake.now(ctx.io);1577    const code = try exec.homeManagerSwitch(ctx.io, &ctx.machine, ctx.gpa);1578    if (code != 0) return error.BuildFailed;15791580    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());1581    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));1582    output.homeApplyDone(homeCurrentGen(ctx), elapsed);1583    runPostHook(ctx, "post-home");1584}15851586// Switch a flake-based home config, trying the most specific attribute first:1587//   <dir>#<user>-<arch>-<os>  →  <dir>#<user>  →  <dir>  (home-manager resolves)1588// Each fallback fires only on a missing-attribute error, never on a real build1589// failure. Mirrors how ${USER}-${system} homeConfigurations keys are written.1590fn homeApplyFlake(ctx: Ctx, dir: []const u8) !void {1591    const user = ctx.environ.get("USER") orelse "default";15921593    var refs: std.ArrayList([]const u8) = .empty;1594    defer {1595        for (refs.items) |r| ctx.gpa.free(r);1596        refs.deinit(ctx.gpa);1597    }1598    if (exec.homeManagerAttr(ctx.gpa, ctx.io, &ctx.machine, ctx.environ) catch null) |attr| {1599        defer ctx.gpa.free(attr);1600        try refs.append(ctx.gpa, try std.fmt.allocPrint(ctx.gpa, "{s}#{s}", .{ dir, attr }));1601    }1602    try refs.append(ctx.gpa, try std.fmt.allocPrint(ctx.gpa, "{s}#{s}", .{ dir, user }));1603    try refs.append(ctx.gpa, try ctx.gpa.dupe(u8, dir));16041605    const start = std.Io.Clock.awake.now(ctx.io);1606    for (refs.items, 0..) |ref, i| {1607        output.printSubstep("home-manager switch --flake {s}", .{ref});1608        switch (try exec.homeManagerSwitchFlake(ctx.io, &ctx.machine, ctx.gpa, ref)) {1609            .ok => {1610                const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());1611                const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));1612                output.homeApplyDone(homeCurrentGen(ctx), elapsed);1613                runPostHook(ctx, "post-home");1614                return;1615            },1616            // Attr not defined by the flake — drop to the next candidate.1617            .attr_missing => {1618                if (i + 1 < refs.items.len) output.homeAttrFallback(ref);1619                continue;1620            },1621            .failed => return error.BuildFailed,1622        }1623    }1624    return error.BuildFailed;1625}16261627// --- Service commands ---16281629const service_help = [_][2][]const u8{1630    .{ "list", "list running services" },1631    .{ "logs <svc>", "show service logs" },1632    .{ "status <svc>", "service status" },1633    .{ "start <svc>", "start a service" },1634    .{ "stop <svc>", "stop a service" },1635    .{ "restart <svc>", "restart a service" },1636    .{ "enable <svc>", "enable at boot" },1637    .{ "disable <svc>", "disable at boot" },1638};16391640pub fn service(ctx: Ctx) !void {1641    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");1642    if (std.mem.eql(u8, ctx.sub, "list")) {1643        output.serviceListHeader(ctx.machine.name);1644        const svcs = exec.serviceList(ctx.gpa, ctx.io, &ctx.machine, ctx.user) catch &.{};1645        defer ctx.gpa.free(svcs);1646        for (svcs) |s| output.serviceRow(s);1647        return;1648    }1649    if (std.mem.eql(u8, ctx.sub, "logs")) {1650        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1651        const follow = ctx.args.len > 1 and std.mem.eql(u8, ctx.args[1], "-f");1652        output.serviceLogsHeader(name, ctx.last, ctx.machine.name);1653        _ = try exec.serviceLogs(ctx.io, &ctx.machine, ctx.gpa, name, ctx.last, follow, ctx.user);1654        return;1655    }1656    if (std.mem.eql(u8, ctx.sub, "status")) {1657        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1658        output.serviceVerb("status", name, ctx.machine.name);1659        _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, "status", name, ctx.user);1660        return;1661    }1662    // start/stop/restart/enable/disable1663    const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1664    if (ctx.cfg.confirm and (std.mem.eql(u8, ctx.sub, "stop") or std.mem.eql(u8, ctx.sub, "disable"))) {1665        if (!output.confirm("")) return;1666    }1667    output.serviceVerb(ctx.sub, name, ctx.machine.name);1668    _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, ctx.sub, name, ctx.user);1669    output.serviceDone();1670}16711672// --- Flake commands ---16731674const flake_help = [_][2][]const u8{1675    .{ "init", "create a new flake.nix" },1676    .{ "update", "update flake inputs" },1677    .{ "update <in>", "update a specific input" },1678    .{ "check", "validate the flake" },1679    .{ "show", "inspect flake outputs" },1680    .{ "lock", "regenerate flake.lock" },1681    .{ "clone <url>", "clone a flake repository" },1682};16831684pub fn flake(ctx: Ctx) !void {1685    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("flake", &flake_help, null);1686    if (std.mem.eql(u8, ctx.sub, "update")) {1687        output.flakeUpdateStart();1688        const input: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1689        _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1690        output.flakeLockWritten();1691        return;1692    }1693    if (std.mem.eql(u8, ctx.sub, "check")) {1694        output.flakeCheckStart();1695        const code = try exec.flakeCheck(ctx.io, &ctx.machine, ctx.gpa);1696        if (code == 0) output.flakeValid() else output.checkFailed("");1697        return;1698    }1699    if (std.mem.eql(u8, ctx.sub, "show")) {1700        const json_out = exec.flakeShow(ctx.gpa, ctx.io, &ctx.machine) catch null;1701        if (json_out) |j| {1702            defer ctx.gpa.free(j);1703            output.flakeShowHeader("flake outputs");1704            // Parse and display the flake outputs1705            const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, j, .{}) catch return;1706            defer parsed.deinit();1707            if (parsed.value == .object) {1708                var it = parsed.value.object.iterator();1709                while (it.next()) |entry| {1710                    if (entry.value_ptr.* == .object) {1711                        var inner = entry.value_ptr.object.iterator();1712                        while (inner.next()) |e2| {1713                            const desc = if (e2.value_ptr.* == .object)1714                                if (e2.value_ptr.object.get("description")) |d|1715                                    if (d == .string) d.string else ""1716                                else1717                                    ""1718                            else1719                                "";1720                            output.flakeShowEntry(entry.key_ptr.*, e2.key_ptr.*, desc);1721                        }1722                    }1723                }1724            }1725        }1726        return;1727    }1728    if (std.mem.eql(u8, ctx.sub, "init")) {1729        _ = try exec.flakeInit(ctx.io, &ctx.machine, ctx.gpa);1730        return;1731    }1732    if (std.mem.eql(u8, ctx.sub, "lock")) {1733        _ = try exec.flakeLock(ctx.io, &ctx.machine, ctx.gpa);1734        return;1735    }1736    if (std.mem.eql(u8, ctx.sub, "clone")) {1737        const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1738        _ = try exec.flakeClone(ctx.io, &ctx.machine, ctx.gpa, url);1739        return;1740    }1741}17421743// --- Store commands ---17441745const store_help = [_][2][]const u8{1746    .{ "info", "store size and counts" },1747    .{ "path <attr>", "store path of a package" },1748    .{ "gc", "collect garbage" },1749    .{ "optimise", "deduplicate store paths with hard links" },1750    .{ "verify", "verify store integrity" },1751    .{ "repair", "repair corrupted paths" },1752};17531754pub fn store(ctx: Ctx) !void {1755    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("store", &store_help, null);1756    if (std.mem.eql(u8, ctx.sub, "gc")) {1757        _ = try exec.storeGc(ctx.io, &ctx.machine, ctx.gpa);1758        return;1759    }1760    // Accept both spellings — optimise (en) and optimize (us).1761    if (std.mem.eql(u8, ctx.sub, "optimise") or std.mem.eql(u8, ctx.sub, "optimize")) {1762        output.storeOptimiseStart(ctx.machine.name);1763        _ = try exec.storeOptimise(ctx.io, &ctx.machine, ctx.gpa);1764        output.storeOptimiseDone();1765        return;1766    }1767    if (std.mem.eql(u8, ctx.sub, "verify")) {1768        output.storeVerifyStart();1769        _ = try exec.storeVerify(ctx.io, &ctx.machine, ctx.gpa);1770        return;1771    }1772    if (std.mem.eql(u8, ctx.sub, "repair")) {1773        if (ctx.cfg.confirm and !output.confirm("")) return;1774        output.storeRepairStart();1775        _ = try exec.storeRepair(ctx.io, &ctx.machine, ctx.gpa);1776        return;1777    }1778    if (std.mem.eql(u8, ctx.sub, "info")) {1779        const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1780        output.storeInfo(si);1781        return;1782    }1783    if (std.mem.eql(u8, ctx.sub, "path")) {1784        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1785        const path = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, attr);1786        defer ctx.gpa.free(path);1787        output.storePath(path);1788        return;1789    }1790    // default: info1791    const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1792    output.storeInfo(si);1793}17941795// --- Channel commands ---17961797const channel_help = [_][2][]const u8{1798    .{ "list", "list channels" },1799    .{ "add <url> [name]", "add a channel" },1800    .{ "remove <name>", "remove a channel" },1801    .{ "update", "update all channels" },1802};18031804pub fn channel(ctx: Ctx) !void {1805    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("channel", &channel_help, null);1806    // On a flake-managed system, nix-channel operations generally don't apply.1807    if (flakeSystem(ctx)) output.flakeChannelNote();1808    if (std.mem.eql(u8, ctx.sub, "list")) {1809        output.channelListHeader(ctx.machine.name);1810        const chans = try exec.channelList(ctx.gpa, ctx.io, &ctx.machine);1811        defer ctx.gpa.free(chans);1812        for (chans) |ch| output.channelRow(ch);1813        return;1814    }1815    if (std.mem.eql(u8, ctx.sub, "add")) {1816        const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1817        const name = if (ctx.args.len > 1) ctx.args[1] else "";1818        _ = try exec.channelAdd(ctx.io, &ctx.machine, ctx.gpa, url, name);1819        output.channelDone();1820        return;1821    }1822    if (std.mem.eql(u8, ctx.sub, "remove")) {1823        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1824        _ = try exec.channelRemove(ctx.io, &ctx.machine, ctx.gpa, name);1825        output.channelDone();1826        return;1827    }1828    if (std.mem.eql(u8, ctx.sub, "update")) {1829        return channelUpdateCmd(ctx);1830    }1831}18321833// --- Profile commands ---18341835pub fn profile(ctx: Ctx) !void {1836    if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {1837        output.profileListHeader();1838        const out = exec.profileList(ctx.gpa, ctx.io, &ctx.machine) catch null;1839        if (out) |o| {1840            defer ctx.gpa.free(o);1841            var lines = std.mem.splitScalar(u8, o, '\n');1842            while (lines.next()) |line| {1843                const t = std.mem.trim(u8, line, " \t\r");1844                if (t.len == 0) continue;1845                output.profileRow(t, "", "");1846            }1847        }1848        return;1849    }1850    if (std.mem.eql(u8, ctx.sub, "install")) {1851        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1852        _ = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, ctx.environ, attr, false);1853        output.done();1854        return;1855    }1856    if (std.mem.eql(u8, ctx.sub, "remove")) {1857        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1858        _ = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, attr);1859        output.done();1860        return;1861    }1862    if (std.mem.eql(u8, ctx.sub, "upgrade")) {1863        _ = try exec.profileUpgrade(ctx.io, &ctx.machine, ctx.gpa);1864        output.done();1865        return;1866    }1867}18681869// --- Pkg commands ---18701871const pkg_help = [_][2][]const u8{1872    .{ "why <pkg>", "what pulled it in" },1873    .{ "deps <pkg>", "direct dependencies" },1874    .{ "size <pkg>", "closure size" },1875    .{ "path <pkg>", "store path" },1876    .{ "closure <pkg>", "full closure" },1877};18781879pub fn pkg(ctx: Ctx) !void {1880    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("pkg", &pkg_help, null);1881    const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1882    if (std.mem.eql(u8, ctx.sub, "why")) {1883        if (try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1884        return;1885    }1886    if (std.mem.eql(u8, ctx.sub, "deps")) {1887        if (try exec.pkgDeps(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1888        return;1889    }1890    if (std.mem.eql(u8, ctx.sub, "size")) {1891        const s = try exec.pkgSize(ctx.gpa, ctx.io, &ctx.machine, name);1892        defer ctx.gpa.free(s);1893        output.pkgResult("size", s);1894        return;1895    }1896    if (std.mem.eql(u8, ctx.sub, "path")) {1897        const p = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, name);1898        defer ctx.gpa.free(p);1899        output.pkgResult("path", p);1900        return;1901    }1902    if (std.mem.eql(u8, ctx.sub, "closure")) {1903        if (try exec.pkgClosure(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1904        return;1905    }1906}19071908// Top-level alias for `nina pkg why <pkg>` — surfaces what pulled a package in1909// without the user needing to know about the `pkg` subgroup.1910pub fn why(ctx: Ctx) !void {1911    const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1912    if (try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1913}19141915// --- Pin / Unpin ---19161917pub fn pin(ctx: Ctx) !void {1918    const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1919    const commit = if (ctx.args.len > 1) ctx.args[1] else return error.Internal;1920    exec.editFlakeLock(ctx.gpa, input, commit) catch return error.ProcessFailed;1921    output.pinDone(input, commit);1922}19231924pub fn unpin(ctx: Ctx) !void {1925    const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1926    _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1927    output.unpinDone(input);1928}19291930// --- Hash / Fetch ---19311932pub fn hash(ctx: Ctx) !void {1933    const path = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1934    const h = try exec.nixHash(ctx.gpa, ctx.io, &ctx.machine, path);1935    defer ctx.gpa.free(h);1936    output.hashResult(std.mem.trim(u8, h, " \t\n\r"));1937}19381939pub fn fetch(ctx: Ctx) !void {1940    const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1941    const h = try exec.nixFetch(ctx.gpa, ctx.io, &ctx.machine, url);1942    defer ctx.gpa.free(h);1943    output.fetchResult(std.mem.trim(u8, h, " \t\n\r"), url);1944}19451946// --- Build / Run ---19471948pub fn build(ctx: Ctx) !void {1949    const attr: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1950    output.buildStart(attr orelse "default");1951    const code = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, attr);1952    if (code != 0) return error.BuildFailed;1953    output.buildDone();1954}19551956pub fn runCmd(ctx: Ctx) !void {1957    const pkg_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1958    output.runStart(pkg_arg);1959    _ = try exec.nixRun(ctx.io, &ctx.machine, ctx.gpa, pkg_arg);1960}19611962// --- Hello ---19631964pub fn hello(ctx: Ctx) !void {1965    output.hello(ctx.cfg.machines);1966}19671968const ConfigKind = enum { flake, channel, none };19691970// Scan the conventional /etc/nixos for a flake.nix (flake-based) or a1971// configuration.nix (channel-based) to pre-fill the wizard's defaults.1972fn scanConfig(io: std.Io) ConfigKind {1973    if (exec.pathExists(io, "/etc/nixos/flake.nix")) return .flake;1974    if (exec.pathExists(io, "/etc/nixos/configuration.nix")) return .channel;1975    return .none;1976}19771978// Runs when the config is absent on first invocation (interactive TTY only).1979// Scans for an existing nixos config, detects flake vs channel, and offers a1980// smart default path — flake-ness is detected, never asked.1981pub fn firstRunWizard(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1982    output.firstRunBanner();1983    output.firstRunNoConfig();19841985    var name_buf: [256]u8 = undefined;1986    var path_buf: [256]u8 = undefined;19871988    const machine_name = output.firstRunPrompt("machine name", "my-machine", &name_buf);19891990    output.firstRunScanning();1991    const kind = scanConfig(io);1992    switch (kind) {1993        .flake => output.firstRunDetected("/etc/nixos/flake.nix", true),1994        .channel => output.firstRunDetected("/etc/nixos/configuration.nix", false),1995        .none => output.firstRunNoneFound(),1996    }19971998    // Detected systems default to /etc/nixos (press enter to confirm); when1999    // nothing was found, leave the default empty so the user must type a path.2000    const default_path: []const u8 = if (kind == .none) "" else "/etc/nixos";2001    const config_path = output.firstRunPromptDefault("config path", default_path, kind != .none, &path_buf);20022003    // Re-detect at the chosen path in case the user pointed elsewhere — flake.nix2004    // there means a flake system, recorded so channel commands warn appropriately.2005    const use_flakes = exec.dirHasFlake(gpa, io, config_path);20062007    const conf_path = try config.configPath(gpa, environ);2008    defer gpa.free(conf_path);2009    if (std.fs.path.dirname(conf_path)) |dir| exec.ensureDir(gpa, io, dir);20102011    // `flake` is a top-level config field, so it must precede the [machine] block.2012    const flake_line = if (use_flakes) "flake = true\n" else "";2013    var content_buf: [1024]u8 = undefined;2014    const content = try std.fmt.bufPrint(2015        &content_buf,2016        "{s}[machine]\nname = {s}\nconfig = {s}\nlocal = true\n",2017        .{ flake_line, machine_name, config_path },2018    );20192020    const file = std.Io.Dir.createFile(.cwd(), io, conf_path, .{}) catch {2021        errors.error_info.setMessage("could not write {s}", .{conf_path});2022        return error.Internal;2023    };2024    defer file.close(io);2025    file.writePositionalAll(io, content, 0) catch {2026        errors.error_info.setMessage("could not write {s}", .{conf_path});2027        return error.Internal;2028    };20292030    output.firstRunWritten(conf_path);2031}20322033pub fn setup(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {2034    // Create the config first if it doesn't exist. This makes `nina setup`2035    // a complete onboarding command — not just a nix-features check. Any legacy2036    // ~/.nina.conf is migrated to the XDG path before we decide to run the wizard.2037    config.migrateLegacyConfig(gpa, io, environ);2038    if (config.configPath(gpa, environ)) |conf_path| {2039        defer gpa.free(conf_path);2040        if (std.Io.Dir.openFile(.cwd(), io, conf_path, .{})) |f| {2041            f.close(io);2042        } else |_| {2043            try firstRunWizard(gpa, io, environ);2044            errors.error_info.reset();2045        }2046    } else |_| {}20472048    output.setupCheck();2049    const status = exec.checkNixFeatures(gpa, io, environ);2050    output.setupFeatures(status.nix_command, status.flakes);20512052    if (status.allEnabled()) {2053        output.setupAllSet();2054        api.ensureRegistryPinned(gpa, io, environ);2055        return;2056    }20572058    // On NixOS the features belong in configuration.nix (the declarative,2059    // permanent home), not ~/.config/nix/nix.conf. Offer to add the one line;2060    // the user runs the rebuild. We don't pin the registry here because the2061    // features aren't live until that rebuild lands.2062    if (exec.isNixOS(io)) {2063        const conf_path = "/etc/nixos/configuration.nix";2064        if (exec.nixosConfigEnablesFeatures(gpa, io, conf_path)) {2065            output.setupNixosNeedsRebuild(conf_path);2066            return;2067        }2068        output.setupNixosOffer(exec.NIXOS_FEATURES_LINE, conf_path);2069        if (output.confirmDefaultNo("add it now?")) {2070            if (exec.appendFeaturesToNixosConfig(gpa, io, environ, conf_path)) |_| {2071                output.setupNixosWrote(conf_path);2072            } else |_| {2073                output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);2074            }2075        } else {2076            output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);2077        }2078        return;2079    }20802081    // Non-NixOS: a user-level nix.conf takes effect immediately, no sudo needed.2082    output.setupEnabling();2083    const path = try exec.enableNixFeatures(gpa, io, environ);2084    defer gpa.free(path);20852086    output.setupDone(path);2087    api.ensureRegistryPinned(gpa, io, environ);2088}20892090// --- Log helper ---20912092fn logAction(ctx: Ctx, action: []const u8, gen: u32) void {2093    var ts_buf: [32]u8 = undefined;2094    const ts = nowIso(ctx.io, &ts_buf);2095    var buf: [256]u8 = undefined;2096    const entry = std.fmt.bufPrint(&buf, "{{\"ts\":\"{s}\",\"machine\":\"{s}\",\"command\":\"{s}\",\"outcome\":\"success\",\"gen_before\":null,\"gen_after\":{d},\"duration_ms\":0}}\n", .{2097        ts, ctx.machine.name, action, gen,2098    }) catch return;2099    exec.appendNinaLog(ctx.io, ctx.environ, entry);2100}21012102// Wall-clock UTC as ISO-8601. Uses Io.Clock.real (the settable Unix-epoch clock);2103// Io.Clock.awake is monotonic and unsuitable for timestamps. Falls back to epoch 0.2104fn nowIso(io: std.Io, buf: []u8) []const u8 {2105    const fallback = "1970-01-01T00:00:00Z";2106    const ns = std.Io.Clock.real.now(io).toNanoseconds();2107    if (ns <= 0) return fallback;2108    const secs: u64 = @intCast(@divFloor(ns, 1_000_000_000));2109    const es = std.time.epoch.EpochSeconds{ .secs = secs };2110    const ed = es.getEpochDay();2111    const yd = ed.calculateYearDay();2112    const md = yd.calculateMonthDay();2113    const ds = es.getDaySeconds();2114    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", .{2115        yd.year,              md.month.numeric(),      @as(u32, md.day_index) + 1,2116        ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(),2117    }) catch return fallback;2118}