commands.zig

84.9 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, ctx.passthrough);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, ctx.passthrough) 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, ctx.passthrough);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        // Build the new version into the store BEFORE touching the profile. A427        // network drop or eval failure here leaves the old element untouched —428        // this is the only step that can fail for reasons outside our control,429        // so it must happen first. Once this succeeds, the subsequent430        // remove+add operates on an already-warm local store and is not431        // expected to fail for the same reasons, closing the window a raw432        // remove-then-add would leave open between the two profile edits.433        const prefetch_r = exec.capture(ctx.gpa, ctx.io, &ctx.machine, &.{ "nix", "build", "--no-link", "--refresh", FLAKE_URL }) catch {434            output.updateSelfNixPrefetchFailed();435            return;436        };437        defer ctx.gpa.free(prefetch_r.stdout);438        defer ctx.gpa.free(prefetch_r.stderr);439        if (prefetch_r.exit_code != 0) {440            output.raw(prefetch_r.stdout);441            output.raw(prefetch_r.stderr);442            output.updateSelfNixPrefetchFailed();443            return;444        }445        // `nix profile upgrade` re-resolves the element's own originalUrl. The446        // archive install runs with --no-write-lock-file, so nix has nowhere to447        // persist the lock it takes at install time except baking it into that448        // originalUrl as a `?narHash=` pin — which then never changes no matter449        // how far kepr's HEAD moves. Upgrading against that pin is a permanent450        // no-op: exit 0, "upgrading from X to X", nothing installed. Remove and451        // re-add against the plain (unpinned) archive URL instead, so nix452        // actually re-resolves HEAD and picks up a fresh narHash.453        const remove_r = exec.capture(ctx.gpa, ctx.io, &ctx.machine, &.{ "nix", "profile", "remove", element }) catch {454            output.updateSelfNixFailed();455            return;456        };457        defer ctx.gpa.free(remove_r.stdout);458        defer ctx.gpa.free(remove_r.stderr);459        if (remove_r.exit_code != 0) {460            output.raw(remove_r.stdout);461            output.raw(remove_r.stderr);462            output.updateSelfNixFailed();463            return;464        }465        // Even against the plain unpinned URL, nix caches its resolution for466        // `tarball-ttl` seconds (default 3600) regardless of HTTP cache-control467        // headers — so within an hour of any prior nix operation touching this468        // URL, add would silently reuse the stale narHash and reinstall the469        // same old version. --refresh forces nix to actually re-check HEAD.470        const add_r = exec.capture(ctx.gpa, ctx.io, &ctx.machine, &.{ "nix", "profile", "add", "--no-write-lock-file", "--refresh", FLAKE_URL }) catch {471            output.updateSelfNixReinstallFailed();472            return;473        };474        defer ctx.gpa.free(add_r.stdout);475        defer ctx.gpa.free(add_r.stderr);476        if (add_r.exit_code != 0) {477            output.raw(add_r.stdout);478            output.raw(add_r.stderr);479            output.updateSelfNixReinstallFailed();480            return;481        }482        output.updateSelfDone(version.VERSION, remote_ver);483        output.updateSelfNixRehash();484        return;485    }486487    const plat_info = blk: {488        const pv = root.object.get("platforms") orelse break :blk null;489        if (pv != .object) break :blk null;490        break :blk pv.object.get(version.PLATFORM);491    };492    if (plat_info == null) {493        output.updateSelfNoPlatform(version.PLATFORM);494        return;495    }496497    const dl_url = blk: {498        const v = plat_info.?.object.get("url") orelse {499            output.printWarning("malformed release metadata");500            return;501        };502        break :blk switch (v) {503            .string => |s| s,504            else => {505                output.printWarning("malformed release metadata");506                return;507            },508        };509    };510511    const raw_cksum = blk: {512        if (plat_info.?.object.get("blake3")) |v|513            break :blk switch (v) {514                .string => |s| s,515                else => {516                    output.printWarning("malformed release metadata");517                    return;518                },519            };520        if (plat_info.?.object.get("checksum")) |v|521            break :blk switch (v) {522                .string => |s| s,523                else => {524                    output.printWarning("malformed release metadata");525                    return;526                },527            };528        output.printWarning("missing checksum in release metadata");529        return;530    };531    const expected_hex = if (std.mem.startsWith(u8, raw_cksum, "blake3:")) raw_cksum["blake3:".len..] else raw_cksum;532533    if (ctx.cfg.confirm and !output.confirm("")) return;534535    output.updateSelfDownloading(remote_ver, version.PLATFORM);536    const tmp_path = exec.downloadToTemp(ctx.gpa, ctx.io, dl_url) catch {537        output.printWarning("download failed — check your connection and try again");538        return;539    };540    defer ctx.gpa.free(tmp_path);541    // Clean up the downloaded temp file whether install succeeds or fails —542    // it's only ever a scratch copy verified against the release checksum.543    defer std.Io.Dir.deleteFileAbsolute(ctx.io, tmp_path) catch {};544545    output.updateSelfVerifying();546    exec.verifyAndInstall(ctx.gpa, ctx.io, tmp_path, expected_hex, install_path) catch |e| switch (e) {547        error.ChecksumMismatch => {548            output.updateSelfChecksumFailed();549            return;550        },551        else => return e,552    };553554    output.updateSelfDone(version.VERSION, remote_ver);555}556557// archives.json covers every version between current and latest; the manifest's558// `notes` field only ever describes the single latest release. Try the full-range559// changelog first so an update spanning several versions doesn't collapse down to560// just the newest one's notes — fall back to `notes` only when the archive has561// nothing (e.g. releases predating archives.json, or the fetch failing).562fn updateReleaseNotes(gpa: std.mem.Allocator, io: std.Io, root: std.json.Value, source_url: []const u8, current: []const u8, latest: []const u8) ![]u8 {563    if (buildKeprArchiveReleaseNotes(gpa, io, source_url, current, latest) catch null) |notes| {564        if (std.mem.trim(u8, notes, " \t\r\n").len > 0) return notes;565        gpa.free(notes);566    }567    if (releaseNotesFromMetadata(gpa, root)) |notes| return notes;568    return gpa.dupe(u8, "");569}570571fn releaseNotesFromMetadata(gpa: std.mem.Allocator, root: std.json.Value) ?[]u8 {572    if (root != .object) return null;573    // `notes` is the one canonical manifest field. The retired `release_notes`574    // and `changelog` fallbacks are gone — Kepr now emits `notes` everywhere, and575    // releases that predate `--notes` fall back to archives.json in the caller.576    const v = root.object.get("notes") orelse return null;577    return switch (v) {578        .string => |s| gpa.dupe(u8, s) catch null,579        else => null,580    };581}582583fn buildKeprArchiveReleaseNotes(gpa: std.mem.Allocator, io: std.Io, source_url: []const u8, current: []const u8, latest: []const u8) ![]u8 {584    const archive_url = try keprArchiveUrl(gpa, source_url);585    defer gpa.free(archive_url);586587    const body = exec.fetchUrl(gpa, io, archive_url) catch return gpa.dupe(u8, "");588    defer gpa.free(body);589590    return releaseNotesFromArchiveJson(gpa, body, current, latest);591}592593fn keprArchiveUrl(gpa: std.mem.Allocator, source_url: []const u8) ![]u8 {594    const scheme = std.mem.indexOf(u8, source_url, "://") orelse return error.InvalidUpdateSource;595    const path_start = std.mem.indexOfScalarPos(u8, source_url, scheme + 3, '/') orelse return error.InvalidUpdateSource;596    const origin = source_url[0..path_start];597    const path = source_url[path_start..];598    if (!std.mem.startsWith(u8, path, "/api/")) return error.InvalidUpdateSource;599600    const after_api = path["/api/".len..];601    const repo_end = std.mem.indexOfScalar(u8, after_api, '/') orelse return error.InvalidUpdateSource;602    const repo = after_api[0..repo_end];603    if (repo.len == 0) return error.InvalidUpdateSource;604605    return std.fmt.allocPrint(gpa, "{s}/{s}/archives.json?limit=100", .{ origin, repo });606}607608// Saves arrive newest-first. For each version in the update range we want the OLDEST609// save message (the one that introduced that version), not a follow-up cleanup/docs save.610// We overwrite the tracked message on each occurrence, so the final stored value per611// version is always the oldest (last-seen in a newest-first stream).612fn releaseNotesFromArchiveJson(gpa: std.mem.Allocator, body: []const u8, current: []const u8, latest: []const u8) ![]u8 {613    const parsed = std.json.parseFromSlice(std.json.Value, gpa, body, .{}) catch return gpa.dupe(u8, "");614    defer parsed.deinit();615616    if (parsed.value != .object) return gpa.dupe(u8, "");617    const saves_v = parsed.value.object.get("saves") orelse return gpa.dupe(u8, "");618    if (saves_v != .array) return gpa.dupe(u8, "");619620    // version string → oldest message seen (both slice into parsed JSON, valid until deinit)621    var best_msg = std.StringHashMap([]const u8).init(gpa);622    defer best_msg.deinit();623    var order: std.ArrayList([]const u8) = .empty;624    defer order.deinit(gpa);625626    for (saves_v.array.items) |save| {627        if (save != .object) continue;628        const ver_v = save.object.get("version") orelse continue;629        const msg_v = save.object.get("message") orelse continue;630        if (ver_v != .string or msg_v != .string) continue;631        const ver = ver_v.string;632        const msg = std.mem.trim(u8, msg_v.string, " \t\r\n");633        if (msg.len == 0 or !versionInUpdateRange(ver, current, latest)) continue;634635        const entry = try best_msg.getOrPut(ver);636        if (!entry.found_existing) try order.append(gpa, ver);637        // Always overwrite: saves are newest-first, so last write = oldest save = version-intro message638        entry.value_ptr.* = msg;639    }640641    if (order.items.len == 0) return gpa.dupe(u8, "");642643    var out: std.ArrayList(u8) = .empty;644    errdefer out.deinit(gpa);645    for (order.items) |ver| {646        const msg = best_msg.get(ver).?;647        // Use only the first line as the summary; multi-line saves may have implementation details below648        const summary_end = std.mem.indexOf(u8, msg, "\n") orelse msg.len;649        const summary = std.mem.trim(u8, msg[0..summary_end], " \t\r");650        if (summary.len == 0) continue;651        try appendLine(&out, gpa, "## {s}\n", .{ver});652        try appendLine(&out, gpa, "- {s}\n\n", .{summary});653    }654655    if (out.items.len == 0) {656        out.deinit(gpa);657        return gpa.dupe(u8, "");658    }659    return out.toOwnedSlice(gpa);660}661662fn appendLine(out: *std.ArrayList(u8), gpa: std.mem.Allocator, comptime template: []const u8, args: anytype) !void {663    const line = try std.fmt.allocPrint(gpa, template, args);664    defer gpa.free(line);665    try out.appendSlice(gpa, line);666}667668fn versionInUpdateRange(candidate: []const u8, current: []const u8, latest: []const u8) bool {669    const cand = parseSemver(candidate) orelse return std.mem.eql(u8, candidate, latest);670    const cur = parseSemver(current) orelse return std.mem.eql(u8, candidate, latest);671    const lat = parseSemver(latest) orelse return std.mem.eql(u8, candidate, latest);672    return compareSemver(cand, cur) == .gt and compareSemver(cand, lat) != .gt;673}674675fn remoteVersionNewer(current: []const u8, remote: []const u8) bool {676    const cur = parseSemver(current) orelse return !std.mem.eql(u8, current, remote);677    const rem = parseSemver(remote) orelse return !std.mem.eql(u8, current, remote);678    return compareSemver(rem, cur) == .gt;679}680681const VersionOrder = enum { lt, eq, gt };682683fn compareSemver(a: Semver, b: Semver) VersionOrder {684    if (a.major != b.major) return if (a.major < b.major) .lt else .gt;685    if (a.minor != b.minor) return if (a.minor < b.minor) .lt else .gt;686    if (a.patch != b.patch) return if (a.patch < b.patch) .lt else .gt;687    return .eq;688}689690fn parseSemver(raw: []const u8) ?Semver {691    const v = if (std.mem.startsWith(u8, raw, "v")) raw[1..] else raw;692    var it = std.mem.splitScalar(u8, v, '.');693    const major_s = it.next() orelse return null;694    const minor_s = it.next() orelse return null;695    const patch_s = it.next() orelse return null;696    if (it.next() != null) return null;697    return .{698        .major = std.fmt.parseInt(u32, major_s, 10) catch return null,699        .minor = std.fmt.parseInt(u32, minor_s, 10) catch return null,700        .patch = std.fmt.parseInt(u32, patch_s, 10) catch return null,701    };702}703704test "versionInUpdateRange includes only newer versions through latest" {705    try std.testing.expect(versionInUpdateRange("3.2.3", "3.1.9", "3.2.3"));706    try std.testing.expect(versionInUpdateRange("3.2.0", "3.1.9", "3.2.3"));707    try std.testing.expect(!versionInUpdateRange("3.1.9", "3.1.9", "3.2.3"));708    try std.testing.expect(!versionInUpdateRange("3.2.4", "3.1.9", "3.2.3"));709}710711test "remoteVersionNewer does not offer downgrades" {712    try std.testing.expect(remoteVersionNewer("3.2.3", "3.2.4"));713    try std.testing.expect(!remoteVersionNewer("3.2.4", "3.2.3"));714    try std.testing.expect(!remoteVersionNewer("3.2.4", "3.2.4"));715}716717test "releaseNotesFromArchiveJson uses oldest save per version" {718    // Saves arrive newest-first. For 3.2.3, the newest save is a CONTINUITY update;719    // the oldest is the version-intro message. We expect the intro message in the output.720    const body =721        \\{722        \\  "saves": [723        \\    {"version":"3.2.3","message":"wip: record verification in CONTINUITY"},724        \\    {"version":"3.2.1","message":"old release"},725        \\    {"version":"3.2.3","message":"add streaming deflate path"}726        \\  ]727        \\}728    ;729    const notes = try releaseNotesFromArchiveJson(std.testing.allocator, body, "3.2.1", "3.2.3");730    defer std.testing.allocator.free(notes);731732    try std.testing.expect(std.mem.indexOf(u8, notes, "## 3.2.3") != null);733    try std.testing.expect(std.mem.indexOf(u8, notes, "- add streaming deflate path") != null);734    try std.testing.expect(std.mem.indexOf(u8, notes, "CONTINUITY") == null);735    try std.testing.expect(std.mem.indexOf(u8, notes, "old release") == null);736}737738test "releaseNotesFromMetadata reads canonical notes and ignores retired keys" {739    const a = std.testing.allocator;740741    // Canonical field is read.742    {743        var parsed = try std.json.parseFromSlice(std.json.Value, a, "{\"notes\":\"colored progress bar\"}", .{});744        defer parsed.deinit();745        const got = releaseNotesFromMetadata(a, parsed.value).?;746        defer a.free(got);747        try std.testing.expectEqualStrings("colored progress bar", got);748    }749750    // Retired field names are no longer honoured — they fall through to null so751    // the caller drops to the archives.json derivation instead.752    {753        var parsed = try std.json.parseFromSlice(std.json.Value, a, "{\"release_notes\":\"x\",\"changelog\":\"y\"}", .{});754        defer parsed.deinit();755        try std.testing.expect(releaseNotesFromMetadata(a, parsed.value) == null);756    }757}758759// nina goodbye — clean uninstall. Three install paths:760// - nix profile (binary in nix store with a profile element) → nix profile remove761// - koh build or source build (plain binary on PATH) → delete the file762pub fn goodbye(ctx: Ctx) !void {763    output.goodbyeStart();764765    var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;766    const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {767        errors.error_info.setMessage("could not determine install path", .{});768        return error.Internal;769    };770771    // A binary outside the nix store is a koh build or source build — delete it.772    if (!std.mem.startsWith(u8, install_path, "/nix/store/")) {773        output.goodbyeFile(install_path);774        if (ctx.cfg.confirm and !output.confirm("")) return;775        std.Io.Dir.deleteFileAbsolute(ctx.io, install_path) catch |e| {776            errors.error_info.setMessage("could not remove {s}", .{install_path});777            return e;778        };779        output.goodbyeDone();780        return;781    }782783    // Binary is in the nix store — find and remove the profile element.784    const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);785    defer {786        if (nina_element) |n| ctx.gpa.free(n);787    }788789    if (nina_element == null) {790        errors.error_info.setMessage("nina not found in nix profile — was it installed via 'nix profile add'?", .{});791        return error.Internal;792    }793794    output.goodbyeNix();795    if (ctx.cfg.confirm and !output.confirm("")) return;796    const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "remove", nina_element.? }) catch {797        output.goodbyeFailed("nix profile remove failed");798        return;799    };800    if (ec != 0) {801        output.goodbyeFailed("nix profile remove failed");802        return;803    }804    output.goodbyeDone();805}806807fn channelUpdateCmd(ctx: Ctx) !void {808    output.updateStart(ctx.machine.name);809    _ = try exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa);810    output.updateDone();811}812813pub fn upgrade(ctx: Ctx) !void {814    if (!try runPreHook(ctx, "pre-upgrade")) {815        output.aborted();816        return error.HookAborted;817    }818819    output.upgradeStart(ctx.machine.name);820    // Flake systems update inputs (flake.lock); channel systems update channels.821    // Running nix-channel --update on a flake system is a no-op at best. The822    // rebuild below is already flake-aware via exec.nixosRebuildSwitch.823    if (flakeSystem(ctx)) {824        output.printSubstep("updating flake inputs", .{});825        _ = exec.flakeUpdateAt(ctx.io, &ctx.machine, ctx.gpa, ctx.machine.config_path) catch {};826    } else {827        output.printSubstep("updating channels", .{});828        _ = exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa) catch {};829    }830    output.printSubstep("rebuilding", .{});831    output.buildPanelInit();832    const start = std.Io.Clock.awake.now(ctx.io);833    var panel = output.BuildPanel{};834    const code = exec.nixosRebuildSwitchWithPanel(ctx.io, &ctx.machine, ctx.gpa, &panel, ctx.passthrough) catch |e| {835        output.buildPanelClear();836        return e;837    };838    output.buildPanelClear();839    if (code != 0) {840        output.applyFailed("");841        return error.BuildFailed;842    }843    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());844    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));845    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;846    output.applyDone(gen, elapsed, false);847    runPostHook(ctx, "post-upgrade");848}849850pub fn log(ctx: Ctx) !void {851    output.logHeader(ctx.machine.name);852    const content = exec.readNinaLog(ctx.gpa, ctx.io, ctx.environ, ctx.last) catch {853        // No log yet — that's fine854        return;855    };856    defer ctx.gpa.free(content);857    var lines = std.mem.splitScalar(u8, content, '\n');858    while (lines.next()) |line| {859        const t = std.mem.trim(u8, line, " \t\r");860        if (t.len == 0) continue;861        if (t[0] == '{') {862            renderJsonLogLine(ctx.gpa, t);863        } else {864            // legacy tab-separated format865            var parts = std.mem.tokenizeScalar(u8, t, '\t');866            const date = parts.next() orelse continue;867            const time = parts.next() orelse "";868            const action = parts.next() orelse "";869            const detail = parts.next() orelse "";870            output.logRow(date, time, action, detail);871        }872    }873}874875// The on-disk log is JSON Lines: {"ts","machine","command","outcome","gen_after",...}.876// Render ts -> date/time columns, command -> action, outcome(+gen) -> detail.877fn renderJsonLogLine(gpa: std.mem.Allocator, line: []const u8) void {878    const parsed = std.json.parseFromSlice(std.json.Value, gpa, line, .{}) catch {879        output.logRow(line, "", "", ""); // unparseable — show raw rather than drop880        return;881    };882    defer parsed.deinit();883    if (parsed.value != .object) return;884    const o = parsed.value.object;885886    const ts = jsonStr(o, "ts");887    const date = if (ts.len >= 10) ts[0..10] else ts;888    const time = if (ts.len >= 16) ts[11..16] else "";889    const action = jsonStr(o, "command");890    const outcome = jsonStr(o, "outcome");891892    var buf: [160]u8 = undefined;893    var detail: []const u8 = outcome;894    if (o.get("gen_after")) |g| {895        if (g == .integer) {896            detail = std.fmt.bufPrint(&buf, "{s}   -> gen {d}", .{ outcome, g.integer }) catch outcome;897        }898    }899    output.logRow(date, time, action, detail);900}901902fn jsonStr(o: std.json.ObjectMap, key: []const u8) []const u8 {903    if (o.get(key)) |v| {904        if (v == .string) return v.string;905    }906    return "";907}908909pub fn edit(ctx: Ctx) !void {910    // `edit` is multi-word, so a bare positional ("hardware") arrives as ctx.sub.911    // hardware-configuration.nix is generated by nixos-generate-config and warns912    // against hand-editing — refuse rather than silently opening the wrong file.913    if (std.mem.eql(u8, ctx.sub, "hardware")) {914        output.editHardwareWarning();915        return;916    }917918    // --dir opens the whole config directory (for editors that work better with919    // a folder open), as root so root-owned config trees like /etc/nixos work.920    var open_dir = false;921    for (ctx.args) |arg| {922        if (std.mem.eql(u8, arg, "--dir")) open_dir = true;923    }924    if (open_dir) {925        output.editOpen(ctx.machine.config_path, ctx.cfg.editor);926        _ = try exec.openEditorSudo(ctx.io, ctx.gpa, ctx.cfg.editor, ctx.machine.config_path);927        return;928    }929930    const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});931    defer ctx.gpa.free(path);932    output.editOpen(path, ctx.cfg.editor);933    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);934}935936pub fn fmt(ctx: Ctx) !void {937    const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});938    defer ctx.gpa.free(path);939    if (ctx.check) {940        const code = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, true);941        if (code != 0) output.fmtNeedsFormat() else output.fmtDone();942        return;943    }944    output.fmtStart(path);945    _ = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, false);946    output.fmtDone();947}948949pub fn repl(ctx: Ctx) !void {950    output.replStart();951    _ = try exec.nixRepl(ctx.io, &ctx.machine, ctx.gpa);952}953954pub fn develop(ctx: Ctx) !void {955    if (std.mem.eql(u8, ctx.sub, "show")) {956        _ = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, null, ctx.passthrough);957        return;958    }959    const run_cmd: ?[]const u8 = if (ctx.args.len > 0 and std.mem.eql(u8, ctx.sub, "run"))960        ctx.args[0]961    else962        null;963    output.developStart(&.{});964    _ = try exec.nixDevelopPs1(ctx.io, &ctx.machine, ctx.gpa, run_cmd, ctx.environ, ctx.passthrough);965    output.developDone();966}967968pub fn info(ctx: Ctx) !void {969    output.infoHeader(ctx.machine.name);970    const nixos_ver = exec.systemInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");971    defer ctx.gpa.free(nixos_ver);972    output.infoRow("nixos", std.mem.trim(u8, nixos_ver, " \t\n\r"));973974    const kernel = exec.kernelInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");975    defer ctx.gpa.free(kernel);976    output.infoRow("kernel", std.mem.trim(u8, kernel, " \t\n\r"));977978    const uptime = exec.uptimeInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");979    defer ctx.gpa.free(uptime);980    output.infoRow("uptime", std.mem.trim(u8, uptime, " \t\n\r"));981}982983pub fn boot(ctx: Ctx) !void {984    output.bootHeader(ctx.machine.name);985    const entries = exec.bootEntries(ctx.gpa, ctx.io, &ctx.machine) catch &.{};986    defer ctx.gpa.free(entries);987    for (entries, 0..) |entry, i| output.bootEntry(entry, i);988}989990pub fn searchCmd(ctx: Ctx) !void {991    const query = if (ctx.args.len > 0) ctx.args[0] else "";992    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);993    const selected = try search_tui.run(ctx.gpa, ctx.io, query, .packages, ctx.environ);994    if (selected) |npkg| try selectAndInstall(ctx, npkg);995}996997pub fn optionCmd(ctx: Ctx) !void {998    const query = if (ctx.args.len > 0) ctx.args[0] else "";999    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);1000    _ = try search_tui.run(ctx.gpa, ctx.io, query, .options, ctx.environ);1001}10021003pub fn install(ctx: Ctx) !void {1004    const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;10051006    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);10071008    // Search for the package to get the attr1009    const pkgs = api.searchPackages(ctx.gpa, ctx.io, ctx.environ, pkg_name) catch {1010        errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});1011        errors.error_info.setSuggestion("nina search {s}", .{pkg_name});1012        return error.PackageNotFound;1013    };10141015    if (pkgs.len == 0) {1016        // No matches — likely a typo. Suggest the closest real package and offer it.1017        if (closestPackage(ctx, pkg_name)) |sugg| {1018            output.didYouMean(pkg_name, sugg.pname);1019            if (output.confirm("")) try selectAndInstall(ctx, sugg);1020            return;1021        }1022        errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});1023        errors.error_info.setSuggestion("nina search {s}", .{pkg_name});1024        return error.PackageNotFound;1025    }10261027    // Prefer an exact name match over the first search result — `install ripgrep`1028    // must pick "ripgrep", not the alphabetically-first match like "repgrep".1029    var found = pkgs[0];1030    for (pkgs) |p| {1031        if (std.mem.eql(u8, p.pname, pkg_name)) {1032            found = p;1033            break;1034        }1035    }1036    try selectAndInstall(ctx, found);1037}10381039// Find the real package whose name is closest to a not-found query (typo help).1040// Typos usually keep the leading characters, so gather candidates with a prefix1041// search and rank by edit distance; return the best only if it's typo-close.1042fn closestPackage(ctx: Ctx, query: []const u8) ?types.NixPackage {1043    if (query.len < 2) return null;1044    var candidates = api.searchPackages(ctx.gpa, ctx.io, ctx.environ, query[0..@min(query.len, 4)]) catch &.{};1045    if (candidates.len == 0 and query.len > 2) {1046        candidates = api.searchPackages(ctx.gpa, ctx.io, ctx.environ, query[0..2]) catch &.{};1047    }1048    if (candidates.len == 0) return null;10491050    var best: ?types.NixPackage = null;1051    var best_dist: usize = std.math.maxInt(usize);1052    for (candidates) |p| {1053        const d = editDistance(query, p.pname);1054        if (d > 0 and d < best_dist) {1055            best_dist = d;1056            best = p;1057        }1058    }1059    // Only suggest a genuinely close name, scaled to query length.1060    const threshold = @max(@as(usize, 2), query.len / 3);1061    return if (best_dist <= threshold) best else null;1062}10631064// Case-insensitive Levenshtein distance. Names longer than the row buffer are1065// treated as far away (never suggested).1066fn editDistance(a: []const u8, b: []const u8) usize {1067    const n = b.len;1068    if (a.len == 0) return n;1069    if (n == 0) return a.len;1070    if (n + 1 > 128) return std.math.maxInt(usize);1071    var prev: [128]usize = undefined;1072    var curr: [128]usize = undefined;1073    var j: usize = 0;1074    while (j <= n) : (j += 1) prev[j] = j;1075    var i: usize = 1;1076    while (i <= a.len) : (i += 1) {1077        curr[0] = i;1078        j = 1;1079        while (j <= n) : (j += 1) {1080            const cost: usize = if (std.ascii.toLower(a[i - 1]) == std.ascii.toLower(b[j - 1])) 0 else 1;1081            curr[j] = @min(prev[j] + 1, @min(curr[j - 1] + 1, prev[j - 1] + cost));1082        }1083        @memcpy(prev[0 .. n + 1], curr[0 .. n + 1]);1084    }1085    return prev[n];1086}10871088test "editDistance is case-insensitive Levenshtein" {1089    try std.testing.expectEqual(@as(usize, 1), editDistance("firefux", "firefox"));1090    try std.testing.expectEqual(@as(usize, 0), editDistance("git", "GIT"));1091    try std.testing.expectEqual(@as(usize, 2), editDistance("fierfox", "firefox"));1092    try std.testing.expectEqual(@as(usize, 7), editDistance("", "firefox"));1093}10941095// Prompt for the install method (profile / system / try) and dispatch. Shared by1096// `nina install <pkg>` and the search widget's Enter-to-select — the letter keys1097// are read here, after the search widget's raw mode is gone, so they don't1098// collide with typing a query.1099fn selectAndInstall(ctx: Ctx, npkg: types.NixPackage) !void {1100    output.installSelectPrompt(npkg.pname, npkg.version);11011102    var choice_buf: [8]u8 = undefined;1103    var choice_len: usize = 0;1104    while (choice_len < choice_buf.len) {1105        const n = std.posix.read(std.posix.STDIN_FILENO, choice_buf[choice_len .. choice_len + 1]) catch break;1106        if (n == 0) break;1107        if (choice_buf[choice_len] == '\n') break;1108        choice_len += 1;1109    }1110    const choice = std.mem.trim(u8, choice_buf[0..choice_len], " \t");11111112    if (choice.len == 0 or choice[0] == 'i' or choice[0] == 'I') {1113        try profileInstallPkg(ctx, npkg);1114    } else if (choice[0] == 's' or choice[0] == 'S') {1115        try systemInstallPkg(ctx, npkg);1116    } else if (choice[0] == 't' or choice[0] == 'T') {1117        try tryPkg(ctx, npkg);1118    }1119}11201121fn profileInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {1122    output.installStart(npkg.pname, .profile);1123    if (npkg.unfree) {1124        output.printSubstep("NIXPKGS_ALLOW_UNFREE=1 nix profile add --impure nixpkgs#{s}", .{npkg.attr});1125        output.printTeach(try std.fmt.allocPrint(ctx.gpa, "NIXPKGS_ALLOW_UNFREE=1 nix profile add --impure nixpkgs#{s}", .{npkg.attr}));1126    } else {1127        output.printSubstep("nix profile add nixpkgs#{s}", .{npkg.attr});1128        output.printTeach(try std.fmt.allocPrint(ctx.gpa, "nix profile add nixpkgs#{s}", .{npkg.attr}));1129    }1130    const code = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, ctx.environ, npkg.attr, npkg.unfree);1131    if (code != 0) return error.ProcessFailed;1132    output.installDone(npkg.pname);1133}11341135fn systemInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {1136    const config_path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});1137    defer ctx.gpa.free(config_path);1138    const line = api.findSystemPackagesLine(ctx.io, config_path) orelse 1;1139    output.installEditorPrompt(npkg.pname, config_path, line, ctx.cfg.editor);1140    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, config_path, line);1141    if (ctx.cfg.confirm) {1142        if (output.confirm("apply now? ")) {1143            try apply(ctx);1144        }1145    }1146}11471148fn tryPkg(ctx: Ctx, npkg: types.NixPackage) !void {1149    output.tryStart(npkg.pname);1150    output.printSubstep("nix shell nixpkgs#{s}", .{npkg.attr});1151    output.tryExitHint();1152    _ = try exec.nixShellPs1(ctx.io, &ctx.machine, ctx.gpa, npkg.attr, ctx.environ);1153    output.tryDone();1154}11551156pub fn remove(ctx: Ctx) !void {1157    const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1158    output.removeStart(pkg_name);1159    const code = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, pkg_name);1160    if (code != 0) return error.ProcessFailed;1161    output.done();1162}11631164pub fn list(ctx: Ctx) !void {1165    output.listHeader(ctx.machine.name);11661167    // Profile packages: parse `nix profile list --json` into clean name+version1168    // rows instead of dumping nix's verbose multi-line "Name:/Flake attribute:"1169    // blocks.1170    if (exec.profileListJson(ctx.gpa, ctx.io, &ctx.machine) catch null) |json| {1171        defer ctx.gpa.free(json);1172        output.listSection("profile");1173        renderProfileJson(ctx.gpa, json);1174    }11751176    // System packages: the references of /run/current-system/sw, each a1177    // <hash>-<name>-<version> store path.1178    if (exec.systemPackagePaths(ctx.gpa, ctx.io, &ctx.machine) catch null) |paths| {1179        defer ctx.gpa.free(paths);1180        output.blankLine();1181        output.listSection("system");1182        var lines = std.mem.splitScalar(u8, paths, '\n');1183        while (lines.next()) |line| {1184            const t = std.mem.trim(u8, line, " \t\r");1185            if (t.len == 0) continue;1186            const row = pkgFromStorePath(t);1187            // Skip support paths with no parseable version (man pages, wrappers).1188            if (row.version.len == 0) continue;1189            output.listPkg(row.name, row.version);1190        }1191    }1192}11931194const PkgRow = struct { name: []const u8, version: []const u8 };11951196// Split a nix store path basename (<hash>-<name>-<version>) into name + version.1197// Version begins at the first '-' followed by a digit, which reliably lands on1198// the name/version boundary since the 32-char hash and package names start with1199// non-digits.1200fn pkgFromStorePath(path: []const u8) PkgRow {1201    const base = std.fs.path.basename(path);1202    const after_hash = if (base.len > 33 and base[32] == '-') base[33..] else base;1203    var i: usize = 0;1204    while (i + 1 < after_hash.len) : (i += 1) {1205        if (after_hash[i] == '-' and std.ascii.isDigit(after_hash[i + 1])) {1206            return .{ .name = after_hash[0..i], .version = stripOutputSuffix(after_hash[i + 1 ..]) };1207        }1208    }1209    return .{ .name = after_hash, .version = "" };1210}12111212// Multi-output derivations append the output name to the store path (e.g.1213// curl-8.20.0-bin, less-692-man). Strip that suffix so the version column reads1214// as just the version.1215fn stripOutputSuffix(ver: []const u8) []const u8 {1216    const suffixes = [_][]const u8{ "-bin", "-man", "-dev", "-doc", "-lib", "-info", "-out", "-static", "-devdoc" };1217    for (suffixes) |s| {1218        if (std.mem.endsWith(u8, ver, s)) return ver[0 .. ver.len - s.len];1219    }1220    return ver;1221}12221223test "pkgFromStorePath splits name and version at first dash-digit" {1224    const a = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-ripgrep-15.1.0");1225    try std.testing.expectEqualStrings("ripgrep", a.name);1226    try std.testing.expectEqualStrings("15.1.0", a.version);12271228    const b = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-helix-25.01");1229    try std.testing.expectEqualStrings("helix", b.name);1230    try std.testing.expectEqualStrings("25.01", b.version);12311232    // multi-output store paths drop their output-name suffix1233    const c = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-curl-8.20.0-bin");1234    try std.testing.expectEqualStrings("curl", c.name);1235    try std.testing.expectEqualStrings("8.20.0", c.version);1236}12371238fn firstStorePath(el: std.json.Value) ?[]const u8 {1239    if (el != .object) return null;1240    const sp = el.object.get("storePaths") orelse return null;1241    if (sp != .array or sp.array.items.len == 0) return null;1242    const first = sp.array.items[0];1243    return if (first == .string) first.string else null;1244}12451246// `nix profile list --json` has two shapes across nix versions: newer keys each1247// element by name (object), older lists them positionally (array). Handle both.1248fn renderProfileJson(gpa: std.mem.Allocator, json: []const u8) void {1249    const parsed = std.json.parseFromSlice(std.json.Value, gpa, json, .{}) catch return;1250    defer parsed.deinit();1251    if (parsed.value != .object) return;1252    const elements = parsed.value.object.get("elements") orelse return;1253    switch (elements) {1254        .object => |obj| {1255            var it = obj.iterator();1256            while (it.next()) |entry| {1257                const ver = if (firstStorePath(entry.value_ptr.*)) |p| pkgFromStorePath(p).version else "";1258                output.listPkg(entry.key_ptr.*, ver);1259            }1260        },1261        .array => |arr| {1262            for (arr.items) |el| {1263                const path = firstStorePath(el) orelse continue;1264                const row = pkgFromStorePath(path);1265                output.listPkg(row.name, row.version);1266            }1267        },1268        else => {},1269    }1270}12711272pub fn tryCmd(ctx: Ctx) !void {1273    const pkg_name_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1274    const shell_pkg = types.NixPackage{ .attr = pkg_name_arg, .pname = pkg_name_arg, .version = "", .description = "" };1275    try tryPkg(ctx, shell_pkg);1276}12771278// --- Home Manager commands ---12791280const home_help = [_][2][]const u8{1281    .{ "init", "set up home manager for the first time" },1282    .{ "init --switch", "set up and activate immediately" },1283    .{ "apply", "apply home-manager configuration" },1284    .{ "apply --dry", "preview changes without activating" },1285    .{ "back", "roll back one generation" },1286    .{ "history", "list all generations" },1287    .{ "edit", "open home.nix" },1288    .{ "check", "validate without applying" },1289    .{ "diff", "compare the latest two generations" },1290    .{ "packages", "list managed packages" },1291};12921293const HomeGen = struct {1294    number: u32,1295    date: []const u8,1296    time: []const u8,1297    path: []const u8,1298};12991300// `home-manager generations` lines read:1301//   2026-06-01 11:56 : id 765 -> /nix/store/<hash>-home-manager-generation1302// Newest first, so index 0 is the current generation.1303fn parseHomeGenerations(gpa: std.mem.Allocator, out_str: []const u8) ![]HomeGen {1304    var gens: std.ArrayList(HomeGen) = .empty;1305    var lines = std.mem.splitScalar(u8, out_str, '\n');1306    while (lines.next()) |line| {1307        const t = std.mem.trim(u8, line, " \t\r");1308        if (t.len == 0) continue;1309        var it = std.mem.tokenizeAny(u8, t, " \t");1310        const date = it.next() orelse continue;1311        const time = it.next() orelse continue;1312        var number: ?u32 = null;1313        var path: []const u8 = "";1314        while (it.next()) |tok| {1315            if (std.mem.eql(u8, tok, "id")) {1316                if (it.next()) |n| number = std.fmt.parseInt(u32, n, 10) catch null;1317            } else if (std.mem.startsWith(u8, tok, "/nix/store/")) {1318                path = tok;1319            }1320        }1321        const num = number orelse continue;1322        try gens.append(gpa, .{1323            .number = num,1324            .date = try gpa.dupe(u8, date),1325            .time = try gpa.dupe(u8, time),1326            .path = try gpa.dupe(u8, path),1327        });1328    }1329    return gens.toOwnedSlice(gpa);1330}13311332fn freeHomeGens(gpa: std.mem.Allocator, gens: []HomeGen) void {1333    for (gens) |g| {1334        gpa.free(g.date);1335        gpa.free(g.time);1336        gpa.free(g.path);1337    }1338    gpa.free(gens);1339}13401341test "parseHomeGenerations reads id, date and store path" {1342    const a = std.testing.allocator;1343    const sample =1344        \\2026-06-01 11:56 : id 765 -> /nix/store/aaaa-home-manager-generation1345        \\2026-05-31 10:29 : id 764 -> /nix/store/bbbb-home-manager-generation1346    ;1347    const gens = try parseHomeGenerations(a, sample);1348    defer freeHomeGens(a, gens);1349    try std.testing.expectEqual(@as(usize, 2), gens.len);1350    try std.testing.expectEqual(@as(u32, 765), gens[0].number);1351    try std.testing.expectEqualStrings("2026-06-01", gens[0].date);1352    try std.testing.expectEqualStrings("11:56", gens[0].time);1353    try std.testing.expectEqualStrings("/nix/store/aaaa-home-manager-generation", gens[0].path);1354    try std.testing.expectEqual(@as(u32, 764), gens[1].number);1355}13561357// Current (newest) home generation number, or 0 if unavailable.1358fn homeCurrentGen(ctx: Ctx) u32 {1359    const out = exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine) catch return 0;1360    defer ctx.gpa.free(out);1361    const gens = parseHomeGenerations(ctx.gpa, out) catch return 0;1362    defer freeHomeGens(ctx.gpa, gens);1363    return if (gens.len > 0) gens[0].number else 0;1364}13651366pub fn home(ctx: Ctx) !void {1367    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help"))1368        return output.subcommandHelp("home", &home_help, null);13691370    // Home Manager manages the local user's environment. Detection (which binary,1371    // ~/.config/home-manager, $HOME/$USER for the flake ref) all read the LOCAL1372    // host, while exec routes over SSH for a remote machine — so `home --on1373    // <remote>` would decide mode/flake-ref from the wrong box. Refuse it cleanly1374    // rather than acting on a mismatch.1375    if (!ctx.machine.local) {1376        output.homeLocalOnly(ctx.machine.name);1377        return;1378    }13791380    // init runs before mode detection: its whole purpose is bootstrapping a host1381    // that has no home-manager yet, so a .none mode must not short-circuit it.1382    if (std.mem.eql(u8, ctx.sub, "init")) return homeInitCmd(ctx);13831384    const mode = exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ);1385    if (mode == .none) {1386        output.homeNotInstalled();1387        return;1388    }13891390    // apply is the only command meaningful in module mode (it redirects to1391    // `nina apply`); everything else needs the standalone home-manager CLI.1392    if (std.mem.eql(u8, ctx.sub, "apply")) return homeApply(ctx, mode);1393    // edit just opens the local home.nix — fine in module mode too.1394    if (std.mem.eql(u8, ctx.sub, "edit")) return homeEdit(ctx);13951396    if (mode == .module) {1397        output.homeModuleManaged();1398        return;1399    }14001401    if (std.mem.eql(u8, ctx.sub, "back")) return homeBack(ctx);1402    if (std.mem.eql(u8, ctx.sub, "history")) return homeHistory(ctx);1403    if (std.mem.eql(u8, ctx.sub, "check")) return homeCheck(ctx);1404    if (std.mem.eql(u8, ctx.sub, "diff")) return homeDiff(ctx);1405    if (std.mem.eql(u8, ctx.sub, "packages")) return homePackages(ctx);14061407    return output.subcommandHelp("home", &home_help, null);1408}14091410fn homePackages(ctx: Ctx) !void {1411    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1412    defer ctx.gpa.free(out);1413    const gens = try parseHomeGenerations(ctx.gpa, out);1414    defer freeHomeGens(ctx.gpa, gens);14151416    output.homePackagesHeader(ctx.machine.name);1417    if (gens.len == 0 or gens[0].path.len == 0) return;14181419    // The generation's OWN references are home-manager's activation deps1420    // (bash, coreutils, ...), not what the user installed. The user's packages1421    // live one level down, in the `…-home-manager-path` env the generation1422    // references — descend into it and list ITS references. Fall back to the1423    // generation refs if that env isn't present (older home-manager layouts).1424    const gen_refs = exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, gens[0].path) catch return;1425    defer ctx.gpa.free(gen_refs);14261427    var refs = gen_refs;1428    var env_refs: ?[]u8 = null;1429    defer if (env_refs) |e| ctx.gpa.free(e);1430    if (findHomeManagerPath(gen_refs)) |pkg_path| {1431        if (exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, pkg_path)) |e| {1432            env_refs = e;1433            refs = e;1434        } else |_| {}1435    }14361437    // Dedup by name: multi-output derivations (jq, jq-lib, jq-doc) collapse to1438    // the same name after the output suffix is stripped. Keys are slices into1439    // `refs`, valid for this function's lifetime.1440    var seen = std.StringHashMap(void).init(ctx.gpa);1441    defer seen.deinit();1442    var lines = std.mem.splitScalar(u8, refs, '\n');1443    while (lines.next()) |line| {1444        const t = std.mem.trim(u8, line, " \t\r");1445        if (t.len == 0) continue;1446        const row = pkgFromStorePath(t);1447        if (row.version.len == 0) continue;1448        if (std.mem.indexOf(u8, row.name, "home-manager") != null) continue;1449        if (seen.contains(row.name)) continue;1450        seen.put(row.name, {}) catch {};1451        output.listPkg(row.name, row.version);1452    }1453}14541455// The `…-home-manager-path` env among a generation's references — the buildEnv1456// of the user's home.packages. Returns the full store-path line, or null.1457fn findHomeManagerPath(refs: []const u8) ?[]const u8 {1458    var lines = std.mem.splitScalar(u8, refs, '\n');1459    while (lines.next()) |line| {1460        const t = std.mem.trim(u8, line, " \t\r");1461        if (std.mem.indexOf(u8, t, "home-manager-path") != null) return t;1462    }1463    return null;1464}14651466test "findHomeManagerPath picks the env, not the generation or infra" {1467    const refs =1468        \\/nix/store/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-bash-5.31469        \\/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path1470        \\/nix/store/cccccccccccccccccccccccccccccccc-coreutils-9.111471    ;1472    try std.testing.expectEqualStrings(1473        "/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path",1474        findHomeManagerPath(refs).?,1475    );1476    try std.testing.expectEqual(@as(?[]const u8, null), findHomeManagerPath("/nix/store/x-bash-5.3\n"));1477}14781479fn homeDiff(ctx: Ctx) !void {1480    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1481    defer ctx.gpa.free(out);1482    const gens = try parseHomeGenerations(ctx.gpa, out);1483    defer freeHomeGens(ctx.gpa, gens);14841485    // Need two generations and both their store paths to diff their closures.1486    if (gens.len < 2 or gens[0].path.len == 0 or gens[1].path.len == 0) {1487        output.homeNothingToDiff();1488        return;1489    }1490    const newer = gens[0];1491    const older = gens[1];1492    output.homeDiffHeader(older.number, newer.number, ctx.machine.name);1493    if (try exec.diffClosuresPaths(ctx.io, &ctx.machine, ctx.gpa, older.path, newer.path) != 0)1494        return error.ProcessFailed;1495}14961497fn homeCheck(ctx: Ctx) !void {1498    output.homeCheckStart(ctx.machine.name);1499    const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa, ctx.passthrough);1500    if (code != 0) return error.BuildFailed;1501    output.homeCheckOk();1502}15031504fn homeEdit(ctx: Ctx) !void {1505    // Standalone home config lives at ~/.config/home-manager/home.nix; the same1506    // path is what detection keys on for module mode, so it resolves for both.1507    const path = exec.homeNixPath(ctx.gpa, ctx.environ) orelse {1508        errors.error_info.setMessage("could not resolve ~/.config/home-manager/home.nix", .{});1509        return error.ConfigNotFound;1510    };1511    defer ctx.gpa.free(path);1512    output.homeEditOpen(path, ctx.cfg.editor);1513    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);1514}15151516fn homeHistory(ctx: Ctx) !void {1517    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1518    defer ctx.gpa.free(out);1519    const gens = try parseHomeGenerations(ctx.gpa, out);1520    defer freeHomeGens(ctx.gpa, gens);1521    output.homeHistoryHeader(ctx.machine.name);1522    // Newest-first from home-manager; the first row is the current generation.1523    for (gens, 0..) |g, i| output.homeHistoryRow(g.number, g.date, g.time, i == 0);1524}15251526fn homeBack(ctx: Ctx) !void {1527    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1528    defer ctx.gpa.free(out);1529    const gens = try parseHomeGenerations(ctx.gpa, out);1530    defer freeHomeGens(ctx.gpa, gens);15311532    // Newest-first: [0] is current, [1] is the generation to roll back to.1533    if (gens.len < 2) {1534        output.alreadyOldest();1535        return;1536    }1537    const current = gens[0].number;1538    const prev = gens[1].number;15391540    output.homeBackStart(ctx.machine.name, current, prev);1541    if (ctx.cfg.confirm and !output.confirm("")) return;1542    const code = try exec.homeManagerRollback(ctx.io, &ctx.machine, ctx.gpa);1543    if (code != 0) return error.BuildFailed;1544    output.homeBackDone(prev);1545}15461547fn homeInitCmd(ctx: Ctx) !void {1548    var switch_on_init = false;1549    var dir: ?[]const u8 = null;1550    for (ctx.args) |arg| {1551        if (std.mem.eql(u8, arg, "--switch")) {1552            switch_on_init = true;1553        } else if (!std.mem.startsWith(u8, arg, "-")) {1554            dir = arg;1555        }1556    }15571558    // Guard only the default location — a custom dir is the user's call, and1559    // home-manager creates it. Never clobber an existing ~/.config/home-manager.1560    if (dir == null) {1561        if (exec.homeNixPath(ctx.gpa, ctx.environ)) |path| {1562            defer ctx.gpa.free(path);1563            if (exec.pathExists(ctx.io, path)) {1564                output.homeInitExists(path);1565                return;1566            }1567        }1568    }15691570    output.homeInitStart(switch_on_init, dir);1571    const code = try exec.homeManagerInit(ctx.io, &ctx.machine, ctx.gpa, switch_on_init, dir);1572    if (code != 0) return error.BuildFailed;1573    output.homeInitDone(switch_on_init);1574}15751576fn homeApply(ctx: Ctx, mode: exec.HomeManagerMode) !void {1577    // NixOS/flake module: home config is rebuilt by nixos-rebuild — redirect.1578    if (mode == .module) {1579        output.homeModuleManaged();1580        return;1581    }1582    if (ctx.dry) {1583        output.homeApplyDry(ctx.machine.name);1584        const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa, ctx.passthrough);1585        if (code != 0) return error.BuildFailed;1586        output.homeApplyDryDone();1587        return;1588    }15891590    if (!try runPreHook(ctx, "pre-home")) {1591        output.aborted();1592        return error.HookAborted;1593    }15941595    output.homeApplyStart(ctx.machine.name);15961597    // Flake-based home config: switch by attribute with a graceful fallback1598    // chain. A channel-based config (no flake.nix) uses a plain switch.1599    const dir = exec.homeFlakeDir(ctx.gpa, ctx.io, ctx.environ);1600    defer if (dir) |d| ctx.gpa.free(d);1601    if (dir) |d| return homeApplyFlake(ctx, d);16021603    output.printSubstep("home-manager switch", .{});1604    const start = std.Io.Clock.awake.now(ctx.io);1605    const code = try exec.homeManagerSwitch(ctx.io, &ctx.machine, ctx.gpa, ctx.passthrough);1606    if (code != 0) return error.BuildFailed;16071608    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());1609    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));1610    output.homeApplyDone(homeCurrentGen(ctx), elapsed);1611    runPostHook(ctx, "post-home");1612}16131614// Switch a flake-based home config, trying the most specific attribute first:1615//   <dir>#<user>-<arch>-<os>  →  <dir>#<user>  →  <dir>  (home-manager resolves)1616// Each fallback fires only on a missing-attribute error, never on a real build1617// failure. Mirrors how ${USER}-${system} homeConfigurations keys are written.1618fn homeApplyFlake(ctx: Ctx, dir: []const u8) !void {1619    const user = ctx.environ.get("USER") orelse "default";16201621    var refs: std.ArrayList([]const u8) = .empty;1622    defer {1623        for (refs.items) |r| ctx.gpa.free(r);1624        refs.deinit(ctx.gpa);1625    }1626    if (exec.homeManagerAttr(ctx.gpa, ctx.io, &ctx.machine, ctx.environ) catch null) |attr| {1627        defer ctx.gpa.free(attr);1628        try refs.append(ctx.gpa, try std.fmt.allocPrint(ctx.gpa, "{s}#{s}", .{ dir, attr }));1629    }1630    try refs.append(ctx.gpa, try std.fmt.allocPrint(ctx.gpa, "{s}#{s}", .{ dir, user }));1631    try refs.append(ctx.gpa, try ctx.gpa.dupe(u8, dir));16321633    const start = std.Io.Clock.awake.now(ctx.io);1634    for (refs.items, 0..) |ref, i| {1635        output.printSubstep("home-manager switch --flake {s}", .{ref});1636        switch (try exec.homeManagerSwitchFlake(ctx.io, &ctx.machine, ctx.gpa, ref, ctx.passthrough)) {1637            .ok => {1638                const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());1639                const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));1640                output.homeApplyDone(homeCurrentGen(ctx), elapsed);1641                runPostHook(ctx, "post-home");1642                return;1643            },1644            // Attr not defined by the flake — drop to the next candidate.1645            .attr_missing => {1646                if (i + 1 < refs.items.len) output.homeAttrFallback(ref);1647                continue;1648            },1649            .failed => return error.BuildFailed,1650        }1651    }1652    return error.BuildFailed;1653}16541655// --- Service commands ---16561657const service_help = [_][2][]const u8{1658    .{ "list", "list running services" },1659    .{ "logs <svc>", "show service logs" },1660    .{ "status <svc>", "service status" },1661    .{ "start <svc>", "start a service" },1662    .{ "stop <svc>", "stop a service" },1663    .{ "restart <svc>", "restart a service" },1664    .{ "enable <svc>", "enable at boot" },1665    .{ "disable <svc>", "disable at boot" },1666};16671668pub fn service(ctx: Ctx) !void {1669    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");1670    if (std.mem.eql(u8, ctx.sub, "list")) {1671        output.serviceListHeader(ctx.machine.name);1672        const svcs = exec.serviceList(ctx.gpa, ctx.io, &ctx.machine, ctx.user) catch &.{};1673        defer ctx.gpa.free(svcs);1674        for (svcs) |s| output.serviceRow(s);1675        return;1676    }1677    if (std.mem.eql(u8, ctx.sub, "logs")) {1678        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1679        const follow = ctx.args.len > 1 and std.mem.eql(u8, ctx.args[1], "-f");1680        output.serviceLogsHeader(name, ctx.last, ctx.machine.name);1681        _ = try exec.serviceLogs(ctx.io, &ctx.machine, ctx.gpa, name, ctx.last, follow, ctx.user);1682        return;1683    }1684    if (std.mem.eql(u8, ctx.sub, "status")) {1685        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1686        output.serviceVerb("status", name, ctx.machine.name);1687        _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, "status", name, ctx.user);1688        return;1689    }1690    // start/stop/restart/enable/disable1691    const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1692    if (ctx.cfg.confirm and (std.mem.eql(u8, ctx.sub, "stop") or std.mem.eql(u8, ctx.sub, "disable"))) {1693        if (!output.confirm("")) return;1694    }1695    output.serviceVerb(ctx.sub, name, ctx.machine.name);1696    _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, ctx.sub, name, ctx.user);1697    output.serviceDone();1698}16991700// --- Flake commands ---17011702const flake_help = [_][2][]const u8{1703    .{ "init", "create a new flake.nix" },1704    .{ "update", "update flake inputs" },1705    .{ "update <in>", "update a specific input" },1706    .{ "check", "validate the flake" },1707    .{ "show", "inspect flake outputs" },1708    .{ "lock", "regenerate flake.lock" },1709    .{ "clone <url>", "clone a flake repository" },1710};17111712pub fn flake(ctx: Ctx) !void {1713    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("flake", &flake_help, null);1714    if (std.mem.eql(u8, ctx.sub, "update")) {1715        output.flakeUpdateStart();1716        const input: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1717        _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input, ctx.passthrough);1718        output.flakeLockWritten();1719        return;1720    }1721    if (std.mem.eql(u8, ctx.sub, "check")) {1722        output.flakeCheckStart();1723        const code = try exec.flakeCheck(ctx.io, &ctx.machine, ctx.gpa, ctx.passthrough);1724        if (code != 0) {1725            output.checkFailed("");1726            return error.CheckFailed;1727        }1728        output.flakeValid();1729        return;1730    }1731    if (std.mem.eql(u8, ctx.sub, "show")) {1732        const json_out = exec.flakeShow(ctx.gpa, ctx.io, &ctx.machine) catch null;1733        if (json_out) |j| {1734            defer ctx.gpa.free(j);1735            output.flakeShowHeader("flake outputs");1736            // Parse and display the flake outputs1737            const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, j, .{}) catch return;1738            defer parsed.deinit();1739            if (parsed.value == .object) {1740                var it = parsed.value.object.iterator();1741                while (it.next()) |entry| {1742                    if (entry.value_ptr.* == .object) {1743                        var inner = entry.value_ptr.object.iterator();1744                        while (inner.next()) |e2| {1745                            const desc = if (e2.value_ptr.* == .object)1746                                if (e2.value_ptr.object.get("description")) |d|1747                                    if (d == .string) d.string else ""1748                                else1749                                    ""1750                            else1751                                "";1752                            output.flakeShowEntry(entry.key_ptr.*, e2.key_ptr.*, desc);1753                        }1754                    }1755                }1756            }1757        }1758        return;1759    }1760    if (std.mem.eql(u8, ctx.sub, "init")) {1761        _ = try exec.flakeInit(ctx.io, &ctx.machine, ctx.gpa);1762        return;1763    }1764    if (std.mem.eql(u8, ctx.sub, "lock")) {1765        _ = try exec.flakeLock(ctx.io, &ctx.machine, ctx.gpa);1766        return;1767    }1768    if (std.mem.eql(u8, ctx.sub, "clone")) {1769        const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1770        _ = try exec.flakeClone(ctx.io, &ctx.machine, ctx.gpa, url);1771        return;1772    }1773}17741775// --- Store commands ---17761777const store_help = [_][2][]const u8{1778    .{ "info", "store size and counts" },1779    .{ "path <attr>", "store path of a package" },1780    .{ "gc", "collect garbage" },1781    .{ "optimise", "deduplicate store paths with hard links" },1782    .{ "verify", "verify store integrity" },1783    .{ "repair", "repair corrupted paths" },1784};17851786pub fn store(ctx: Ctx) !void {1787    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("store", &store_help, null);1788    if (std.mem.eql(u8, ctx.sub, "gc")) {1789        _ = try exec.storeGc(ctx.io, &ctx.machine, ctx.gpa);1790        return;1791    }1792    // Accept both spellings — optimise (en) and optimize (us).1793    if (std.mem.eql(u8, ctx.sub, "optimise") or std.mem.eql(u8, ctx.sub, "optimize")) {1794        output.storeOptimiseStart(ctx.machine.name);1795        _ = try exec.storeOptimise(ctx.io, &ctx.machine, ctx.gpa);1796        output.storeOptimiseDone();1797        return;1798    }1799    if (std.mem.eql(u8, ctx.sub, "verify")) {1800        output.storeVerifyStart();1801        _ = try exec.storeVerify(ctx.io, &ctx.machine, ctx.gpa);1802        return;1803    }1804    if (std.mem.eql(u8, ctx.sub, "repair")) {1805        if (ctx.cfg.confirm and !output.confirm("")) return;1806        output.storeRepairStart();1807        _ = try exec.storeRepair(ctx.io, &ctx.machine, ctx.gpa);1808        return;1809    }1810    if (std.mem.eql(u8, ctx.sub, "info")) {1811        const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1812        output.storeInfo(si);1813        return;1814    }1815    if (std.mem.eql(u8, ctx.sub, "path")) {1816        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1817        const path = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, attr);1818        defer ctx.gpa.free(path);1819        output.storePath(path);1820        return;1821    }1822    // default: info1823    const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1824    output.storeInfo(si);1825}18261827// --- Channel commands ---18281829const channel_help = [_][2][]const u8{1830    .{ "list", "list channels" },1831    .{ "add <url> [name]", "add a channel" },1832    .{ "remove <name>", "remove a channel" },1833    .{ "update", "update all channels" },1834};18351836pub fn channel(ctx: Ctx) !void {1837    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("channel", &channel_help, null);1838    // On a flake-managed system, nix-channel operations generally don't apply.1839    if (flakeSystem(ctx)) output.flakeChannelNote();1840    if (std.mem.eql(u8, ctx.sub, "list")) {1841        output.channelListHeader(ctx.machine.name);1842        const chans = try exec.channelList(ctx.gpa, ctx.io, &ctx.machine);1843        defer ctx.gpa.free(chans);1844        for (chans) |ch| output.channelRow(ch);1845        return;1846    }1847    if (std.mem.eql(u8, ctx.sub, "add")) {1848        const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1849        const name = if (ctx.args.len > 1) ctx.args[1] else "";1850        _ = try exec.channelAdd(ctx.io, &ctx.machine, ctx.gpa, url, name);1851        output.channelDone();1852        return;1853    }1854    if (std.mem.eql(u8, ctx.sub, "remove")) {1855        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1856        _ = try exec.channelRemove(ctx.io, &ctx.machine, ctx.gpa, name);1857        output.channelDone();1858        return;1859    }1860    if (std.mem.eql(u8, ctx.sub, "update")) {1861        return channelUpdateCmd(ctx);1862    }1863}18641865// --- Profile commands ---18661867pub fn profile(ctx: Ctx) !void {1868    if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {1869        output.profileListHeader();1870        const out = exec.profileList(ctx.gpa, ctx.io, &ctx.machine) catch null;1871        if (out) |o| {1872            defer ctx.gpa.free(o);1873            var lines = std.mem.splitScalar(u8, o, '\n');1874            while (lines.next()) |line| {1875                const t = std.mem.trim(u8, line, " \t\r");1876                if (t.len == 0) continue;1877                output.profileRow(t, "", "");1878            }1879        }1880        return;1881    }1882    if (std.mem.eql(u8, ctx.sub, "install")) {1883        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1884        _ = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, ctx.environ, attr, false);1885        output.done();1886        return;1887    }1888    if (std.mem.eql(u8, ctx.sub, "remove")) {1889        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1890        _ = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, attr);1891        output.done();1892        return;1893    }1894    if (std.mem.eql(u8, ctx.sub, "upgrade")) {1895        _ = try exec.profileUpgrade(ctx.io, &ctx.machine, ctx.gpa);1896        output.done();1897        return;1898    }1899}19001901// --- Pkg commands ---19021903const pkg_help = [_][2][]const u8{1904    .{ "why <pkg>", "what pulled it in" },1905    .{ "deps <pkg>", "direct dependencies" },1906    .{ "size <pkg>", "closure size" },1907    .{ "path <pkg>", "store path" },1908    .{ "closure <pkg>", "full closure" },1909};19101911pub fn pkg(ctx: Ctx) !void {1912    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("pkg", &pkg_help, null);1913    const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1914    if (std.mem.eql(u8, ctx.sub, "why")) {1915        if (try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1916        return;1917    }1918    if (std.mem.eql(u8, ctx.sub, "deps")) {1919        if (try exec.pkgDeps(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1920        return;1921    }1922    if (std.mem.eql(u8, ctx.sub, "size")) {1923        const s = try exec.pkgSize(ctx.gpa, ctx.io, &ctx.machine, name);1924        defer ctx.gpa.free(s);1925        output.pkgResult("size", s);1926        return;1927    }1928    if (std.mem.eql(u8, ctx.sub, "path")) {1929        const p = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, name);1930        defer ctx.gpa.free(p);1931        output.pkgResult("path", p);1932        return;1933    }1934    if (std.mem.eql(u8, ctx.sub, "closure")) {1935        if (try exec.pkgClosure(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1936        return;1937    }1938}19391940// Top-level alias for `nina pkg why <pkg>` — surfaces what pulled a package in1941// without the user needing to know about the `pkg` subgroup.1942pub fn why(ctx: Ctx) !void {1943    const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1944    if (try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1945}19461947// --- Pin / Unpin ---19481949pub fn pin(ctx: Ctx) !void {1950    const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1951    const commit = if (ctx.args.len > 1) ctx.args[1] else return error.Internal;1952    exec.editFlakeLock(ctx.gpa, input, commit) catch return error.ProcessFailed;1953    output.pinDone(input, commit);1954}19551956pub fn unpin(ctx: Ctx) !void {1957    const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1958    _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input, &.{});1959    output.unpinDone(input);1960}19611962// --- Hash / Fetch ---19631964pub fn hash(ctx: Ctx) !void {1965    const path = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1966    const h = try exec.nixHash(ctx.gpa, ctx.io, &ctx.machine, path);1967    defer ctx.gpa.free(h);1968    output.hashResult(std.mem.trim(u8, h, " \t\n\r"));1969}19701971pub fn fetch(ctx: Ctx) !void {1972    const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1973    const h = try exec.nixFetch(ctx.gpa, ctx.io, &ctx.machine, url);1974    defer ctx.gpa.free(h);1975    output.fetchResult(std.mem.trim(u8, h, " \t\n\r"), url);1976}19771978// --- Build / Run ---19791980pub fn build(ctx: Ctx) !void {1981    const attr: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1982    output.buildStart(attr orelse "default");1983    const code = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, attr, ctx.passthrough);1984    if (code != 0) return error.BuildFailed;1985    output.buildDone();1986}19871988pub fn runCmd(ctx: Ctx) !void {1989    const pkg_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1990    output.runStart(pkg_arg);1991    _ = try exec.nixRun(ctx.io, &ctx.machine, ctx.gpa, pkg_arg, ctx.passthrough);1992}19931994// --- Hello ---19951996pub fn hello(ctx: Ctx) !void {1997    output.hello(ctx.cfg.machines);1998}19992000const ConfigKind = enum { flake, channel, none };20012002// Scan the conventional /etc/nixos for a flake.nix (flake-based) or a2003// configuration.nix (channel-based) to pre-fill the wizard's defaults.2004fn scanConfig(io: std.Io) ConfigKind {2005    if (exec.pathExists(io, "/etc/nixos/flake.nix")) return .flake;2006    if (exec.pathExists(io, "/etc/nixos/configuration.nix")) return .channel;2007    return .none;2008}20092010// Runs when the config is absent on first invocation (interactive TTY only).2011// Scans for an existing nixos config, detects flake vs channel, and offers a2012// smart default path — flake-ness is detected, never asked.2013pub fn firstRunWizard(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {2014    output.firstRunBanner();2015    output.firstRunNoConfig();20162017    var name_buf: [256]u8 = undefined;2018    var path_buf: [256]u8 = undefined;20192020    const machine_name = output.firstRunPrompt("machine name", "my-machine", &name_buf);20212022    output.firstRunScanning();2023    const kind = scanConfig(io);2024    switch (kind) {2025        .flake => output.firstRunDetected("/etc/nixos/flake.nix", true),2026        .channel => output.firstRunDetected("/etc/nixos/configuration.nix", false),2027        .none => output.firstRunNoneFound(),2028    }20292030    // Detected systems default to /etc/nixos (press enter to confirm); when2031    // nothing was found, leave the default empty so the user must type a path.2032    const default_path: []const u8 = if (kind == .none) "" else "/etc/nixos";2033    const config_path = output.firstRunPromptDefault("config path", default_path, kind != .none, &path_buf);20342035    // Re-detect at the chosen path in case the user pointed elsewhere — flake.nix2036    // there means a flake system, recorded so channel commands warn appropriately.2037    const use_flakes = exec.dirHasFlake(gpa, io, config_path);20382039    const conf_path = try config.configPath(gpa, environ);2040    defer gpa.free(conf_path);2041    if (std.fs.path.dirname(conf_path)) |dir| exec.ensureDir(gpa, io, dir);20422043    // `flake` is a top-level config field, so it must precede the [machine] block.2044    const flake_line = if (use_flakes) "flake = true\n" else "";2045    var content_buf: [1024]u8 = undefined;2046    const content = try std.fmt.bufPrint(2047        &content_buf,2048        "{s}[machine]\nname = {s}\nconfig = {s}\nlocal = true\n",2049        .{ flake_line, machine_name, config_path },2050    );20512052    const file = std.Io.Dir.createFile(.cwd(), io, conf_path, .{}) catch {2053        errors.error_info.setMessage("could not write {s}", .{conf_path});2054        return error.Internal;2055    };2056    defer file.close(io);2057    file.writePositionalAll(io, content, 0) catch {2058        errors.error_info.setMessage("could not write {s}", .{conf_path});2059        return error.Internal;2060    };20612062    output.firstRunWritten(conf_path);2063}20642065pub fn setup(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {2066    // Create the config first if it doesn't exist. This makes `nina setup`2067    // a complete onboarding command — not just a nix-features check. Any legacy2068    // ~/.nina.conf is migrated to the XDG path before we decide to run the wizard.2069    config.migrateLegacyConfig(gpa, io, environ);2070    if (config.configPath(gpa, environ)) |conf_path| {2071        defer gpa.free(conf_path);2072        if (std.Io.Dir.openFile(.cwd(), io, conf_path, .{})) |f| {2073            f.close(io);2074        } else |_| {2075            try firstRunWizard(gpa, io, environ);2076            errors.error_info.reset();2077        }2078    } else |_| {}20792080    output.setupCheck();2081    const status = exec.checkNixFeatures(gpa, io, environ);2082    output.setupFeatures(status.nix_command, status.flakes);20832084    if (status.allEnabled()) {2085        output.setupAllSet();2086        api.ensureRegistryPinned(gpa, io, environ);2087        return;2088    }20892090    // On NixOS the features belong in configuration.nix (the declarative,2091    // permanent home), not ~/.config/nix/nix.conf. Offer to add the one line;2092    // the user runs the rebuild. We don't pin the registry here because the2093    // features aren't live until that rebuild lands.2094    if (exec.isNixOS(io)) {2095        const conf_path = "/etc/nixos/configuration.nix";2096        if (exec.nixosConfigEnablesFeatures(gpa, io, conf_path)) {2097            output.setupNixosNeedsRebuild(conf_path);2098            return;2099        }2100        output.setupNixosOffer(exec.NIXOS_FEATURES_LINE, conf_path);2101        if (output.confirmDefaultNo("add it now?")) {2102            if (exec.appendFeaturesToNixosConfig(gpa, io, environ, conf_path)) |_| {2103                output.setupNixosWrote(conf_path);2104            } else |_| {2105                output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);2106            }2107        } else {2108            output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);2109        }2110        return;2111    }21122113    // Non-NixOS: a user-level nix.conf takes effect immediately, no sudo needed.2114    output.setupEnabling();2115    const path = try exec.enableNixFeatures(gpa, io, environ);2116    defer gpa.free(path);21172118    output.setupDone(path);2119    api.ensureRegistryPinned(gpa, io, environ);2120}21212122// --- Log helper ---21232124fn logAction(ctx: Ctx, action: []const u8, gen: u32) void {2125    var ts_buf: [32]u8 = undefined;2126    const ts = nowIso(ctx.io, &ts_buf);2127    var buf: [256]u8 = undefined;2128    const entry = std.fmt.bufPrint(&buf, "{{\"ts\":\"{s}\",\"machine\":\"{s}\",\"command\":\"{s}\",\"outcome\":\"success\",\"gen_before\":null,\"gen_after\":{d},\"duration_ms\":0}}\n", .{2129        ts, ctx.machine.name, action, gen,2130    }) catch return;2131    exec.appendNinaLog(ctx.io, ctx.environ, entry);2132}21332134// Wall-clock UTC as ISO-8601. Uses Io.Clock.real (the settable Unix-epoch clock);2135// Io.Clock.awake is monotonic and unsuitable for timestamps. Falls back to epoch 0.2136fn nowIso(io: std.Io, buf: []u8) []const u8 {2137    const fallback = "1970-01-01T00:00:00Z";2138    const ns = std.Io.Clock.real.now(io).toNanoseconds();2139    if (ns <= 0) return fallback;2140    const secs: u64 = @intCast(@divFloor(ns, 1_000_000_000));2141    const es = std.time.epoch.EpochSeconds{ .secs = secs };2142    const ed = es.getEpochDay();2143    const yd = ed.calculateYearDay();2144    const md = yd.calculateMonthDay();2145    const ds = es.getDaySeconds();2146    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", .{2147        yd.year,              md.month.numeric(),      @as(u32, md.day_index) + 1,2148        ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(),2149    }) catch return fallback;2150}