commands.zig

83.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";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    passthrough: []const []const u8, // unrecognized flags, forwarded verbatim to the wrapped nix command31    sub: []const u8, // subcommand (e.g. "list" in "service list")32    dry: bool,33    check: bool,34    no_apply: bool,35    all: bool,36    last: u32,37    json: bool,38    user: bool, // --user: operate on user (vs system) services39};4041// A system is flake-managed when the config says so OR a flake.nix is present in42// the config dir. Detection means a fresh channel user who points nina at a flake43// dir gets the right behavior without editing config first.44fn flakeSystem(ctx: Ctx) bool {45    return ctx.cfg.flake or exec.configHasFlake(ctx.gpa, ctx.io, &ctx.machine);46}4748fn runPreHook(ctx: Ctx, hook_name: []const u8) !bool {49    const hook = try exec.runHook(ctx.gpa, ctx.io, ctx.environ, hook_name);50    defer ctx.gpa.free(hook.output);51    switch (hook.result) {52        .not_found, .ok => return true,53        .failed => {54            output.hookFailed(hook_name, hook.exit_code, hook.output);55            return output.confirmDefaultNo("continue anyway?");56        },57    }58}5960fn runPostHook(ctx: Ctx, hook_name: []const u8) void {61    const hook = exec.runHook(ctx.gpa, ctx.io, ctx.environ, hook_name) catch return;62    defer ctx.gpa.free(hook.output);63    if (hook.result == .failed) {64        output.hookWarning(hook_name, hook.exit_code, hook.output);65    }66}6768pub fn apply(ctx: Ctx) !void {69    if (ctx.dry) {70        output.applyDry(ctx.machine.name);71        const code = try exec.nixosRebuildDryActivate(ctx.io, &ctx.machine, ctx.gpa);72        if (code != 0) return error.BuildFailed;73        output.applyDryDone();74        return;75    }76    if (ctx.check) {77        return check(ctx);78    }7980    if (!try runPreHook(ctx, "pre-apply")) {81        output.aborted();82        return error.HookAborted;83    }8485    output.applyStart(ctx.machine.name);86    output.buildPanelInit();87    const start = std.Io.Clock.awake.now(ctx.io);8889    var panel = output.BuildPanel{};90    const code = exec.nixosRebuildSwitchWithPanel(ctx.io, &ctx.machine, ctx.gpa, &panel) catch |e| {91        output.buildPanelClear();92        exec.markApplyFailed(ctx.io, ctx.environ);93        return e;94    };95    output.buildPanelClear();9697    if (code != 0) {98        exec.markApplyFailed(ctx.io, ctx.environ);99        return error.BuildFailed;100    }101102    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());103    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));104    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;105    const after_failure = exec.takeApplyFailed(ctx.io, ctx.environ);106    output.applyDone(gen, elapsed, after_failure);107    // Show any nix warnings collected during the build (dim yellow, after success line).108    const warnings = errors.extractWarnings(ctx.gpa, errors.getBuildStderr()) catch &.{};109    defer {110        for (warnings) |w| ctx.gpa.free(w);111        ctx.gpa.free(warnings);112    }113    if (warnings.len > 0) output.buildWarnings(warnings);114    runPostHook(ctx, "post-apply");115    logAction(ctx, "apply", gen);116}117118pub fn check(ctx: Ctx) !void {119    output.checkStart(ctx.machine.name);120    const code = try exec.nixosRebuildBuild(ctx.io, &ctx.machine, ctx.gpa);121    if (code != 0) return error.BuildFailed;122    output.checkOk();123}124125pub fn back(ctx: Ctx) !void {126    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);127    defer ctx.gpa.free(gens);128129    var current: u32 = 0;130    for (gens) |g| if (g.current) {131        current = g.number;132    };133134    // Newest generation older than current. If there is none, we're already at the135    // oldest — stop cleanly instead of letting rollback fail with 'build failed'.136    var prev: u32 = 0;137    var has_prev = false;138    for (gens) |g| {139        if (g.number < current and (!has_prev or g.number > prev)) {140            prev = g.number;141            has_prev = true;142        }143    }144    if (!has_prev) {145        output.alreadyOldest();146        return;147    }148149    if (!try runPreHook(ctx, "pre-back")) {150        output.aborted();151        return error.HookAborted;152    }153154    output.backStart(ctx.machine.name, current, prev);155    if (ctx.cfg.confirm and !output.confirm("")) return;156157    // Flake systems don't have <nixos-config> in the Nix search path, so158    // `nixos-rebuild --rollback` fails. Switch by generation number instead159    // (same path as `nina go N`), which works for both channel and flake.160    const code = if (flakeSystem(ctx))161        try exec.switchGeneration(ctx.io, &ctx.machine, ctx.gpa, prev)162    else163        try exec.rollback(ctx.io, &ctx.machine, ctx.gpa);164    if (code != 0) return error.BuildFailed;165    output.backDone(prev);166    runPostHook(ctx, "post-back");167}168169pub fn go(ctx: Ctx) !void {170    if (ctx.args.len == 0) return error.Internal;171    const target = std.fmt.parseInt(u32, ctx.args[0], 10) catch return error.Internal;172    const current = try exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine);173174    output.goStart(ctx.machine.name, current, target);175    if (ctx.cfg.confirm and !output.confirm("")) return;176177    const code = try exec.switchGeneration(ctx.io, &ctx.machine, ctx.gpa, target);178    if (code != 0) return error.ProcessFailed;179    output.generationDone(target);180}181182pub fn history(ctx: Ctx) !void {183    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);184    defer ctx.gpa.free(gens);185    output.historyHeader(ctx.machine.name);186    for (gens) |g| output.historyRow(g);187}188189const gen_help = [_][2][]const u8{190    .{ "list", "list generations" },191    .{ "current", "show current generation" },192    .{ "delete <n>", "delete generation n" },193    .{ "delete old", "delete old generations" },194};195196pub fn genCmd(ctx: Ctx) !void {197    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("gen", &gen_help, null);198    if (std.mem.eql(u8, ctx.sub, "list")) return history(ctx);199    if (std.mem.eql(u8, ctx.sub, "current")) {200        const n = try exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine);201        output.genCurrent(n);202        return;203    }204    if (std.mem.eql(u8, ctx.sub, "delete")) {205        if (ctx.args.len == 0) return error.Internal;206        if (std.mem.eql(u8, ctx.args[0], "old")) {207            if (ctx.cfg.confirm and !output.confirm("")) return;208            _ = try exec.deleteOldGenerations(ctx.io, &ctx.machine, ctx.gpa);209        } else {210            const n = std.fmt.parseInt(u32, ctx.args[0], 10) catch return error.Internal;211            if (ctx.cfg.confirm and !output.confirm("")) return;212            _ = try exec.deleteGeneration(ctx.io, &ctx.machine, ctx.gpa, n);213        }214        output.done();215        return;216    }217    return error.Internal;218}219220pub fn clean(ctx: Ctx) !void {221    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);222    defer ctx.gpa.free(gens);223    const all = ctx.all or std.mem.eql(u8, ctx.sub, "all");224    const total: u32 = @intCast(gens.len);225    // `clean all` keeps only the current generation; otherwise keep the configured226    // count. With nothing older than the keep limit, there's nothing to collect.227    const keep: u32 = if (all) 1 else ctx.cfg.generations;228    if (total <= keep) {229        output.cleanNothing(ctx.machine.name, total);230        return;231    }232    output.cleanStart(ctx.machine.name, keep, total);233    if (ctx.cfg.confirm and !output.confirm("removing — cannot be undone")) return;234    _ = try exec.collectGarbage(ctx.io, &ctx.machine, ctx.gpa, all, ctx.cfg.generations);235    output.cleanDone();236}237238pub fn statusCmd(ctx: Ctx) !void {239    output.statusHeader();240    // --all renders every configured machine; remotes route through the same SSH241    // path as exec.capture. An unreachable machine is shown in red, not fatal.242    if (ctx.all and ctx.cfg.machines.len > 0) {243        for (ctx.cfg.machines) |m| statusRowFor(ctx, &m);244    } else {245        statusRowFor(ctx, &ctx.machine);246    }247    homeStatusLine(ctx);248}249250// When standalone Home Manager is present, show its current generation as a dim251// line indented under the machine rows. Gated on standalone mode (the only mode252// where we can read a generation), so a machine without HM is unaffected.253fn homeStatusLine(ctx: Ctx) void {254    if (exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ) != .standalone) return;255    const out = exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine) catch return;256    defer ctx.gpa.free(out);257    const gens = parseHomeGenerations(ctx.gpa, out) catch return;258    defer freeHomeGens(ctx.gpa, gens);259    if (gens.len == 0) return;260    output.statusHomeRow(gens[0].number, gens[0].date);261}262263fn statusRowFor(ctx: Ctx, machine: *const types.Machine) void {264    // A failure to read the current generation means we couldn't reach or query265    // the machine — mark it unreachable rather than reporting a bogus gen 0.266    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, machine) catch {267        output.statusRow(machine.name, 0, "", "", false);268        return;269    };270    const st = exec.systemStatus(ctx.gpa, ctx.io, machine);271    defer ctx.gpa.free(st.size);272    defer ctx.gpa.free(st.age);273    output.statusRow(machine.name, gen, st.age, st.size, true);274}275276pub fn diff(ctx: Ctx) !void {277    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);278    defer ctx.gpa.free(gens);279    var current: u32 = 0;280    var prev: u32 = 0;281    for (gens) |g| {282        if (g.current) current = g.number;283        if (!g.current and g.number > prev and g.number < current) prev = g.number;284    }285    if (ctx.args.len >= 2) {286        const a = std.fmt.parseInt(u32, ctx.args[0], 10) catch current - 1;287        const b = std.fmt.parseInt(u32, ctx.args[1], 10) catch current;288        output.diffHeader(a, b, ctx.machine.name);289        if (try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, a, b) != 0) return error.ProcessFailed;290    } else {291        output.diffHeader(if (prev > 0) prev else current - 1, current, ctx.machine.name);292        if (try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, if (prev > 0) prev else current - 1, current) != 0) return error.ProcessFailed;293    }294}295296pub fn mood(ctx: Ctx) !void {297    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;298    const st = exec.systemStatus(ctx.gpa, ctx.io, &ctx.machine);299    defer ctx.gpa.free(st.size);300    defer ctx.gpa.free(st.age);301    const state = exec.systemRunningState(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");302    defer ctx.gpa.free(state);303    output.mood(ctx.machine.name, state, gen, st.age, st.size);304}305306pub fn doctor(ctx: Ctx) !void {307    output.doctorHeader(ctx.machine.name);308    const checks = try exec.runDoctorChecks(ctx.gpa, ctx.io, &ctx.machine);309    defer ctx.gpa.free(checks);310    var warnings: u32 = 0;311    var failures: u32 = 0;312    for (checks) |ch| {313        output.doctorRow(ch);314        if (ch.status == .warn) warnings += 1;315        if (ch.status == .fail) failures += 1;316    }317318    // Home Manager row only when present — absent on a machine without HM, so319    // doctor's table is unchanged there.320    const hm_mode = exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ);321    if (hm_mode != .none) {322        const note = homeDoctorNote(ctx, hm_mode);323        defer ctx.gpa.free(note);324        output.doctorRow(.{ .name = "home manager", .status = .ok, .note = note });325    }326327    output.doctorSummary(warnings, failures);328}329330// "standalone  gen 765" / "module" — the note shown in doctor's home manager row.331// Caller owns the returned slice.332fn homeDoctorNote(ctx: Ctx, mode: exec.HomeManagerMode) []const u8 {333    const label = switch (mode) {334        .standalone => "standalone",335        .module => "module",336        .none => "",337    };338    if (mode == .standalone) {339        const gen = homeCurrentGen(ctx);340        if (gen != 0)341            return std.fmt.allocPrint(ctx.gpa, "{s}  gen {d}", .{ label, gen }) catch342                (ctx.gpa.dupe(u8, label) catch "");343    }344    return ctx.gpa.dupe(u8, label) catch "";345}346347// nina update — kepr self-update for the nina binary itself.348pub fn update(ctx: Ctx) !void {349    output.updateSelfStart();350351    if (comptime std.mem.eql(u8, version.PLATFORM, "unsupported")) {352        output.updateSelfNoPlatform(@tagName(builtin.cpu.arch) ++ "-" ++ @tagName(builtin.os.tag));353        return error.Internal;354    }355356    const env_url = ctx.environ.get("NINA_UPDATE_SOURCE");357    const source_url = env_url orelse UPDATE_URL;358359    const body = exec.fetchUrl(ctx.gpa, ctx.io, source_url) catch |e| switch (e) {360        error.NetworkError, error.HttpError => {361            output.updateSelfNetworkError();362            return;363        },364        else => return e,365    };366    defer ctx.gpa.free(body);367368    const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, body, .{}) catch {369        output.printWarning("could not parse release metadata");370        return;371    };372    defer parsed.deinit();373374    const root = parsed.value;375    if (root != .object) {376        output.printWarning("malformed release metadata");377        return;378    }379380    const remote_ver = blk: {381        const v = root.object.get("version") orelse {382            output.printWarning("malformed release metadata");383            return;384        };385        break :blk switch (v) {386            .string => |s| s,387            else => {388                output.printWarning("malformed release metadata");389                return;390            },391        };392    };393    if (!remoteVersionNewer(version.VERSION, remote_ver)) {394        output.updateSelfCurrent(version.VERSION);395        return;396    }397398    const release_notes = try updateReleaseNotes(ctx.gpa, ctx.io, root, source_url, version.VERSION, remote_ver);399    defer ctx.gpa.free(release_notes);400401    output.updateSelfAvailable(version.VERSION, remote_ver);402    output.updateSelfReleaseNotes(release_notes);403    if (ctx.check) return;404405    var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;406    const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {407        errors.error_info.setMessage("could not determine install path", .{});408        return error.Internal;409    };410411    // When running from the nix store, defer to nix profile upgrade so nix412    // manages the transition (the store is read-only; binary replacement fails).413    // A NixOS system install also resolves into the store but isn't a profile414    // element, so check the profile to avoid a no-op `upgrade` — it updates with415    // the next nixos-rebuild instead.416    if (std.mem.startsWith(u8, install_path, "/nix/store/")) {417        const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);418        defer if (nina_element) |n| ctx.gpa.free(n);419        if (nina_element == null) {420            output.updateSelfSystemManaged();421            return;422        }423        const element = nina_element.?;424        output.updateSelfNixManaged(remote_ver);425        if (ctx.cfg.confirm and !output.confirm("")) return;426        // `nix profile upgrade` re-resolves the element's own originalUrl. The427        // archive install runs with --no-write-lock-file, so nix has nowhere to428        // persist the lock it takes at install time except baking it into that429        // originalUrl as a `?narHash=` pin — which then never changes no matter430        // how far kepr's HEAD moves. Upgrading against that pin is a permanent431        // no-op: exit 0, "upgrading from X to X", nothing installed. Remove and432        // re-add against the plain (unpinned) archive URL instead, so nix433        // actually re-resolves HEAD and picks up a fresh narHash.434        const remove_r = exec.capture(ctx.gpa, ctx.io, &ctx.machine, &.{ "nix", "profile", "remove", element }) catch {435            output.updateSelfNixFailed();436            return;437        };438        defer ctx.gpa.free(remove_r.stdout);439        defer ctx.gpa.free(remove_r.stderr);440        if (remove_r.exit_code != 0) {441            output.raw(remove_r.stdout);442            output.raw(remove_r.stderr);443            output.updateSelfNixFailed();444            return;445        }446        // Even against the plain unpinned URL, nix caches its resolution for447        // `tarball-ttl` seconds (default 3600) regardless of HTTP cache-control448        // headers — so within an hour of any prior nix operation touching this449        // URL, add would silently reuse the stale narHash and reinstall the450        // same old version. --refresh forces nix to actually re-check HEAD.451        const add_r = exec.capture(ctx.gpa, ctx.io, &ctx.machine, &.{ "nix", "profile", "add", "--no-write-lock-file", "--refresh", FLAKE_URL }) catch {452            output.updateSelfNixReinstallFailed();453            return;454        };455        defer ctx.gpa.free(add_r.stdout);456        defer ctx.gpa.free(add_r.stderr);457        if (add_r.exit_code != 0) {458            output.raw(add_r.stdout);459            output.raw(add_r.stderr);460            output.updateSelfNixReinstallFailed();461            return;462        }463        output.updateSelfDone(version.VERSION, remote_ver);464        output.updateSelfNixRehash();465        return;466    }467468    const plat_info = blk: {469        const pv = root.object.get("platforms") orelse break :blk null;470        if (pv != .object) break :blk null;471        break :blk pv.object.get(version.PLATFORM);472    };473    if (plat_info == null) {474        output.updateSelfNoPlatform(version.PLATFORM);475        return;476    }477478    const dl_url = blk: {479        const v = plat_info.?.object.get("url") orelse {480            output.printWarning("malformed release metadata");481            return;482        };483        break :blk switch (v) {484            .string => |s| s,485            else => {486                output.printWarning("malformed release metadata");487                return;488            },489        };490    };491492    const raw_cksum = blk: {493        if (plat_info.?.object.get("blake3")) |v|494            break :blk switch (v) {495                .string => |s| s,496                else => {497                    output.printWarning("malformed release metadata");498                    return;499                },500            };501        if (plat_info.?.object.get("checksum")) |v|502            break :blk switch (v) {503                .string => |s| s,504                else => {505                    output.printWarning("malformed release metadata");506                    return;507                },508            };509        output.printWarning("missing checksum in release metadata");510        return;511    };512    const expected_hex = if (std.mem.startsWith(u8, raw_cksum, "blake3:")) raw_cksum["blake3:".len..] else raw_cksum;513514    if (ctx.cfg.confirm and !output.confirm("")) return;515516    output.updateSelfDownloading(remote_ver, version.PLATFORM);517    const tmp_path = exec.downloadToTemp(ctx.gpa, ctx.io, dl_url) catch {518        output.printWarning("download failed — check your connection and try again");519        return;520    };521    defer ctx.gpa.free(tmp_path);522523    output.updateSelfVerifying();524    exec.verifyAndInstall(ctx.gpa, ctx.io, tmp_path, expected_hex, install_path) catch |e| switch (e) {525        error.ChecksumMismatch => {526            output.updateSelfChecksumFailed();527            return;528        },529        else => return e,530    };531532    output.updateSelfDone(version.VERSION, remote_ver);533}534535// archives.json covers every version between current and latest; the manifest's536// `notes` field only ever describes the single latest release. Try the full-range537// changelog first so an update spanning several versions doesn't collapse down to538// just the newest one's notes — fall back to `notes` only when the archive has539// nothing (e.g. releases predating archives.json, or the fetch failing).540fn updateReleaseNotes(gpa: std.mem.Allocator, io: std.Io, root: std.json.Value, source_url: []const u8, current: []const u8, latest: []const u8) ![]u8 {541    if (buildKeprArchiveReleaseNotes(gpa, io, source_url, current, latest) catch null) |notes| {542        if (std.mem.trim(u8, notes, " \t\r\n").len > 0) return notes;543        gpa.free(notes);544    }545    if (releaseNotesFromMetadata(gpa, root)) |notes| return notes;546    return gpa.dupe(u8, "");547}548549fn releaseNotesFromMetadata(gpa: std.mem.Allocator, root: std.json.Value) ?[]u8 {550    if (root != .object) return null;551    // `notes` is the one canonical manifest field. The retired `release_notes`552    // and `changelog` fallbacks are gone — Kepr now emits `notes` everywhere, and553    // releases that predate `--notes` fall back to archives.json in the caller.554    const v = root.object.get("notes") orelse return null;555    return switch (v) {556        .string => |s| gpa.dupe(u8, s) catch null,557        else => null,558    };559}560561fn buildKeprArchiveReleaseNotes(gpa: std.mem.Allocator, io: std.Io, source_url: []const u8, current: []const u8, latest: []const u8) ![]u8 {562    const archive_url = try keprArchiveUrl(gpa, source_url);563    defer gpa.free(archive_url);564565    const body = exec.fetchUrl(gpa, io, archive_url) catch return gpa.dupe(u8, "");566    defer gpa.free(body);567568    return releaseNotesFromArchiveJson(gpa, body, current, latest);569}570571fn keprArchiveUrl(gpa: std.mem.Allocator, source_url: []const u8) ![]u8 {572    const scheme = std.mem.indexOf(u8, source_url, "://") orelse return error.InvalidUpdateSource;573    const path_start = std.mem.indexOfScalarPos(u8, source_url, scheme + 3, '/') orelse return error.InvalidUpdateSource;574    const origin = source_url[0..path_start];575    const path = source_url[path_start..];576    if (!std.mem.startsWith(u8, path, "/api/")) return error.InvalidUpdateSource;577578    const after_api = path["/api/".len..];579    const repo_end = std.mem.indexOfScalar(u8, after_api, '/') orelse return error.InvalidUpdateSource;580    const repo = after_api[0..repo_end];581    if (repo.len == 0) return error.InvalidUpdateSource;582583    return std.fmt.allocPrint(gpa, "{s}/{s}/archives.json?limit=100", .{ origin, repo });584}585586// Saves arrive newest-first. For each version in the update range we want the OLDEST587// save message (the one that introduced that version), not a follow-up cleanup/docs save.588// We overwrite the tracked message on each occurrence, so the final stored value per589// version is always the oldest (last-seen in a newest-first stream).590fn releaseNotesFromArchiveJson(gpa: std.mem.Allocator, body: []const u8, current: []const u8, latest: []const u8) ![]u8 {591    const parsed = std.json.parseFromSlice(std.json.Value, gpa, body, .{}) catch return gpa.dupe(u8, "");592    defer parsed.deinit();593594    if (parsed.value != .object) return gpa.dupe(u8, "");595    const saves_v = parsed.value.object.get("saves") orelse return gpa.dupe(u8, "");596    if (saves_v != .array) return gpa.dupe(u8, "");597598    // version string → oldest message seen (both slice into parsed JSON, valid until deinit)599    var best_msg = std.StringHashMap([]const u8).init(gpa);600    defer best_msg.deinit();601    var order: std.ArrayList([]const u8) = .empty;602    defer order.deinit(gpa);603604    for (saves_v.array.items) |save| {605        if (save != .object) continue;606        const ver_v = save.object.get("version") orelse continue;607        const msg_v = save.object.get("message") orelse continue;608        if (ver_v != .string or msg_v != .string) continue;609        const ver = ver_v.string;610        const msg = std.mem.trim(u8, msg_v.string, " \t\r\n");611        if (msg.len == 0 or !versionInUpdateRange(ver, current, latest)) continue;612613        const entry = try best_msg.getOrPut(ver);614        if (!entry.found_existing) try order.append(gpa, ver);615        // Always overwrite: saves are newest-first, so last write = oldest save = version-intro message616        entry.value_ptr.* = msg;617    }618619    if (order.items.len == 0) return gpa.dupe(u8, "");620621    var out: std.ArrayList(u8) = .empty;622    errdefer out.deinit(gpa);623    for (order.items) |ver| {624        const msg = best_msg.get(ver).?;625        // Use only the first line as the summary; multi-line saves may have implementation details below626        const summary_end = std.mem.indexOf(u8, msg, "\n") orelse msg.len;627        const summary = std.mem.trim(u8, msg[0..summary_end], " \t\r");628        if (summary.len == 0) continue;629        try appendLine(&out, gpa, "## {s}\n", .{ver});630        try appendLine(&out, gpa, "- {s}\n\n", .{summary});631    }632633    if (out.items.len == 0) {634        out.deinit(gpa);635        return gpa.dupe(u8, "");636    }637    return out.toOwnedSlice(gpa);638}639640fn appendLine(out: *std.ArrayList(u8), gpa: std.mem.Allocator, comptime template: []const u8, args: anytype) !void {641    const line = try std.fmt.allocPrint(gpa, template, args);642    defer gpa.free(line);643    try out.appendSlice(gpa, line);644}645646fn versionInUpdateRange(candidate: []const u8, current: []const u8, latest: []const u8) bool {647    const cand = parseSemver(candidate) orelse return std.mem.eql(u8, candidate, latest);648    const cur = parseSemver(current) orelse return std.mem.eql(u8, candidate, latest);649    const lat = parseSemver(latest) orelse return std.mem.eql(u8, candidate, latest);650    return compareSemver(cand, cur) == .gt and compareSemver(cand, lat) != .gt;651}652653fn remoteVersionNewer(current: []const u8, remote: []const u8) bool {654    const cur = parseSemver(current) orelse return !std.mem.eql(u8, current, remote);655    const rem = parseSemver(remote) orelse return !std.mem.eql(u8, current, remote);656    return compareSemver(rem, cur) == .gt;657}658659const VersionOrder = enum { lt, eq, gt };660661fn compareSemver(a: Semver, b: Semver) VersionOrder {662    if (a.major != b.major) return if (a.major < b.major) .lt else .gt;663    if (a.minor != b.minor) return if (a.minor < b.minor) .lt else .gt;664    if (a.patch != b.patch) return if (a.patch < b.patch) .lt else .gt;665    return .eq;666}667668fn parseSemver(raw: []const u8) ?Semver {669    const v = if (std.mem.startsWith(u8, raw, "v")) raw[1..] else raw;670    var it = std.mem.splitScalar(u8, v, '.');671    const major_s = it.next() orelse return null;672    const minor_s = it.next() orelse return null;673    const patch_s = it.next() orelse return null;674    if (it.next() != null) return null;675    return .{676        .major = std.fmt.parseInt(u32, major_s, 10) catch return null,677        .minor = std.fmt.parseInt(u32, minor_s, 10) catch return null,678        .patch = std.fmt.parseInt(u32, patch_s, 10) catch return null,679    };680}681682test "versionInUpdateRange includes only newer versions through latest" {683    try std.testing.expect(versionInUpdateRange("3.2.3", "3.1.9", "3.2.3"));684    try std.testing.expect(versionInUpdateRange("3.2.0", "3.1.9", "3.2.3"));685    try std.testing.expect(!versionInUpdateRange("3.1.9", "3.1.9", "3.2.3"));686    try std.testing.expect(!versionInUpdateRange("3.2.4", "3.1.9", "3.2.3"));687}688689test "remoteVersionNewer does not offer downgrades" {690    try std.testing.expect(remoteVersionNewer("3.2.3", "3.2.4"));691    try std.testing.expect(!remoteVersionNewer("3.2.4", "3.2.3"));692    try std.testing.expect(!remoteVersionNewer("3.2.4", "3.2.4"));693}694695test "releaseNotesFromArchiveJson uses oldest save per version" {696    // Saves arrive newest-first. For 3.2.3, the newest save is a CONTINUITY update;697    // the oldest is the version-intro message. We expect the intro message in the output.698    const body =699        \\{700        \\  "saves": [701        \\    {"version":"3.2.3","message":"wip: record verification in CONTINUITY"},702        \\    {"version":"3.2.1","message":"old release"},703        \\    {"version":"3.2.3","message":"add streaming deflate path"}704        \\  ]705        \\}706    ;707    const notes = try releaseNotesFromArchiveJson(std.testing.allocator, body, "3.2.1", "3.2.3");708    defer std.testing.allocator.free(notes);709710    try std.testing.expect(std.mem.indexOf(u8, notes, "## 3.2.3") != null);711    try std.testing.expect(std.mem.indexOf(u8, notes, "- add streaming deflate path") != null);712    try std.testing.expect(std.mem.indexOf(u8, notes, "CONTINUITY") == null);713    try std.testing.expect(std.mem.indexOf(u8, notes, "old release") == null);714}715716test "releaseNotesFromMetadata reads canonical notes and ignores retired keys" {717    const a = std.testing.allocator;718719    // Canonical field is read.720    {721        var parsed = try std.json.parseFromSlice(std.json.Value, a, "{\"notes\":\"colored progress bar\"}", .{});722        defer parsed.deinit();723        const got = releaseNotesFromMetadata(a, parsed.value).?;724        defer a.free(got);725        try std.testing.expectEqualStrings("colored progress bar", got);726    }727728    // Retired field names are no longer honoured — they fall through to null so729    // the caller drops to the archives.json derivation instead.730    {731        var parsed = try std.json.parseFromSlice(std.json.Value, a, "{\"release_notes\":\"x\",\"changelog\":\"y\"}", .{});732        defer parsed.deinit();733        try std.testing.expect(releaseNotesFromMetadata(a, parsed.value) == null);734    }735}736737// nina goodbye — clean uninstall. Three install paths:738// - nix profile (binary in nix store with a profile element) → nix profile remove739// - koh build or source build (plain binary on PATH) → delete the file740pub fn goodbye(ctx: Ctx) !void {741    output.goodbyeStart();742743    var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;744    const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {745        errors.error_info.setMessage("could not determine install path", .{});746        return error.Internal;747    };748749    // A binary outside the nix store is a koh build or source build — delete it.750    if (!std.mem.startsWith(u8, install_path, "/nix/store/")) {751        output.goodbyeFile(install_path);752        if (ctx.cfg.confirm and !output.confirm("")) return;753        std.Io.Dir.deleteFileAbsolute(ctx.io, install_path) catch |e| {754            errors.error_info.setMessage("could not remove {s}", .{install_path});755            return e;756        };757        output.goodbyeDone();758        return;759    }760761    // Binary is in the nix store — find and remove the profile element.762    const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);763    defer {764        if (nina_element) |n| ctx.gpa.free(n);765    }766767    if (nina_element == null) {768        errors.error_info.setMessage("nina not found in nix profile — was it installed via 'nix profile add'?", .{});769        return error.Internal;770    }771772    output.goodbyeNix();773    if (ctx.cfg.confirm and !output.confirm("")) return;774    const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "remove", nina_element.? }) catch {775        output.goodbyeFailed("nix profile remove failed");776        return;777    };778    if (ec != 0) {779        output.goodbyeFailed("nix profile remove failed");780        return;781    }782    output.goodbyeDone();783}784785fn channelUpdateCmd(ctx: Ctx) !void {786    output.updateStart(ctx.machine.name);787    _ = try exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa);788    output.updateDone();789}790791pub fn upgrade(ctx: Ctx) !void {792    if (!try runPreHook(ctx, "pre-upgrade")) {793        output.aborted();794        return error.HookAborted;795    }796797    output.upgradeStart(ctx.machine.name);798    // Flake systems update inputs (flake.lock); channel systems update channels.799    // Running nix-channel --update on a flake system is a no-op at best. The800    // rebuild below is already flake-aware via exec.nixosRebuildSwitch.801    if (flakeSystem(ctx)) {802        output.printSubstep("updating flake inputs", .{});803        _ = exec.flakeUpdateAt(ctx.io, &ctx.machine, ctx.gpa, ctx.machine.config_path) catch {};804    } else {805        output.printSubstep("updating channels", .{});806        _ = exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa) catch {};807    }808    output.printSubstep("rebuilding", .{});809    output.buildPanelInit();810    const start = std.Io.Clock.awake.now(ctx.io);811    var panel = output.BuildPanel{};812    const code = exec.nixosRebuildSwitchWithPanel(ctx.io, &ctx.machine, ctx.gpa, &panel) catch |e| {813        output.buildPanelClear();814        return e;815    };816    output.buildPanelClear();817    if (code != 0) {818        output.applyFailed("");819        return error.BuildFailed;820    }821    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());822    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));823    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;824    output.applyDone(gen, elapsed, false);825    runPostHook(ctx, "post-upgrade");826}827828pub fn log(ctx: Ctx) !void {829    output.logHeader(ctx.machine.name);830    const content = exec.readNinaLog(ctx.gpa, ctx.io, ctx.environ, ctx.last) catch {831        // No log yet — that's fine832        return;833    };834    defer ctx.gpa.free(content);835    var lines = std.mem.splitScalar(u8, content, '\n');836    while (lines.next()) |line| {837        const t = std.mem.trim(u8, line, " \t\r");838        if (t.len == 0) continue;839        if (t[0] == '{') {840            renderJsonLogLine(ctx.gpa, t);841        } else {842            // legacy tab-separated format843            var parts = std.mem.tokenizeScalar(u8, t, '\t');844            const date = parts.next() orelse continue;845            const time = parts.next() orelse "";846            const action = parts.next() orelse "";847            const detail = parts.next() orelse "";848            output.logRow(date, time, action, detail);849        }850    }851}852853// The on-disk log is JSON Lines: {"ts","machine","command","outcome","gen_after",...}.854// Render ts -> date/time columns, command -> action, outcome(+gen) -> detail.855fn renderJsonLogLine(gpa: std.mem.Allocator, line: []const u8) void {856    const parsed = std.json.parseFromSlice(std.json.Value, gpa, line, .{}) catch {857        output.logRow(line, "", "", ""); // unparseable — show raw rather than drop858        return;859    };860    defer parsed.deinit();861    if (parsed.value != .object) return;862    const o = parsed.value.object;863864    const ts = jsonStr(o, "ts");865    const date = if (ts.len >= 10) ts[0..10] else ts;866    const time = if (ts.len >= 16) ts[11..16] else "";867    const action = jsonStr(o, "command");868    const outcome = jsonStr(o, "outcome");869870    var buf: [160]u8 = undefined;871    var detail: []const u8 = outcome;872    if (o.get("gen_after")) |g| {873        if (g == .integer) {874            detail = std.fmt.bufPrint(&buf, "{s}   -> gen {d}", .{ outcome, g.integer }) catch outcome;875        }876    }877    output.logRow(date, time, action, detail);878}879880fn jsonStr(o: std.json.ObjectMap, key: []const u8) []const u8 {881    if (o.get(key)) |v| {882        if (v == .string) return v.string;883    }884    return "";885}886887pub fn edit(ctx: Ctx) !void {888    // `edit` is multi-word, so a bare positional ("hardware") arrives as ctx.sub.889    // hardware-configuration.nix is generated by nixos-generate-config and warns890    // against hand-editing — refuse rather than silently opening the wrong file.891    if (std.mem.eql(u8, ctx.sub, "hardware")) {892        output.editHardwareWarning();893        return;894    }895896    // --dir opens the whole config directory (for editors that work better with897    // a folder open), as root so root-owned config trees like /etc/nixos work.898    var open_dir = false;899    for (ctx.args) |arg| {900        if (std.mem.eql(u8, arg, "--dir")) open_dir = true;901    }902    if (open_dir) {903        output.editOpen(ctx.machine.config_path, ctx.cfg.editor);904        _ = try exec.openEditorSudo(ctx.io, ctx.gpa, ctx.cfg.editor, ctx.machine.config_path);905        return;906    }907908    const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});909    defer ctx.gpa.free(path);910    output.editOpen(path, ctx.cfg.editor);911    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);912}913914pub fn fmt(ctx: Ctx) !void {915    const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});916    defer ctx.gpa.free(path);917    if (ctx.check) {918        const code = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, true);919        if (code != 0) output.fmtNeedsFormat() else output.fmtDone();920        return;921    }922    output.fmtStart(path);923    _ = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, false);924    output.fmtDone();925}926927pub fn repl(ctx: Ctx) !void {928    output.replStart();929    _ = try exec.nixRepl(ctx.io, &ctx.machine, ctx.gpa);930}931932pub fn develop(ctx: Ctx) !void {933    if (std.mem.eql(u8, ctx.sub, "show")) {934        _ = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, null);935        return;936    }937    const run_cmd: ?[]const u8 = if (ctx.args.len > 0 and std.mem.eql(u8, ctx.sub, "run"))938        ctx.args[0]939    else940        null;941    output.developStart(&.{});942    _ = try exec.nixDevelopPs1(ctx.io, &ctx.machine, ctx.gpa, run_cmd, ctx.environ);943    output.developDone();944}945946pub fn info(ctx: Ctx) !void {947    output.infoHeader(ctx.machine.name);948    const nixos_ver = exec.systemInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");949    defer ctx.gpa.free(nixos_ver);950    output.infoRow("nixos", std.mem.trim(u8, nixos_ver, " \t\n\r"));951952    const kernel = exec.kernelInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");953    defer ctx.gpa.free(kernel);954    output.infoRow("kernel", std.mem.trim(u8, kernel, " \t\n\r"));955956    const uptime = exec.uptimeInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");957    defer ctx.gpa.free(uptime);958    output.infoRow("uptime", std.mem.trim(u8, uptime, " \t\n\r"));959}960961pub fn boot(ctx: Ctx) !void {962    output.bootHeader(ctx.machine.name);963    const entries = exec.bootEntries(ctx.gpa, ctx.io, &ctx.machine) catch &.{};964    defer ctx.gpa.free(entries);965    for (entries, 0..) |entry, i| output.bootEntry(entry, i);966}967968pub fn searchCmd(ctx: Ctx) !void {969    const query = if (ctx.args.len > 0) ctx.args[0] else "";970    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);971    const selected = try search_tui.run(ctx.gpa, ctx.io, query, .packages, ctx.environ);972    if (selected) |npkg| try selectAndInstall(ctx, npkg);973}974975pub fn optionCmd(ctx: Ctx) !void {976    const query = if (ctx.args.len > 0) ctx.args[0] else "";977    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);978    _ = try search_tui.run(ctx.gpa, ctx.io, query, .options, ctx.environ);979}980981pub fn install(ctx: Ctx) !void {982    const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;983984    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);985986    // Search for the package to get the attr987    const pkgs = api.searchPackages(ctx.gpa, ctx.io, ctx.environ, pkg_name) catch {988        errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});989        errors.error_info.setSuggestion("nina search {s}", .{pkg_name});990        return error.PackageNotFound;991    };992993    if (pkgs.len == 0) {994        // No matches — likely a typo. Suggest the closest real package and offer it.995        if (closestPackage(ctx, pkg_name)) |sugg| {996            output.didYouMean(pkg_name, sugg.pname);997            if (output.confirm("")) try selectAndInstall(ctx, sugg);998            return;999        }1000        errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});1001        errors.error_info.setSuggestion("nina search {s}", .{pkg_name});1002        return error.PackageNotFound;1003    }10041005    // Prefer an exact name match over the first search result — `install ripgrep`1006    // must pick "ripgrep", not the alphabetically-first match like "repgrep".1007    var found = pkgs[0];1008    for (pkgs) |p| {1009        if (std.mem.eql(u8, p.pname, pkg_name)) {1010            found = p;1011            break;1012        }1013    }1014    try selectAndInstall(ctx, found);1015}10161017// Find the real package whose name is closest to a not-found query (typo help).1018// Typos usually keep the leading characters, so gather candidates with a prefix1019// search and rank by edit distance; return the best only if it's typo-close.1020fn closestPackage(ctx: Ctx, query: []const u8) ?types.NixPackage {1021    if (query.len < 2) return null;1022    var candidates = api.searchPackages(ctx.gpa, ctx.io, ctx.environ, query[0..@min(query.len, 4)]) catch &.{};1023    if (candidates.len == 0 and query.len > 2) {1024        candidates = api.searchPackages(ctx.gpa, ctx.io, ctx.environ, query[0..2]) catch &.{};1025    }1026    if (candidates.len == 0) return null;10271028    var best: ?types.NixPackage = null;1029    var best_dist: usize = std.math.maxInt(usize);1030    for (candidates) |p| {1031        const d = editDistance(query, p.pname);1032        if (d > 0 and d < best_dist) {1033            best_dist = d;1034            best = p;1035        }1036    }1037    // Only suggest a genuinely close name, scaled to query length.1038    const threshold = @max(@as(usize, 2), query.len / 3);1039    return if (best_dist <= threshold) best else null;1040}10411042// Case-insensitive Levenshtein distance. Names longer than the row buffer are1043// treated as far away (never suggested).1044fn editDistance(a: []const u8, b: []const u8) usize {1045    const n = b.len;1046    if (a.len == 0) return n;1047    if (n == 0) return a.len;1048    if (n + 1 > 128) return std.math.maxInt(usize);1049    var prev: [128]usize = undefined;1050    var curr: [128]usize = undefined;1051    var j: usize = 0;1052    while (j <= n) : (j += 1) prev[j] = j;1053    var i: usize = 1;1054    while (i <= a.len) : (i += 1) {1055        curr[0] = i;1056        j = 1;1057        while (j <= n) : (j += 1) {1058            const cost: usize = if (std.ascii.toLower(a[i - 1]) == std.ascii.toLower(b[j - 1])) 0 else 1;1059            curr[j] = @min(prev[j] + 1, @min(curr[j - 1] + 1, prev[j - 1] + cost));1060        }1061        @memcpy(prev[0 .. n + 1], curr[0 .. n + 1]);1062    }1063    return prev[n];1064}10651066test "editDistance is case-insensitive Levenshtein" {1067    try std.testing.expectEqual(@as(usize, 1), editDistance("firefux", "firefox"));1068    try std.testing.expectEqual(@as(usize, 0), editDistance("git", "GIT"));1069    try std.testing.expectEqual(@as(usize, 2), editDistance("fierfox", "firefox"));1070    try std.testing.expectEqual(@as(usize, 7), editDistance("", "firefox"));1071}10721073// Prompt for the install method (profile / system / try) and dispatch. Shared by1074// `nina install <pkg>` and the search widget's Enter-to-select — the letter keys1075// are read here, after the search widget's raw mode is gone, so they don't1076// collide with typing a query.1077fn selectAndInstall(ctx: Ctx, npkg: types.NixPackage) !void {1078    output.installSelectPrompt(npkg.pname, npkg.version);10791080    var choice_buf: [8]u8 = undefined;1081    var choice_len: usize = 0;1082    while (choice_len < choice_buf.len) {1083        const n = std.posix.read(std.posix.STDIN_FILENO, choice_buf[choice_len .. choice_len + 1]) catch break;1084        if (n == 0) break;1085        if (choice_buf[choice_len] == '\n') break;1086        choice_len += 1;1087    }1088    const choice = std.mem.trim(u8, choice_buf[0..choice_len], " \t");10891090    if (choice.len == 0 or choice[0] == 'i' or choice[0] == 'I') {1091        try profileInstallPkg(ctx, npkg);1092    } else if (choice[0] == 's' or choice[0] == 'S') {1093        try systemInstallPkg(ctx, npkg);1094    } else if (choice[0] == 't' or choice[0] == 'T') {1095        try tryPkg(ctx, npkg);1096    }1097}10981099fn profileInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {1100    output.installStart(npkg.pname, .profile);1101    if (npkg.unfree) {1102        output.printSubstep("NIXPKGS_ALLOW_UNFREE=1 nix profile add --impure nixpkgs#{s}", .{npkg.attr});1103        output.printTeach(try std.fmt.allocPrint(ctx.gpa, "NIXPKGS_ALLOW_UNFREE=1 nix profile add --impure nixpkgs#{s}", .{npkg.attr}));1104    } else {1105        output.printSubstep("nix profile add nixpkgs#{s}", .{npkg.attr});1106        output.printTeach(try std.fmt.allocPrint(ctx.gpa, "nix profile add nixpkgs#{s}", .{npkg.attr}));1107    }1108    const code = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, ctx.environ, npkg.attr, npkg.unfree);1109    if (code != 0) return error.ProcessFailed;1110    output.installDone(npkg.pname);1111}11121113fn systemInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {1114    const config_path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});1115    defer ctx.gpa.free(config_path);1116    const line = api.findSystemPackagesLine(ctx.io, config_path) orelse 1;1117    output.installEditorPrompt(npkg.pname, config_path, line, ctx.cfg.editor);1118    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, config_path, line);1119    if (ctx.cfg.confirm) {1120        if (output.confirm("apply now? ")) {1121            try apply(ctx);1122        }1123    }1124}11251126fn tryPkg(ctx: Ctx, npkg: types.NixPackage) !void {1127    output.tryStart(npkg.pname);1128    output.printSubstep("nix shell nixpkgs#{s}", .{npkg.attr});1129    output.tryExitHint();1130    _ = try exec.nixShellPs1(ctx.io, &ctx.machine, ctx.gpa, npkg.attr, ctx.environ);1131    output.tryDone();1132}11331134pub fn remove(ctx: Ctx) !void {1135    const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1136    output.removeStart(pkg_name);1137    const code = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, pkg_name);1138    if (code != 0) return error.ProcessFailed;1139    output.done();1140}11411142pub fn list(ctx: Ctx) !void {1143    output.listHeader(ctx.machine.name);11441145    // Profile packages: parse `nix profile list --json` into clean name+version1146    // rows instead of dumping nix's verbose multi-line "Name:/Flake attribute:"1147    // blocks.1148    if (exec.profileListJson(ctx.gpa, ctx.io, &ctx.machine) catch null) |json| {1149        defer ctx.gpa.free(json);1150        output.listSection("profile");1151        renderProfileJson(ctx.gpa, json);1152    }11531154    // System packages: the references of /run/current-system/sw, each a1155    // <hash>-<name>-<version> store path.1156    if (exec.systemPackagePaths(ctx.gpa, ctx.io, &ctx.machine) catch null) |paths| {1157        defer ctx.gpa.free(paths);1158        output.blankLine();1159        output.listSection("system");1160        var lines = std.mem.splitScalar(u8, paths, '\n');1161        while (lines.next()) |line| {1162            const t = std.mem.trim(u8, line, " \t\r");1163            if (t.len == 0) continue;1164            const row = pkgFromStorePath(t);1165            // Skip support paths with no parseable version (man pages, wrappers).1166            if (row.version.len == 0) continue;1167            output.listPkg(row.name, row.version);1168        }1169    }1170}11711172const PkgRow = struct { name: []const u8, version: []const u8 };11731174// Split a nix store path basename (<hash>-<name>-<version>) into name + version.1175// Version begins at the first '-' followed by a digit, which reliably lands on1176// the name/version boundary since the 32-char hash and package names start with1177// non-digits.1178fn pkgFromStorePath(path: []const u8) PkgRow {1179    const base = std.fs.path.basename(path);1180    const after_hash = if (base.len > 33 and base[32] == '-') base[33..] else base;1181    var i: usize = 0;1182    while (i + 1 < after_hash.len) : (i += 1) {1183        if (after_hash[i] == '-' and std.ascii.isDigit(after_hash[i + 1])) {1184            return .{ .name = after_hash[0..i], .version = stripOutputSuffix(after_hash[i + 1 ..]) };1185        }1186    }1187    return .{ .name = after_hash, .version = "" };1188}11891190// Multi-output derivations append the output name to the store path (e.g.1191// curl-8.20.0-bin, less-692-man). Strip that suffix so the version column reads1192// as just the version.1193fn stripOutputSuffix(ver: []const u8) []const u8 {1194    const suffixes = [_][]const u8{ "-bin", "-man", "-dev", "-doc", "-lib", "-info", "-out", "-static", "-devdoc" };1195    for (suffixes) |s| {1196        if (std.mem.endsWith(u8, ver, s)) return ver[0 .. ver.len - s.len];1197    }1198    return ver;1199}12001201test "pkgFromStorePath splits name and version at first dash-digit" {1202    const a = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-ripgrep-15.1.0");1203    try std.testing.expectEqualStrings("ripgrep", a.name);1204    try std.testing.expectEqualStrings("15.1.0", a.version);12051206    const b = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-helix-25.01");1207    try std.testing.expectEqualStrings("helix", b.name);1208    try std.testing.expectEqualStrings("25.01", b.version);12091210    // multi-output store paths drop their output-name suffix1211    const c = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-curl-8.20.0-bin");1212    try std.testing.expectEqualStrings("curl", c.name);1213    try std.testing.expectEqualStrings("8.20.0", c.version);1214}12151216fn firstStorePath(el: std.json.Value) ?[]const u8 {1217    if (el != .object) return null;1218    const sp = el.object.get("storePaths") orelse return null;1219    if (sp != .array or sp.array.items.len == 0) return null;1220    const first = sp.array.items[0];1221    return if (first == .string) first.string else null;1222}12231224// `nix profile list --json` has two shapes across nix versions: newer keys each1225// element by name (object), older lists them positionally (array). Handle both.1226fn renderProfileJson(gpa: std.mem.Allocator, json: []const u8) void {1227    const parsed = std.json.parseFromSlice(std.json.Value, gpa, json, .{}) catch return;1228    defer parsed.deinit();1229    if (parsed.value != .object) return;1230    const elements = parsed.value.object.get("elements") orelse return;1231    switch (elements) {1232        .object => |obj| {1233            var it = obj.iterator();1234            while (it.next()) |entry| {1235                const ver = if (firstStorePath(entry.value_ptr.*)) |p| pkgFromStorePath(p).version else "";1236                output.listPkg(entry.key_ptr.*, ver);1237            }1238        },1239        .array => |arr| {1240            for (arr.items) |el| {1241                const path = firstStorePath(el) orelse continue;1242                const row = pkgFromStorePath(path);1243                output.listPkg(row.name, row.version);1244            }1245        },1246        else => {},1247    }1248}12491250pub fn tryCmd(ctx: Ctx) !void {1251    const pkg_name_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1252    const shell_pkg = types.NixPackage{ .attr = pkg_name_arg, .pname = pkg_name_arg, .version = "", .description = "" };1253    try tryPkg(ctx, shell_pkg);1254}12551256// --- Home Manager commands ---12571258const home_help = [_][2][]const u8{1259    .{ "init", "set up home manager for the first time" },1260    .{ "init --switch", "set up and activate immediately" },1261    .{ "apply", "apply home-manager configuration" },1262    .{ "apply --dry", "preview changes without activating" },1263    .{ "back", "roll back one generation" },1264    .{ "history", "list all generations" },1265    .{ "edit", "open home.nix" },1266    .{ "check", "validate without applying" },1267    .{ "diff", "compare the latest two generations" },1268    .{ "packages", "list managed packages" },1269};12701271const HomeGen = struct {1272    number: u32,1273    date: []const u8,1274    time: []const u8,1275    path: []const u8,1276};12771278// `home-manager generations` lines read:1279//   2026-06-01 11:56 : id 765 -> /nix/store/<hash>-home-manager-generation1280// Newest first, so index 0 is the current generation.1281fn parseHomeGenerations(gpa: std.mem.Allocator, out_str: []const u8) ![]HomeGen {1282    var gens: std.ArrayList(HomeGen) = .empty;1283    var lines = std.mem.splitScalar(u8, out_str, '\n');1284    while (lines.next()) |line| {1285        const t = std.mem.trim(u8, line, " \t\r");1286        if (t.len == 0) continue;1287        var it = std.mem.tokenizeAny(u8, t, " \t");1288        const date = it.next() orelse continue;1289        const time = it.next() orelse continue;1290        var number: ?u32 = null;1291        var path: []const u8 = "";1292        while (it.next()) |tok| {1293            if (std.mem.eql(u8, tok, "id")) {1294                if (it.next()) |n| number = std.fmt.parseInt(u32, n, 10) catch null;1295            } else if (std.mem.startsWith(u8, tok, "/nix/store/")) {1296                path = tok;1297            }1298        }1299        const num = number orelse continue;1300        try gens.append(gpa, .{1301            .number = num,1302            .date = try gpa.dupe(u8, date),1303            .time = try gpa.dupe(u8, time),1304            .path = try gpa.dupe(u8, path),1305        });1306    }1307    return gens.toOwnedSlice(gpa);1308}13091310fn freeHomeGens(gpa: std.mem.Allocator, gens: []HomeGen) void {1311    for (gens) |g| {1312        gpa.free(g.date);1313        gpa.free(g.time);1314        gpa.free(g.path);1315    }1316    gpa.free(gens);1317}13181319test "parseHomeGenerations reads id, date and store path" {1320    const a = std.testing.allocator;1321    const sample =1322        \\2026-06-01 11:56 : id 765 -> /nix/store/aaaa-home-manager-generation1323        \\2026-05-31 10:29 : id 764 -> /nix/store/bbbb-home-manager-generation1324    ;1325    const gens = try parseHomeGenerations(a, sample);1326    defer freeHomeGens(a, gens);1327    try std.testing.expectEqual(@as(usize, 2), gens.len);1328    try std.testing.expectEqual(@as(u32, 765), gens[0].number);1329    try std.testing.expectEqualStrings("2026-06-01", gens[0].date);1330    try std.testing.expectEqualStrings("11:56", gens[0].time);1331    try std.testing.expectEqualStrings("/nix/store/aaaa-home-manager-generation", gens[0].path);1332    try std.testing.expectEqual(@as(u32, 764), gens[1].number);1333}13341335// Current (newest) home generation number, or 0 if unavailable.1336fn homeCurrentGen(ctx: Ctx) u32 {1337    const out = exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine) catch return 0;1338    defer ctx.gpa.free(out);1339    const gens = parseHomeGenerations(ctx.gpa, out) catch return 0;1340    defer freeHomeGens(ctx.gpa, gens);1341    return if (gens.len > 0) gens[0].number else 0;1342}13431344pub fn home(ctx: Ctx) !void {1345    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help"))1346        return output.subcommandHelp("home", &home_help, null);13471348    // Home Manager manages the local user's environment. Detection (which binary,1349    // ~/.config/home-manager, $HOME/$USER for the flake ref) all read the LOCAL1350    // host, while exec routes over SSH for a remote machine — so `home --on1351    // <remote>` would decide mode/flake-ref from the wrong box. Refuse it cleanly1352    // rather than acting on a mismatch.1353    if (!ctx.machine.local) {1354        output.homeLocalOnly(ctx.machine.name);1355        return;1356    }13571358    // init runs before mode detection: its whole purpose is bootstrapping a host1359    // that has no home-manager yet, so a .none mode must not short-circuit it.1360    if (std.mem.eql(u8, ctx.sub, "init")) return homeInitCmd(ctx);13611362    const mode = exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ);1363    if (mode == .none) {1364        output.homeNotInstalled();1365        return;1366    }13671368    // apply is the only command meaningful in module mode (it redirects to1369    // `nina apply`); everything else needs the standalone home-manager CLI.1370    if (std.mem.eql(u8, ctx.sub, "apply")) return homeApply(ctx, mode);1371    // edit just opens the local home.nix — fine in module mode too.1372    if (std.mem.eql(u8, ctx.sub, "edit")) return homeEdit(ctx);13731374    if (mode == .module) {1375        output.homeModuleManaged();1376        return;1377    }13781379    if (std.mem.eql(u8, ctx.sub, "back")) return homeBack(ctx);1380    if (std.mem.eql(u8, ctx.sub, "history")) return homeHistory(ctx);1381    if (std.mem.eql(u8, ctx.sub, "check")) return homeCheck(ctx);1382    if (std.mem.eql(u8, ctx.sub, "diff")) return homeDiff(ctx);1383    if (std.mem.eql(u8, ctx.sub, "packages")) return homePackages(ctx);13841385    return output.subcommandHelp("home", &home_help, null);1386}13871388fn homePackages(ctx: Ctx) !void {1389    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1390    defer ctx.gpa.free(out);1391    const gens = try parseHomeGenerations(ctx.gpa, out);1392    defer freeHomeGens(ctx.gpa, gens);13931394    output.homePackagesHeader(ctx.machine.name);1395    if (gens.len == 0 or gens[0].path.len == 0) return;13961397    // The generation's OWN references are home-manager's activation deps1398    // (bash, coreutils, ...), not what the user installed. The user's packages1399    // live one level down, in the `…-home-manager-path` env the generation1400    // references — descend into it and list ITS references. Fall back to the1401    // generation refs if that env isn't present (older home-manager layouts).1402    const gen_refs = exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, gens[0].path) catch return;1403    defer ctx.gpa.free(gen_refs);14041405    var refs = gen_refs;1406    var env_refs: ?[]u8 = null;1407    defer if (env_refs) |e| ctx.gpa.free(e);1408    if (findHomeManagerPath(gen_refs)) |pkg_path| {1409        if (exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, pkg_path)) |e| {1410            env_refs = e;1411            refs = e;1412        } else |_| {}1413    }14141415    // Dedup by name: multi-output derivations (jq, jq-lib, jq-doc) collapse to1416    // the same name after the output suffix is stripped. Keys are slices into1417    // `refs`, valid for this function's lifetime.1418    var seen = std.StringHashMap(void).init(ctx.gpa);1419    defer seen.deinit();1420    var lines = std.mem.splitScalar(u8, refs, '\n');1421    while (lines.next()) |line| {1422        const t = std.mem.trim(u8, line, " \t\r");1423        if (t.len == 0) continue;1424        const row = pkgFromStorePath(t);1425        if (row.version.len == 0) continue;1426        if (std.mem.indexOf(u8, row.name, "home-manager") != null) continue;1427        if (seen.contains(row.name)) continue;1428        seen.put(row.name, {}) catch {};1429        output.listPkg(row.name, row.version);1430    }1431}14321433// The `…-home-manager-path` env among a generation's references — the buildEnv1434// of the user's home.packages. Returns the full store-path line, or null.1435fn findHomeManagerPath(refs: []const u8) ?[]const u8 {1436    var lines = std.mem.splitScalar(u8, refs, '\n');1437    while (lines.next()) |line| {1438        const t = std.mem.trim(u8, line, " \t\r");1439        if (std.mem.indexOf(u8, t, "home-manager-path") != null) return t;1440    }1441    return null;1442}14431444test "findHomeManagerPath picks the env, not the generation or infra" {1445    const refs =1446        \\/nix/store/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-bash-5.31447        \\/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path1448        \\/nix/store/cccccccccccccccccccccccccccccccc-coreutils-9.111449    ;1450    try std.testing.expectEqualStrings(1451        "/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path",1452        findHomeManagerPath(refs).?,1453    );1454    try std.testing.expectEqual(@as(?[]const u8, null), findHomeManagerPath("/nix/store/x-bash-5.3\n"));1455}14561457fn homeDiff(ctx: Ctx) !void {1458    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1459    defer ctx.gpa.free(out);1460    const gens = try parseHomeGenerations(ctx.gpa, out);1461    defer freeHomeGens(ctx.gpa, gens);14621463    // Need two generations and both their store paths to diff their closures.1464    if (gens.len < 2 or gens[0].path.len == 0 or gens[1].path.len == 0) {1465        output.homeNothingToDiff();1466        return;1467    }1468    const newer = gens[0];1469    const older = gens[1];1470    output.homeDiffHeader(older.number, newer.number, ctx.machine.name);1471    if (try exec.diffClosuresPaths(ctx.io, &ctx.machine, ctx.gpa, older.path, newer.path) != 0)1472        return error.ProcessFailed;1473}14741475fn homeCheck(ctx: Ctx) !void {1476    output.homeCheckStart(ctx.machine.name);1477    const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa);1478    if (code != 0) return error.BuildFailed;1479    output.homeCheckOk();1480}14811482fn homeEdit(ctx: Ctx) !void {1483    // Standalone home config lives at ~/.config/home-manager/home.nix; the same1484    // path is what detection keys on for module mode, so it resolves for both.1485    const path = exec.homeNixPath(ctx.gpa, ctx.environ) orelse {1486        errors.error_info.setMessage("could not resolve ~/.config/home-manager/home.nix", .{});1487        return error.ConfigNotFound;1488    };1489    defer ctx.gpa.free(path);1490    output.homeEditOpen(path, ctx.cfg.editor);1491    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);1492}14931494fn homeHistory(ctx: Ctx) !void {1495    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1496    defer ctx.gpa.free(out);1497    const gens = try parseHomeGenerations(ctx.gpa, out);1498    defer freeHomeGens(ctx.gpa, gens);1499    output.homeHistoryHeader(ctx.machine.name);1500    // Newest-first from home-manager; the first row is the current generation.1501    for (gens, 0..) |g, i| output.homeHistoryRow(g.number, g.date, g.time, i == 0);1502}15031504fn homeBack(ctx: Ctx) !void {1505    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1506    defer ctx.gpa.free(out);1507    const gens = try parseHomeGenerations(ctx.gpa, out);1508    defer freeHomeGens(ctx.gpa, gens);15091510    // Newest-first: [0] is current, [1] is the generation to roll back to.1511    if (gens.len < 2) {1512        output.alreadyOldest();1513        return;1514    }1515    const current = gens[0].number;1516    const prev = gens[1].number;15171518    output.homeBackStart(ctx.machine.name, current, prev);1519    if (ctx.cfg.confirm and !output.confirm("")) return;1520    const code = try exec.homeManagerRollback(ctx.io, &ctx.machine, ctx.gpa);1521    if (code != 0) return error.BuildFailed;1522    output.homeBackDone(prev);1523}15241525fn homeInitCmd(ctx: Ctx) !void {1526    var switch_on_init = false;1527    var dir: ?[]const u8 = null;1528    for (ctx.args) |arg| {1529        if (std.mem.eql(u8, arg, "--switch")) {1530            switch_on_init = true;1531        } else if (!std.mem.startsWith(u8, arg, "-")) {1532            dir = arg;1533        }1534    }15351536    // Guard only the default location — a custom dir is the user's call, and1537    // home-manager creates it. Never clobber an existing ~/.config/home-manager.1538    if (dir == null) {1539        if (exec.homeNixPath(ctx.gpa, ctx.environ)) |path| {1540            defer ctx.gpa.free(path);1541            if (exec.pathExists(ctx.io, path)) {1542                output.homeInitExists(path);1543                return;1544            }1545        }1546    }15471548    output.homeInitStart(switch_on_init, dir);1549    const code = try exec.homeManagerInit(ctx.io, &ctx.machine, ctx.gpa, switch_on_init, dir);1550    if (code != 0) return error.BuildFailed;1551    output.homeInitDone(switch_on_init);1552}15531554fn homeApply(ctx: Ctx, mode: exec.HomeManagerMode) !void {1555    // NixOS/flake module: home config is rebuilt by nixos-rebuild — redirect.1556    if (mode == .module) {1557        output.homeModuleManaged();1558        return;1559    }1560    if (ctx.dry) {1561        output.homeApplyDry(ctx.machine.name);1562        const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa);1563        if (code != 0) return error.BuildFailed;1564        output.homeApplyDryDone();1565        return;1566    }15671568    if (!try runPreHook(ctx, "pre-home")) {1569        output.aborted();1570        return error.HookAborted;1571    }15721573    output.homeApplyStart(ctx.machine.name);15741575    // Flake-based home config: switch by attribute with a graceful fallback1576    // chain. A channel-based config (no flake.nix) uses a plain switch.1577    const dir = exec.homeFlakeDir(ctx.gpa, ctx.io, ctx.environ);1578    defer if (dir) |d| ctx.gpa.free(d);1579    if (dir) |d| return homeApplyFlake(ctx, d);15801581    output.printSubstep("home-manager switch", .{});1582    const start = std.Io.Clock.awake.now(ctx.io);1583    const code = try exec.homeManagerSwitch(ctx.io, &ctx.machine, ctx.gpa);1584    if (code != 0) return error.BuildFailed;15851586    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());1587    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));1588    output.homeApplyDone(homeCurrentGen(ctx), elapsed);1589    runPostHook(ctx, "post-home");1590}15911592// Switch a flake-based home config, trying the most specific attribute first:1593//   <dir>#<user>-<arch>-<os>  →  <dir>#<user>  →  <dir>  (home-manager resolves)1594// Each fallback fires only on a missing-attribute error, never on a real build1595// failure. Mirrors how ${USER}-${system} homeConfigurations keys are written.1596fn homeApplyFlake(ctx: Ctx, dir: []const u8) !void {1597    const user = ctx.environ.get("USER") orelse "default";15981599    var refs: std.ArrayList([]const u8) = .empty;1600    defer {1601        for (refs.items) |r| ctx.gpa.free(r);1602        refs.deinit(ctx.gpa);1603    }1604    if (exec.homeManagerAttr(ctx.gpa, ctx.io, &ctx.machine, ctx.environ) catch null) |attr| {1605        defer ctx.gpa.free(attr);1606        try refs.append(ctx.gpa, try std.fmt.allocPrint(ctx.gpa, "{s}#{s}", .{ dir, attr }));1607    }1608    try refs.append(ctx.gpa, try std.fmt.allocPrint(ctx.gpa, "{s}#{s}", .{ dir, user }));1609    try refs.append(ctx.gpa, try ctx.gpa.dupe(u8, dir));16101611    const start = std.Io.Clock.awake.now(ctx.io);1612    for (refs.items, 0..) |ref, i| {1613        output.printSubstep("home-manager switch --flake {s}", .{ref});1614        switch (try exec.homeManagerSwitchFlake(ctx.io, &ctx.machine, ctx.gpa, ref)) {1615            .ok => {1616                const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());1617                const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));1618                output.homeApplyDone(homeCurrentGen(ctx), elapsed);1619                runPostHook(ctx, "post-home");1620                return;1621            },1622            // Attr not defined by the flake — drop to the next candidate.1623            .attr_missing => {1624                if (i + 1 < refs.items.len) output.homeAttrFallback(ref);1625                continue;1626            },1627            .failed => return error.BuildFailed,1628        }1629    }1630    return error.BuildFailed;1631}16321633// --- Service commands ---16341635const service_help = [_][2][]const u8{1636    .{ "list", "list running services" },1637    .{ "logs <svc>", "show service logs" },1638    .{ "status <svc>", "service status" },1639    .{ "start <svc>", "start a service" },1640    .{ "stop <svc>", "stop a service" },1641    .{ "restart <svc>", "restart a service" },1642    .{ "enable <svc>", "enable at boot" },1643    .{ "disable <svc>", "disable at boot" },1644};16451646pub fn service(ctx: Ctx) !void {1647    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");1648    if (std.mem.eql(u8, ctx.sub, "list")) {1649        output.serviceListHeader(ctx.machine.name);1650        const svcs = exec.serviceList(ctx.gpa, ctx.io, &ctx.machine, ctx.user) catch &.{};1651        defer ctx.gpa.free(svcs);1652        for (svcs) |s| output.serviceRow(s);1653        return;1654    }1655    if (std.mem.eql(u8, ctx.sub, "logs")) {1656        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1657        const follow = ctx.args.len > 1 and std.mem.eql(u8, ctx.args[1], "-f");1658        output.serviceLogsHeader(name, ctx.last, ctx.machine.name);1659        _ = try exec.serviceLogs(ctx.io, &ctx.machine, ctx.gpa, name, ctx.last, follow, ctx.user);1660        return;1661    }1662    if (std.mem.eql(u8, ctx.sub, "status")) {1663        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1664        output.serviceVerb("status", name, ctx.machine.name);1665        _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, "status", name, ctx.user);1666        return;1667    }1668    // start/stop/restart/enable/disable1669    const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1670    if (ctx.cfg.confirm and (std.mem.eql(u8, ctx.sub, "stop") or std.mem.eql(u8, ctx.sub, "disable"))) {1671        if (!output.confirm("")) return;1672    }1673    output.serviceVerb(ctx.sub, name, ctx.machine.name);1674    _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, ctx.sub, name, ctx.user);1675    output.serviceDone();1676}16771678// --- Flake commands ---16791680const flake_help = [_][2][]const u8{1681    .{ "init", "create a new flake.nix" },1682    .{ "update", "update flake inputs" },1683    .{ "update <in>", "update a specific input" },1684    .{ "check", "validate the flake" },1685    .{ "show", "inspect flake outputs" },1686    .{ "lock", "regenerate flake.lock" },1687    .{ "clone <url>", "clone a flake repository" },1688};16891690pub fn flake(ctx: Ctx) !void {1691    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("flake", &flake_help, null);1692    if (std.mem.eql(u8, ctx.sub, "update")) {1693        output.flakeUpdateStart();1694        const input: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1695        _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input, ctx.passthrough);1696        output.flakeLockWritten();1697        return;1698    }1699    if (std.mem.eql(u8, ctx.sub, "check")) {1700        output.flakeCheckStart();1701        const code = try exec.flakeCheck(ctx.io, &ctx.machine, ctx.gpa);1702        if (code == 0) output.flakeValid() else output.checkFailed("");1703        return;1704    }1705    if (std.mem.eql(u8, ctx.sub, "show")) {1706        const json_out = exec.flakeShow(ctx.gpa, ctx.io, &ctx.machine) catch null;1707        if (json_out) |j| {1708            defer ctx.gpa.free(j);1709            output.flakeShowHeader("flake outputs");1710            // Parse and display the flake outputs1711            const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, j, .{}) catch return;1712            defer parsed.deinit();1713            if (parsed.value == .object) {1714                var it = parsed.value.object.iterator();1715                while (it.next()) |entry| {1716                    if (entry.value_ptr.* == .object) {1717                        var inner = entry.value_ptr.object.iterator();1718                        while (inner.next()) |e2| {1719                            const desc = if (e2.value_ptr.* == .object)1720                                if (e2.value_ptr.object.get("description")) |d|1721                                    if (d == .string) d.string else ""1722                                else1723                                    ""1724                            else1725                                "";1726                            output.flakeShowEntry(entry.key_ptr.*, e2.key_ptr.*, desc);1727                        }1728                    }1729                }1730            }1731        }1732        return;1733    }1734    if (std.mem.eql(u8, ctx.sub, "init")) {1735        _ = try exec.flakeInit(ctx.io, &ctx.machine, ctx.gpa);1736        return;1737    }1738    if (std.mem.eql(u8, ctx.sub, "lock")) {1739        _ = try exec.flakeLock(ctx.io, &ctx.machine, ctx.gpa);1740        return;1741    }1742    if (std.mem.eql(u8, ctx.sub, "clone")) {1743        const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1744        _ = try exec.flakeClone(ctx.io, &ctx.machine, ctx.gpa, url);1745        return;1746    }1747}17481749// --- Store commands ---17501751const store_help = [_][2][]const u8{1752    .{ "info", "store size and counts" },1753    .{ "path <attr>", "store path of a package" },1754    .{ "gc", "collect garbage" },1755    .{ "optimise", "deduplicate store paths with hard links" },1756    .{ "verify", "verify store integrity" },1757    .{ "repair", "repair corrupted paths" },1758};17591760pub fn store(ctx: Ctx) !void {1761    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("store", &store_help, null);1762    if (std.mem.eql(u8, ctx.sub, "gc")) {1763        _ = try exec.storeGc(ctx.io, &ctx.machine, ctx.gpa);1764        return;1765    }1766    // Accept both spellings — optimise (en) and optimize (us).1767    if (std.mem.eql(u8, ctx.sub, "optimise") or std.mem.eql(u8, ctx.sub, "optimize")) {1768        output.storeOptimiseStart(ctx.machine.name);1769        _ = try exec.storeOptimise(ctx.io, &ctx.machine, ctx.gpa);1770        output.storeOptimiseDone();1771        return;1772    }1773    if (std.mem.eql(u8, ctx.sub, "verify")) {1774        output.storeVerifyStart();1775        _ = try exec.storeVerify(ctx.io, &ctx.machine, ctx.gpa);1776        return;1777    }1778    if (std.mem.eql(u8, ctx.sub, "repair")) {1779        if (ctx.cfg.confirm and !output.confirm("")) return;1780        output.storeRepairStart();1781        _ = try exec.storeRepair(ctx.io, &ctx.machine, ctx.gpa);1782        return;1783    }1784    if (std.mem.eql(u8, ctx.sub, "info")) {1785        const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1786        output.storeInfo(si);1787        return;1788    }1789    if (std.mem.eql(u8, ctx.sub, "path")) {1790        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1791        const path = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, attr);1792        defer ctx.gpa.free(path);1793        output.storePath(path);1794        return;1795    }1796    // default: info1797    const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1798    output.storeInfo(si);1799}18001801// --- Channel commands ---18021803const channel_help = [_][2][]const u8{1804    .{ "list", "list channels" },1805    .{ "add <url> [name]", "add a channel" },1806    .{ "remove <name>", "remove a channel" },1807    .{ "update", "update all channels" },1808};18091810pub fn channel(ctx: Ctx) !void {1811    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("channel", &channel_help, null);1812    // On a flake-managed system, nix-channel operations generally don't apply.1813    if (flakeSystem(ctx)) output.flakeChannelNote();1814    if (std.mem.eql(u8, ctx.sub, "list")) {1815        output.channelListHeader(ctx.machine.name);1816        const chans = try exec.channelList(ctx.gpa, ctx.io, &ctx.machine);1817        defer ctx.gpa.free(chans);1818        for (chans) |ch| output.channelRow(ch);1819        return;1820    }1821    if (std.mem.eql(u8, ctx.sub, "add")) {1822        const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1823        const name = if (ctx.args.len > 1) ctx.args[1] else "";1824        _ = try exec.channelAdd(ctx.io, &ctx.machine, ctx.gpa, url, name);1825        output.channelDone();1826        return;1827    }1828    if (std.mem.eql(u8, ctx.sub, "remove")) {1829        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1830        _ = try exec.channelRemove(ctx.io, &ctx.machine, ctx.gpa, name);1831        output.channelDone();1832        return;1833    }1834    if (std.mem.eql(u8, ctx.sub, "update")) {1835        return channelUpdateCmd(ctx);1836    }1837}18381839// --- Profile commands ---18401841pub fn profile(ctx: Ctx) !void {1842    if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {1843        output.profileListHeader();1844        const out = exec.profileList(ctx.gpa, ctx.io, &ctx.machine) catch null;1845        if (out) |o| {1846            defer ctx.gpa.free(o);1847            var lines = std.mem.splitScalar(u8, o, '\n');1848            while (lines.next()) |line| {1849                const t = std.mem.trim(u8, line, " \t\r");1850                if (t.len == 0) continue;1851                output.profileRow(t, "", "");1852            }1853        }1854        return;1855    }1856    if (std.mem.eql(u8, ctx.sub, "install")) {1857        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1858        _ = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, ctx.environ, attr, false);1859        output.done();1860        return;1861    }1862    if (std.mem.eql(u8, ctx.sub, "remove")) {1863        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1864        _ = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, attr);1865        output.done();1866        return;1867    }1868    if (std.mem.eql(u8, ctx.sub, "upgrade")) {1869        _ = try exec.profileUpgrade(ctx.io, &ctx.machine, ctx.gpa);1870        output.done();1871        return;1872    }1873}18741875// --- Pkg commands ---18761877const pkg_help = [_][2][]const u8{1878    .{ "why <pkg>", "what pulled it in" },1879    .{ "deps <pkg>", "direct dependencies" },1880    .{ "size <pkg>", "closure size" },1881    .{ "path <pkg>", "store path" },1882    .{ "closure <pkg>", "full closure" },1883};18841885pub fn pkg(ctx: Ctx) !void {1886    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("pkg", &pkg_help, null);1887    const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1888    if (std.mem.eql(u8, ctx.sub, "why")) {1889        if (try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1890        return;1891    }1892    if (std.mem.eql(u8, ctx.sub, "deps")) {1893        if (try exec.pkgDeps(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1894        return;1895    }1896    if (std.mem.eql(u8, ctx.sub, "size")) {1897        const s = try exec.pkgSize(ctx.gpa, ctx.io, &ctx.machine, name);1898        defer ctx.gpa.free(s);1899        output.pkgResult("size", s);1900        return;1901    }1902    if (std.mem.eql(u8, ctx.sub, "path")) {1903        const p = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, name);1904        defer ctx.gpa.free(p);1905        output.pkgResult("path", p);1906        return;1907    }1908    if (std.mem.eql(u8, ctx.sub, "closure")) {1909        if (try exec.pkgClosure(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1910        return;1911    }1912}19131914// Top-level alias for `nina pkg why <pkg>` — surfaces what pulled a package in1915// without the user needing to know about the `pkg` subgroup.1916pub fn why(ctx: Ctx) !void {1917    const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1918    if (try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1919}19201921// --- Pin / Unpin ---19221923pub fn pin(ctx: Ctx) !void {1924    const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1925    const commit = if (ctx.args.len > 1) ctx.args[1] else return error.Internal;1926    exec.editFlakeLock(ctx.gpa, input, commit) catch return error.ProcessFailed;1927    output.pinDone(input, commit);1928}19291930pub fn unpin(ctx: Ctx) !void {1931    const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1932    _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input, &.{});1933    output.unpinDone(input);1934}19351936// --- Hash / Fetch ---19371938pub fn hash(ctx: Ctx) !void {1939    const path = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1940    const h = try exec.nixHash(ctx.gpa, ctx.io, &ctx.machine, path);1941    defer ctx.gpa.free(h);1942    output.hashResult(std.mem.trim(u8, h, " \t\n\r"));1943}19441945pub fn fetch(ctx: Ctx) !void {1946    const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1947    const h = try exec.nixFetch(ctx.gpa, ctx.io, &ctx.machine, url);1948    defer ctx.gpa.free(h);1949    output.fetchResult(std.mem.trim(u8, h, " \t\n\r"), url);1950}19511952// --- Build / Run ---19531954pub fn build(ctx: Ctx) !void {1955    const attr: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1956    output.buildStart(attr orelse "default");1957    const code = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, attr);1958    if (code != 0) return error.BuildFailed;1959    output.buildDone();1960}19611962pub fn runCmd(ctx: Ctx) !void {1963    const pkg_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1964    output.runStart(pkg_arg);1965    _ = try exec.nixRun(ctx.io, &ctx.machine, ctx.gpa, pkg_arg);1966}19671968// --- Hello ---19691970pub fn hello(ctx: Ctx) !void {1971    output.hello(ctx.cfg.machines);1972}19731974const ConfigKind = enum { flake, channel, none };19751976// Scan the conventional /etc/nixos for a flake.nix (flake-based) or a1977// configuration.nix (channel-based) to pre-fill the wizard's defaults.1978fn scanConfig(io: std.Io) ConfigKind {1979    if (exec.pathExists(io, "/etc/nixos/flake.nix")) return .flake;1980    if (exec.pathExists(io, "/etc/nixos/configuration.nix")) return .channel;1981    return .none;1982}19831984// Runs when the config is absent on first invocation (interactive TTY only).1985// Scans for an existing nixos config, detects flake vs channel, and offers a1986// smart default path — flake-ness is detected, never asked.1987pub fn firstRunWizard(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1988    output.firstRunBanner();1989    output.firstRunNoConfig();19901991    var name_buf: [256]u8 = undefined;1992    var path_buf: [256]u8 = undefined;19931994    const machine_name = output.firstRunPrompt("machine name", "my-machine", &name_buf);19951996    output.firstRunScanning();1997    const kind = scanConfig(io);1998    switch (kind) {1999        .flake => output.firstRunDetected("/etc/nixos/flake.nix", true),2000        .channel => output.firstRunDetected("/etc/nixos/configuration.nix", false),2001        .none => output.firstRunNoneFound(),2002    }20032004    // Detected systems default to /etc/nixos (press enter to confirm); when2005    // nothing was found, leave the default empty so the user must type a path.2006    const default_path: []const u8 = if (kind == .none) "" else "/etc/nixos";2007    const config_path = output.firstRunPromptDefault("config path", default_path, kind != .none, &path_buf);20082009    // Re-detect at the chosen path in case the user pointed elsewhere — flake.nix2010    // there means a flake system, recorded so channel commands warn appropriately.2011    const use_flakes = exec.dirHasFlake(gpa, io, config_path);20122013    const conf_path = try config.configPath(gpa, environ);2014    defer gpa.free(conf_path);2015    if (std.fs.path.dirname(conf_path)) |dir| exec.ensureDir(gpa, io, dir);20162017    // `flake` is a top-level config field, so it must precede the [machine] block.2018    const flake_line = if (use_flakes) "flake = true\n" else "";2019    var content_buf: [1024]u8 = undefined;2020    const content = try std.fmt.bufPrint(2021        &content_buf,2022        "{s}[machine]\nname = {s}\nconfig = {s}\nlocal = true\n",2023        .{ flake_line, machine_name, config_path },2024    );20252026    const file = std.Io.Dir.createFile(.cwd(), io, conf_path, .{}) catch {2027        errors.error_info.setMessage("could not write {s}", .{conf_path});2028        return error.Internal;2029    };2030    defer file.close(io);2031    file.writePositionalAll(io, content, 0) catch {2032        errors.error_info.setMessage("could not write {s}", .{conf_path});2033        return error.Internal;2034    };20352036    output.firstRunWritten(conf_path);2037}20382039pub fn setup(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {2040    // Create the config first if it doesn't exist. This makes `nina setup`2041    // a complete onboarding command — not just a nix-features check. Any legacy2042    // ~/.nina.conf is migrated to the XDG path before we decide to run the wizard.2043    config.migrateLegacyConfig(gpa, io, environ);2044    if (config.configPath(gpa, environ)) |conf_path| {2045        defer gpa.free(conf_path);2046        if (std.Io.Dir.openFile(.cwd(), io, conf_path, .{})) |f| {2047            f.close(io);2048        } else |_| {2049            try firstRunWizard(gpa, io, environ);2050            errors.error_info.reset();2051        }2052    } else |_| {}20532054    output.setupCheck();2055    const status = exec.checkNixFeatures(gpa, io, environ);2056    output.setupFeatures(status.nix_command, status.flakes);20572058    if (status.allEnabled()) {2059        output.setupAllSet();2060        api.ensureRegistryPinned(gpa, io, environ);2061        return;2062    }20632064    // On NixOS the features belong in configuration.nix (the declarative,2065    // permanent home), not ~/.config/nix/nix.conf. Offer to add the one line;2066    // the user runs the rebuild. We don't pin the registry here because the2067    // features aren't live until that rebuild lands.2068    if (exec.isNixOS(io)) {2069        const conf_path = "/etc/nixos/configuration.nix";2070        if (exec.nixosConfigEnablesFeatures(gpa, io, conf_path)) {2071            output.setupNixosNeedsRebuild(conf_path);2072            return;2073        }2074        output.setupNixosOffer(exec.NIXOS_FEATURES_LINE, conf_path);2075        if (output.confirmDefaultNo("add it now?")) {2076            if (exec.appendFeaturesToNixosConfig(gpa, io, environ, conf_path)) |_| {2077                output.setupNixosWrote(conf_path);2078            } else |_| {2079                output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);2080            }2081        } else {2082            output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);2083        }2084        return;2085    }20862087    // Non-NixOS: a user-level nix.conf takes effect immediately, no sudo needed.2088    output.setupEnabling();2089    const path = try exec.enableNixFeatures(gpa, io, environ);2090    defer gpa.free(path);20912092    output.setupDone(path);2093    api.ensureRegistryPinned(gpa, io, environ);2094}20952096// --- Log helper ---20972098fn logAction(ctx: Ctx, action: []const u8, gen: u32) void {2099    var ts_buf: [32]u8 = undefined;2100    const ts = nowIso(ctx.io, &ts_buf);2101    var buf: [256]u8 = undefined;2102    const entry = std.fmt.bufPrint(&buf, "{{\"ts\":\"{s}\",\"machine\":\"{s}\",\"command\":\"{s}\",\"outcome\":\"success\",\"gen_before\":null,\"gen_after\":{d},\"duration_ms\":0}}\n", .{2103        ts, ctx.machine.name, action, gen,2104    }) catch return;2105    exec.appendNinaLog(ctx.io, ctx.environ, entry);2106}21072108// Wall-clock UTC as ISO-8601. Uses Io.Clock.real (the settable Unix-epoch clock);2109// Io.Clock.awake is monotonic and unsuitable for timestamps. Falls back to epoch 0.2110fn nowIso(io: std.Io, buf: []u8) []const u8 {2111    const fallback = "1970-01-01T00:00:00Z";2112    const ns = std.Io.Clock.real.now(io).toNanoseconds();2113    if (ns <= 0) return fallback;2114    const secs: u64 = @intCast(@divFloor(ns, 1_000_000_000));2115    const es = std.time.epoch.EpochSeconds{ .secs = secs };2116    const ed = es.getEpochDay();2117    const yd = ed.calculateYearDay();2118    const md = yd.calculateMonthDay();2119    const ds = es.getDaySeconds();2120    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", .{2121        yd.year,              md.month.numeric(),      @as(u32, md.day_index) + 1,2122        ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(),2123    }) catch return fallback;2124}