commands.zig

83.8 KB · raw

1// commands.zig — all command handlers2// Orchestrates exec/api/output. Zero direct stdout writes.3const std = @import("std");4const builtin = @import("builtin");5const types = @import("types.zig");6const errors = @import("errors.zig");7const config = @import("config.zig");8const output = @import("output.zig");9const exec = @import("exec.zig");10const api = @import("api.zig");11const search_tui = @import("search.zig");12const version = @import("version.zig");1314const UPDATE_URL = "https://kepr.uk/api/nina/releases/latest";15const FLAKE_URL = "https://kepr.uk/nina/archive/HEAD.tar.gz#nina";1617const Semver = struct {18    major: u32,19    minor: u32,20    patch: u32,21};2223pub const Ctx = struct {24    gpa: std.mem.Allocator,25    io: std.Io,26    environ: *const std.process.Environ.Map,27    machine: types.Machine,28    cfg: types.NinaConfig,29    args: []const []const u8, // positional args after subcommand30    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        // `nix profile upgrade` re-resolves the element's own originalUrl. The427        // archive install runs with --no-write-lock-file, so nix has nowhere to428        // persist the lock it takes at install time except baking it into that429        // originalUrl as a `?narHash=` pin — which then never changes no matter430        // how far kepr's HEAD moves. Upgrading against that pin is a permanent431        // no-op: exit 0, "upgrading from X to X", nothing installed. Remove and432        // re-add against the plain (unpinned) archive URL instead, so nix433        // actually re-resolves HEAD and picks up a fresh narHash.434        const remove_r = exec.capture(ctx.gpa, ctx.io, &ctx.machine, &.{ "nix", "profile", "remove", element }) catch {435            output.updateSelfNixFailed();436            return;437        };438        defer ctx.gpa.free(remove_r.stdout);439        defer ctx.gpa.free(remove_r.stderr);440        if (remove_r.exit_code != 0) {441            output.raw(remove_r.stdout);442            output.raw(remove_r.stderr);443            output.updateSelfNixFailed();444            return;445        }446        // Even against the plain unpinned URL, nix caches its resolution for447        // `tarball-ttl` seconds (default 3600) regardless of HTTP cache-control448        // headers — so within an hour of any prior nix operation touching this449        // URL, add would silently reuse the stale narHash and reinstall the450        // same old version. --refresh forces nix to actually re-check HEAD.451        const add_r = exec.capture(ctx.gpa, ctx.io, &ctx.machine, &.{ "nix", "profile", "add", "--no-write-lock-file", "--refresh", FLAKE_URL }) catch {452            output.updateSelfNixReinstallFailed();453            return;454        };455        defer ctx.gpa.free(add_r.stdout);456        defer ctx.gpa.free(add_r.stderr);457        if (add_r.exit_code != 0) {458            output.raw(add_r.stdout);459            output.raw(add_r.stderr);460            output.updateSelfNixReinstallFailed();461            return;462        }463        output.updateSelfDone(version.VERSION, remote_ver);464        output.updateSelfNixRehash();465        return;466    }467468    const plat_info = blk: {469        const pv = root.object.get("platforms") orelse break :blk null;470        if (pv != .object) break :blk null;471        break :blk pv.object.get(version.PLATFORM);472    };473    if (plat_info == null) {474        output.updateSelfNoPlatform(version.PLATFORM);475        return;476    }477478    const dl_url = blk: {479        const v = plat_info.?.object.get("url") orelse {480            output.printWarning("malformed release metadata");481            return;482        };483        break :blk switch (v) {484            .string => |s| s,485            else => {486                output.printWarning("malformed release metadata");487                return;488            },489        };490    };491492    const raw_cksum = blk: {493        if (plat_info.?.object.get("blake3")) |v|494            break :blk switch (v) {495                .string => |s| s,496                else => {497                    output.printWarning("malformed release metadata");498                    return;499                },500            };501        if (plat_info.?.object.get("checksum")) |v|502            break :blk switch (v) {503                .string => |s| s,504                else => {505                    output.printWarning("malformed release metadata");506                    return;507                },508            };509        output.printWarning("missing checksum in release metadata");510        return;511    };512    const expected_hex = if (std.mem.startsWith(u8, raw_cksum, "blake3:")) raw_cksum["blake3:".len..] else raw_cksum;513514    if (ctx.cfg.confirm and !output.confirm("")) return;515516    output.updateSelfDownloading(remote_ver, version.PLATFORM);517    const tmp_path = exec.downloadToTemp(ctx.gpa, ctx.io, dl_url) catch {518        output.printWarning("download failed — check your connection and try again");519        return;520    };521    defer ctx.gpa.free(tmp_path);522    // Clean up the downloaded temp file whether install succeeds or fails —523    // it's only ever a scratch copy verified against the release checksum.524    defer std.Io.Dir.deleteFileAbsolute(ctx.io, tmp_path) catch {};525526    output.updateSelfVerifying();527    exec.verifyAndInstall(ctx.gpa, ctx.io, tmp_path, expected_hex, install_path) catch |e| switch (e) {528        error.ChecksumMismatch => {529            output.updateSelfChecksumFailed();530            return;531        },532        else => return e,533    };534535    output.updateSelfDone(version.VERSION, remote_ver);536}537538// archives.json covers every version between current and latest; the manifest's539// `notes` field only ever describes the single latest release. Try the full-range540// changelog first so an update spanning several versions doesn't collapse down to541// just the newest one's notes — fall back to `notes` only when the archive has542// nothing (e.g. releases predating archives.json, or the fetch failing).543fn updateReleaseNotes(gpa: std.mem.Allocator, io: std.Io, root: std.json.Value, source_url: []const u8, current: []const u8, latest: []const u8) ![]u8 {544    if (buildKeprArchiveReleaseNotes(gpa, io, source_url, current, latest) catch null) |notes| {545        if (std.mem.trim(u8, notes, " \t\r\n").len > 0) return notes;546        gpa.free(notes);547    }548    if (releaseNotesFromMetadata(gpa, root)) |notes| return notes;549    return gpa.dupe(u8, "");550}551552fn releaseNotesFromMetadata(gpa: std.mem.Allocator, root: std.json.Value) ?[]u8 {553    if (root != .object) return null;554    // `notes` is the one canonical manifest field. The retired `release_notes`555    // and `changelog` fallbacks are gone — Kepr now emits `notes` everywhere, and556    // releases that predate `--notes` fall back to archives.json in the caller.557    const v = root.object.get("notes") orelse return null;558    return switch (v) {559        .string => |s| gpa.dupe(u8, s) catch null,560        else => null,561    };562}563564fn buildKeprArchiveReleaseNotes(gpa: std.mem.Allocator, io: std.Io, source_url: []const u8, current: []const u8, latest: []const u8) ![]u8 {565    const archive_url = try keprArchiveUrl(gpa, source_url);566    defer gpa.free(archive_url);567568    const body = exec.fetchUrl(gpa, io, archive_url) catch return gpa.dupe(u8, "");569    defer gpa.free(body);570571    return releaseNotesFromArchiveJson(gpa, body, current, latest);572}573574fn keprArchiveUrl(gpa: std.mem.Allocator, source_url: []const u8) ![]u8 {575    const scheme = std.mem.indexOf(u8, source_url, "://") orelse return error.InvalidUpdateSource;576    const path_start = std.mem.indexOfScalarPos(u8, source_url, scheme + 3, '/') orelse return error.InvalidUpdateSource;577    const origin = source_url[0..path_start];578    const path = source_url[path_start..];579    if (!std.mem.startsWith(u8, path, "/api/")) return error.InvalidUpdateSource;580581    const after_api = path["/api/".len..];582    const repo_end = std.mem.indexOfScalar(u8, after_api, '/') orelse return error.InvalidUpdateSource;583    const repo = after_api[0..repo_end];584    if (repo.len == 0) return error.InvalidUpdateSource;585586    return std.fmt.allocPrint(gpa, "{s}/{s}/archives.json?limit=100", .{ origin, repo });587}588589// Saves arrive newest-first. For each version in the update range we want the OLDEST590// save message (the one that introduced that version), not a follow-up cleanup/docs save.591// We overwrite the tracked message on each occurrence, so the final stored value per592// version is always the oldest (last-seen in a newest-first stream).593fn releaseNotesFromArchiveJson(gpa: std.mem.Allocator, body: []const u8, current: []const u8, latest: []const u8) ![]u8 {594    const parsed = std.json.parseFromSlice(std.json.Value, gpa, body, .{}) catch return gpa.dupe(u8, "");595    defer parsed.deinit();596597    if (parsed.value != .object) return gpa.dupe(u8, "");598    const saves_v = parsed.value.object.get("saves") orelse return gpa.dupe(u8, "");599    if (saves_v != .array) return gpa.dupe(u8, "");600601    // version string → oldest message seen (both slice into parsed JSON, valid until deinit)602    var best_msg = std.StringHashMap([]const u8).init(gpa);603    defer best_msg.deinit();604    var order: std.ArrayList([]const u8) = .empty;605    defer order.deinit(gpa);606607    for (saves_v.array.items) |save| {608        if (save != .object) continue;609        const ver_v = save.object.get("version") orelse continue;610        const msg_v = save.object.get("message") orelse continue;611        if (ver_v != .string or msg_v != .string) continue;612        const ver = ver_v.string;613        const msg = std.mem.trim(u8, msg_v.string, " \t\r\n");614        if (msg.len == 0 or !versionInUpdateRange(ver, current, latest)) continue;615616        const entry = try best_msg.getOrPut(ver);617        if (!entry.found_existing) try order.append(gpa, ver);618        // Always overwrite: saves are newest-first, so last write = oldest save = version-intro message619        entry.value_ptr.* = msg;620    }621622    if (order.items.len == 0) return gpa.dupe(u8, "");623624    var out: std.ArrayList(u8) = .empty;625    errdefer out.deinit(gpa);626    for (order.items) |ver| {627        const msg = best_msg.get(ver).?;628        // Use only the first line as the summary; multi-line saves may have implementation details below629        const summary_end = std.mem.indexOf(u8, msg, "\n") orelse msg.len;630        const summary = std.mem.trim(u8, msg[0..summary_end], " \t\r");631        if (summary.len == 0) continue;632        try appendLine(&out, gpa, "## {s}\n", .{ver});633        try appendLine(&out, gpa, "- {s}\n\n", .{summary});634    }635636    if (out.items.len == 0) {637        out.deinit(gpa);638        return gpa.dupe(u8, "");639    }640    return out.toOwnedSlice(gpa);641}642643fn appendLine(out: *std.ArrayList(u8), gpa: std.mem.Allocator, comptime template: []const u8, args: anytype) !void {644    const line = try std.fmt.allocPrint(gpa, template, args);645    defer gpa.free(line);646    try out.appendSlice(gpa, line);647}648649fn versionInUpdateRange(candidate: []const u8, current: []const u8, latest: []const u8) bool {650    const cand = parseSemver(candidate) orelse return std.mem.eql(u8, candidate, latest);651    const cur = parseSemver(current) orelse return std.mem.eql(u8, candidate, latest);652    const lat = parseSemver(latest) orelse return std.mem.eql(u8, candidate, latest);653    return compareSemver(cand, cur) == .gt and compareSemver(cand, lat) != .gt;654}655656fn remoteVersionNewer(current: []const u8, remote: []const u8) bool {657    const cur = parseSemver(current) orelse return !std.mem.eql(u8, current, remote);658    const rem = parseSemver(remote) orelse return !std.mem.eql(u8, current, remote);659    return compareSemver(rem, cur) == .gt;660}661662const VersionOrder = enum { lt, eq, gt };663664fn compareSemver(a: Semver, b: Semver) VersionOrder {665    if (a.major != b.major) return if (a.major < b.major) .lt else .gt;666    if (a.minor != b.minor) return if (a.minor < b.minor) .lt else .gt;667    if (a.patch != b.patch) return if (a.patch < b.patch) .lt else .gt;668    return .eq;669}670671fn parseSemver(raw: []const u8) ?Semver {672    const v = if (std.mem.startsWith(u8, raw, "v")) raw[1..] else raw;673    var it = std.mem.splitScalar(u8, v, '.');674    const major_s = it.next() orelse return null;675    const minor_s = it.next() orelse return null;676    const patch_s = it.next() orelse return null;677    if (it.next() != null) return null;678    return .{679        .major = std.fmt.parseInt(u32, major_s, 10) catch return null,680        .minor = std.fmt.parseInt(u32, minor_s, 10) catch return null,681        .patch = std.fmt.parseInt(u32, patch_s, 10) catch return null,682    };683}684685test "versionInUpdateRange includes only newer versions through latest" {686    try std.testing.expect(versionInUpdateRange("3.2.3", "3.1.9", "3.2.3"));687    try std.testing.expect(versionInUpdateRange("3.2.0", "3.1.9", "3.2.3"));688    try std.testing.expect(!versionInUpdateRange("3.1.9", "3.1.9", "3.2.3"));689    try std.testing.expect(!versionInUpdateRange("3.2.4", "3.1.9", "3.2.3"));690}691692test "remoteVersionNewer does not offer downgrades" {693    try std.testing.expect(remoteVersionNewer("3.2.3", "3.2.4"));694    try std.testing.expect(!remoteVersionNewer("3.2.4", "3.2.3"));695    try std.testing.expect(!remoteVersionNewer("3.2.4", "3.2.4"));696}697698test "releaseNotesFromArchiveJson uses oldest save per version" {699    // Saves arrive newest-first. For 3.2.3, the newest save is a CONTINUITY update;700    // the oldest is the version-intro message. We expect the intro message in the output.701    const body =702        \\{703        \\  "saves": [704        \\    {"version":"3.2.3","message":"wip: record verification in CONTINUITY"},705        \\    {"version":"3.2.1","message":"old release"},706        \\    {"version":"3.2.3","message":"add streaming deflate path"}707        \\  ]708        \\}709    ;710    const notes = try releaseNotesFromArchiveJson(std.testing.allocator, body, "3.2.1", "3.2.3");711    defer std.testing.allocator.free(notes);712713    try std.testing.expect(std.mem.indexOf(u8, notes, "## 3.2.3") != null);714    try std.testing.expect(std.mem.indexOf(u8, notes, "- add streaming deflate path") != null);715    try std.testing.expect(std.mem.indexOf(u8, notes, "CONTINUITY") == null);716    try std.testing.expect(std.mem.indexOf(u8, notes, "old release") == null);717}718719test "releaseNotesFromMetadata reads canonical notes and ignores retired keys" {720    const a = std.testing.allocator;721722    // Canonical field is read.723    {724        var parsed = try std.json.parseFromSlice(std.json.Value, a, "{\"notes\":\"colored progress bar\"}", .{});725        defer parsed.deinit();726        const got = releaseNotesFromMetadata(a, parsed.value).?;727        defer a.free(got);728        try std.testing.expectEqualStrings("colored progress bar", got);729    }730731    // Retired field names are no longer honoured — they fall through to null so732    // the caller drops to the archives.json derivation instead.733    {734        var parsed = try std.json.parseFromSlice(std.json.Value, a, "{\"release_notes\":\"x\",\"changelog\":\"y\"}", .{});735        defer parsed.deinit();736        try std.testing.expect(releaseNotesFromMetadata(a, parsed.value) == null);737    }738}739740// nina goodbye — clean uninstall. Three install paths:741// - nix profile (binary in nix store with a profile element) → nix profile remove742// - koh build or source build (plain binary on PATH) → delete the file743pub fn goodbye(ctx: Ctx) !void {744    output.goodbyeStart();745746    var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;747    const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {748        errors.error_info.setMessage("could not determine install path", .{});749        return error.Internal;750    };751752    // A binary outside the nix store is a koh build or source build — delete it.753    if (!std.mem.startsWith(u8, install_path, "/nix/store/")) {754        output.goodbyeFile(install_path);755        if (ctx.cfg.confirm and !output.confirm("")) return;756        std.Io.Dir.deleteFileAbsolute(ctx.io, install_path) catch |e| {757            errors.error_info.setMessage("could not remove {s}", .{install_path});758            return e;759        };760        output.goodbyeDone();761        return;762    }763764    // Binary is in the nix store — find and remove the profile element.765    const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);766    defer {767        if (nina_element) |n| ctx.gpa.free(n);768    }769770    if (nina_element == null) {771        errors.error_info.setMessage("nina not found in nix profile — was it installed via 'nix profile add'?", .{});772        return error.Internal;773    }774775    output.goodbyeNix();776    if (ctx.cfg.confirm and !output.confirm("")) return;777    const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "remove", nina_element.? }) catch {778        output.goodbyeFailed("nix profile remove failed");779        return;780    };781    if (ec != 0) {782        output.goodbyeFailed("nix profile remove failed");783        return;784    }785    output.goodbyeDone();786}787788fn channelUpdateCmd(ctx: Ctx) !void {789    output.updateStart(ctx.machine.name);790    _ = try exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa);791    output.updateDone();792}793794pub fn upgrade(ctx: Ctx) !void {795    if (!try runPreHook(ctx, "pre-upgrade")) {796        output.aborted();797        return error.HookAborted;798    }799800    output.upgradeStart(ctx.machine.name);801    // Flake systems update inputs (flake.lock); channel systems update channels.802    // Running nix-channel --update on a flake system is a no-op at best. The803    // rebuild below is already flake-aware via exec.nixosRebuildSwitch.804    if (flakeSystem(ctx)) {805        output.printSubstep("updating flake inputs", .{});806        _ = exec.flakeUpdateAt(ctx.io, &ctx.machine, ctx.gpa, ctx.machine.config_path) catch {};807    } else {808        output.printSubstep("updating channels", .{});809        _ = exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa) catch {};810    }811    output.printSubstep("rebuilding", .{});812    output.buildPanelInit();813    const start = std.Io.Clock.awake.now(ctx.io);814    var panel = output.BuildPanel{};815    const code = exec.nixosRebuildSwitchWithPanel(ctx.io, &ctx.machine, ctx.gpa, &panel, ctx.passthrough) catch |e| {816        output.buildPanelClear();817        return e;818    };819    output.buildPanelClear();820    if (code != 0) {821        output.applyFailed("");822        return error.BuildFailed;823    }824    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());825    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));826    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;827    output.applyDone(gen, elapsed, false);828    runPostHook(ctx, "post-upgrade");829}830831pub fn log(ctx: Ctx) !void {832    output.logHeader(ctx.machine.name);833    const content = exec.readNinaLog(ctx.gpa, ctx.io, ctx.environ, ctx.last) catch {834        // No log yet — that's fine835        return;836    };837    defer ctx.gpa.free(content);838    var lines = std.mem.splitScalar(u8, content, '\n');839    while (lines.next()) |line| {840        const t = std.mem.trim(u8, line, " \t\r");841        if (t.len == 0) continue;842        if (t[0] == '{') {843            renderJsonLogLine(ctx.gpa, t);844        } else {845            // legacy tab-separated format846            var parts = std.mem.tokenizeScalar(u8, t, '\t');847            const date = parts.next() orelse continue;848            const time = parts.next() orelse "";849            const action = parts.next() orelse "";850            const detail = parts.next() orelse "";851            output.logRow(date, time, action, detail);852        }853    }854}855856// The on-disk log is JSON Lines: {"ts","machine","command","outcome","gen_after",...}.857// Render ts -> date/time columns, command -> action, outcome(+gen) -> detail.858fn renderJsonLogLine(gpa: std.mem.Allocator, line: []const u8) void {859    const parsed = std.json.parseFromSlice(std.json.Value, gpa, line, .{}) catch {860        output.logRow(line, "", "", ""); // unparseable — show raw rather than drop861        return;862    };863    defer parsed.deinit();864    if (parsed.value != .object) return;865    const o = parsed.value.object;866867    const ts = jsonStr(o, "ts");868    const date = if (ts.len >= 10) ts[0..10] else ts;869    const time = if (ts.len >= 16) ts[11..16] else "";870    const action = jsonStr(o, "command");871    const outcome = jsonStr(o, "outcome");872873    var buf: [160]u8 = undefined;874    var detail: []const u8 = outcome;875    if (o.get("gen_after")) |g| {876        if (g == .integer) {877            detail = std.fmt.bufPrint(&buf, "{s}   -> gen {d}", .{ outcome, g.integer }) catch outcome;878        }879    }880    output.logRow(date, time, action, detail);881}882883fn jsonStr(o: std.json.ObjectMap, key: []const u8) []const u8 {884    if (o.get(key)) |v| {885        if (v == .string) return v.string;886    }887    return "";888}889890pub fn edit(ctx: Ctx) !void {891    // `edit` is multi-word, so a bare positional ("hardware") arrives as ctx.sub.892    // hardware-configuration.nix is generated by nixos-generate-config and warns893    // against hand-editing — refuse rather than silently opening the wrong file.894    if (std.mem.eql(u8, ctx.sub, "hardware")) {895        output.editHardwareWarning();896        return;897    }898899    // --dir opens the whole config directory (for editors that work better with900    // a folder open), as root so root-owned config trees like /etc/nixos work.901    var open_dir = false;902    for (ctx.args) |arg| {903        if (std.mem.eql(u8, arg, "--dir")) open_dir = true;904    }905    if (open_dir) {906        output.editOpen(ctx.machine.config_path, ctx.cfg.editor);907        _ = try exec.openEditorSudo(ctx.io, ctx.gpa, ctx.cfg.editor, ctx.machine.config_path);908        return;909    }910911    const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});912    defer ctx.gpa.free(path);913    output.editOpen(path, ctx.cfg.editor);914    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);915}916917pub fn fmt(ctx: Ctx) !void {918    const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});919    defer ctx.gpa.free(path);920    if (ctx.check) {921        const code = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, true);922        if (code != 0) output.fmtNeedsFormat() else output.fmtDone();923        return;924    }925    output.fmtStart(path);926    _ = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, false);927    output.fmtDone();928}929930pub fn repl(ctx: Ctx) !void {931    output.replStart();932    _ = try exec.nixRepl(ctx.io, &ctx.machine, ctx.gpa);933}934935pub fn develop(ctx: Ctx) !void {936    if (std.mem.eql(u8, ctx.sub, "show")) {937        _ = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, null, ctx.passthrough);938        return;939    }940    const run_cmd: ?[]const u8 = if (ctx.args.len > 0 and std.mem.eql(u8, ctx.sub, "run"))941        ctx.args[0]942    else943        null;944    output.developStart(&.{});945    _ = try exec.nixDevelopPs1(ctx.io, &ctx.machine, ctx.gpa, run_cmd, ctx.environ, ctx.passthrough);946    output.developDone();947}948949pub fn info(ctx: Ctx) !void {950    output.infoHeader(ctx.machine.name);951    const nixos_ver = exec.systemInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");952    defer ctx.gpa.free(nixos_ver);953    output.infoRow("nixos", std.mem.trim(u8, nixos_ver, " \t\n\r"));954955    const kernel = exec.kernelInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");956    defer ctx.gpa.free(kernel);957    output.infoRow("kernel", std.mem.trim(u8, kernel, " \t\n\r"));958959    const uptime = exec.uptimeInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");960    defer ctx.gpa.free(uptime);961    output.infoRow("uptime", std.mem.trim(u8, uptime, " \t\n\r"));962}963964pub fn boot(ctx: Ctx) !void {965    output.bootHeader(ctx.machine.name);966    const entries = exec.bootEntries(ctx.gpa, ctx.io, &ctx.machine) catch &.{};967    defer ctx.gpa.free(entries);968    for (entries, 0..) |entry, i| output.bootEntry(entry, i);969}970971pub fn searchCmd(ctx: Ctx) !void {972    const query = if (ctx.args.len > 0) ctx.args[0] else "";973    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);974    const selected = try search_tui.run(ctx.gpa, ctx.io, query, .packages, ctx.environ);975    if (selected) |npkg| try selectAndInstall(ctx, npkg);976}977978pub fn optionCmd(ctx: Ctx) !void {979    const query = if (ctx.args.len > 0) ctx.args[0] else "";980    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);981    _ = try search_tui.run(ctx.gpa, ctx.io, query, .options, ctx.environ);982}983984pub fn install(ctx: Ctx) !void {985    const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;986987    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);988989    // Search for the package to get the attr990    const pkgs = api.searchPackages(ctx.gpa, ctx.io, ctx.environ, pkg_name) catch {991        errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});992        errors.error_info.setSuggestion("nina search {s}", .{pkg_name});993        return error.PackageNotFound;994    };995996    if (pkgs.len == 0) {997        // No matches — likely a typo. Suggest the closest real package and offer it.998        if (closestPackage(ctx, pkg_name)) |sugg| {999            output.didYouMean(pkg_name, sugg.pname);1000            if (output.confirm("")) try selectAndInstall(ctx, sugg);1001            return;1002        }1003        errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});1004        errors.error_info.setSuggestion("nina search {s}", .{pkg_name});1005        return error.PackageNotFound;1006    }10071008    // Prefer an exact name match over the first search result — `install ripgrep`1009    // must pick "ripgrep", not the alphabetically-first match like "repgrep".1010    var found = pkgs[0];1011    for (pkgs) |p| {1012        if (std.mem.eql(u8, p.pname, pkg_name)) {1013            found = p;1014            break;1015        }1016    }1017    try selectAndInstall(ctx, found);1018}10191020// Find the real package whose name is closest to a not-found query (typo help).1021// Typos usually keep the leading characters, so gather candidates with a prefix1022// search and rank by edit distance; return the best only if it's typo-close.1023fn closestPackage(ctx: Ctx, query: []const u8) ?types.NixPackage {1024    if (query.len < 2) return null;1025    var candidates = api.searchPackages(ctx.gpa, ctx.io, ctx.environ, query[0..@min(query.len, 4)]) catch &.{};1026    if (candidates.len == 0 and query.len > 2) {1027        candidates = api.searchPackages(ctx.gpa, ctx.io, ctx.environ, query[0..2]) catch &.{};1028    }1029    if (candidates.len == 0) return null;10301031    var best: ?types.NixPackage = null;1032    var best_dist: usize = std.math.maxInt(usize);1033    for (candidates) |p| {1034        const d = editDistance(query, p.pname);1035        if (d > 0 and d < best_dist) {1036            best_dist = d;1037            best = p;1038        }1039    }1040    // Only suggest a genuinely close name, scaled to query length.1041    const threshold = @max(@as(usize, 2), query.len / 3);1042    return if (best_dist <= threshold) best else null;1043}10441045// Case-insensitive Levenshtein distance. Names longer than the row buffer are1046// treated as far away (never suggested).1047fn editDistance(a: []const u8, b: []const u8) usize {1048    const n = b.len;1049    if (a.len == 0) return n;1050    if (n == 0) return a.len;1051    if (n + 1 > 128) return std.math.maxInt(usize);1052    var prev: [128]usize = undefined;1053    var curr: [128]usize = undefined;1054    var j: usize = 0;1055    while (j <= n) : (j += 1) prev[j] = j;1056    var i: usize = 1;1057    while (i <= a.len) : (i += 1) {1058        curr[0] = i;1059        j = 1;1060        while (j <= n) : (j += 1) {1061            const cost: usize = if (std.ascii.toLower(a[i - 1]) == std.ascii.toLower(b[j - 1])) 0 else 1;1062            curr[j] = @min(prev[j] + 1, @min(curr[j - 1] + 1, prev[j - 1] + cost));1063        }1064        @memcpy(prev[0 .. n + 1], curr[0 .. n + 1]);1065    }1066    return prev[n];1067}10681069test "editDistance is case-insensitive Levenshtein" {1070    try std.testing.expectEqual(@as(usize, 1), editDistance("firefux", "firefox"));1071    try std.testing.expectEqual(@as(usize, 0), editDistance("git", "GIT"));1072    try std.testing.expectEqual(@as(usize, 2), editDistance("fierfox", "firefox"));1073    try std.testing.expectEqual(@as(usize, 7), editDistance("", "firefox"));1074}10751076// Prompt for the install method (profile / system / try) and dispatch. Shared by1077// `nina install <pkg>` and the search widget's Enter-to-select — the letter keys1078// are read here, after the search widget's raw mode is gone, so they don't1079// collide with typing a query.1080fn selectAndInstall(ctx: Ctx, npkg: types.NixPackage) !void {1081    output.installSelectPrompt(npkg.pname, npkg.version);10821083    var choice_buf: [8]u8 = undefined;1084    var choice_len: usize = 0;1085    while (choice_len < choice_buf.len) {1086        const n = std.posix.read(std.posix.STDIN_FILENO, choice_buf[choice_len .. choice_len + 1]) catch break;1087        if (n == 0) break;1088        if (choice_buf[choice_len] == '\n') break;1089        choice_len += 1;1090    }1091    const choice = std.mem.trim(u8, choice_buf[0..choice_len], " \t");10921093    if (choice.len == 0 or choice[0] == 'i' or choice[0] == 'I') {1094        try profileInstallPkg(ctx, npkg);1095    } else if (choice[0] == 's' or choice[0] == 'S') {1096        try systemInstallPkg(ctx, npkg);1097    } else if (choice[0] == 't' or choice[0] == 'T') {1098        try tryPkg(ctx, npkg);1099    }1100}11011102fn profileInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {1103    output.installStart(npkg.pname, .profile);1104    if (npkg.unfree) {1105        output.printSubstep("NIXPKGS_ALLOW_UNFREE=1 nix profile add --impure nixpkgs#{s}", .{npkg.attr});1106        output.printTeach(try std.fmt.allocPrint(ctx.gpa, "NIXPKGS_ALLOW_UNFREE=1 nix profile add --impure nixpkgs#{s}", .{npkg.attr}));1107    } else {1108        output.printSubstep("nix profile add nixpkgs#{s}", .{npkg.attr});1109        output.printTeach(try std.fmt.allocPrint(ctx.gpa, "nix profile add nixpkgs#{s}", .{npkg.attr}));1110    }1111    const code = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, ctx.environ, npkg.attr, npkg.unfree);1112    if (code != 0) return error.ProcessFailed;1113    output.installDone(npkg.pname);1114}11151116fn systemInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {1117    const config_path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});1118    defer ctx.gpa.free(config_path);1119    const line = api.findSystemPackagesLine(ctx.io, config_path) orelse 1;1120    output.installEditorPrompt(npkg.pname, config_path, line, ctx.cfg.editor);1121    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, config_path, line);1122    if (ctx.cfg.confirm) {1123        if (output.confirm("apply now? ")) {1124            try apply(ctx);1125        }1126    }1127}11281129fn tryPkg(ctx: Ctx, npkg: types.NixPackage) !void {1130    output.tryStart(npkg.pname);1131    output.printSubstep("nix shell nixpkgs#{s}", .{npkg.attr});1132    output.tryExitHint();1133    _ = try exec.nixShellPs1(ctx.io, &ctx.machine, ctx.gpa, npkg.attr, ctx.environ);1134    output.tryDone();1135}11361137pub fn remove(ctx: Ctx) !void {1138    const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1139    output.removeStart(pkg_name);1140    const code = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, pkg_name);1141    if (code != 0) return error.ProcessFailed;1142    output.done();1143}11441145pub fn list(ctx: Ctx) !void {1146    output.listHeader(ctx.machine.name);11471148    // Profile packages: parse `nix profile list --json` into clean name+version1149    // rows instead of dumping nix's verbose multi-line "Name:/Flake attribute:"1150    // blocks.1151    if (exec.profileListJson(ctx.gpa, ctx.io, &ctx.machine) catch null) |json| {1152        defer ctx.gpa.free(json);1153        output.listSection("profile");1154        renderProfileJson(ctx.gpa, json);1155    }11561157    // System packages: the references of /run/current-system/sw, each a1158    // <hash>-<name>-<version> store path.1159    if (exec.systemPackagePaths(ctx.gpa, ctx.io, &ctx.machine) catch null) |paths| {1160        defer ctx.gpa.free(paths);1161        output.blankLine();1162        output.listSection("system");1163        var lines = std.mem.splitScalar(u8, paths, '\n');1164        while (lines.next()) |line| {1165            const t = std.mem.trim(u8, line, " \t\r");1166            if (t.len == 0) continue;1167            const row = pkgFromStorePath(t);1168            // Skip support paths with no parseable version (man pages, wrappers).1169            if (row.version.len == 0) continue;1170            output.listPkg(row.name, row.version);1171        }1172    }1173}11741175const PkgRow = struct { name: []const u8, version: []const u8 };11761177// Split a nix store path basename (<hash>-<name>-<version>) into name + version.1178// Version begins at the first '-' followed by a digit, which reliably lands on1179// the name/version boundary since the 32-char hash and package names start with1180// non-digits.1181fn pkgFromStorePath(path: []const u8) PkgRow {1182    const base = std.fs.path.basename(path);1183    const after_hash = if (base.len > 33 and base[32] == '-') base[33..] else base;1184    var i: usize = 0;1185    while (i + 1 < after_hash.len) : (i += 1) {1186        if (after_hash[i] == '-' and std.ascii.isDigit(after_hash[i + 1])) {1187            return .{ .name = after_hash[0..i], .version = stripOutputSuffix(after_hash[i + 1 ..]) };1188        }1189    }1190    return .{ .name = after_hash, .version = "" };1191}11921193// Multi-output derivations append the output name to the store path (e.g.1194// curl-8.20.0-bin, less-692-man). Strip that suffix so the version column reads1195// as just the version.1196fn stripOutputSuffix(ver: []const u8) []const u8 {1197    const suffixes = [_][]const u8{ "-bin", "-man", "-dev", "-doc", "-lib", "-info", "-out", "-static", "-devdoc" };1198    for (suffixes) |s| {1199        if (std.mem.endsWith(u8, ver, s)) return ver[0 .. ver.len - s.len];1200    }1201    return ver;1202}12031204test "pkgFromStorePath splits name and version at first dash-digit" {1205    const a = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-ripgrep-15.1.0");1206    try std.testing.expectEqualStrings("ripgrep", a.name);1207    try std.testing.expectEqualStrings("15.1.0", a.version);12081209    const b = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-helix-25.01");1210    try std.testing.expectEqualStrings("helix", b.name);1211    try std.testing.expectEqualStrings("25.01", b.version);12121213    // multi-output store paths drop their output-name suffix1214    const c = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-curl-8.20.0-bin");1215    try std.testing.expectEqualStrings("curl", c.name);1216    try std.testing.expectEqualStrings("8.20.0", c.version);1217}12181219fn firstStorePath(el: std.json.Value) ?[]const u8 {1220    if (el != .object) return null;1221    const sp = el.object.get("storePaths") orelse return null;1222    if (sp != .array or sp.array.items.len == 0) return null;1223    const first = sp.array.items[0];1224    return if (first == .string) first.string else null;1225}12261227// `nix profile list --json` has two shapes across nix versions: newer keys each1228// element by name (object), older lists them positionally (array). Handle both.1229fn renderProfileJson(gpa: std.mem.Allocator, json: []const u8) void {1230    const parsed = std.json.parseFromSlice(std.json.Value, gpa, json, .{}) catch return;1231    defer parsed.deinit();1232    if (parsed.value != .object) return;1233    const elements = parsed.value.object.get("elements") orelse return;1234    switch (elements) {1235        .object => |obj| {1236            var it = obj.iterator();1237            while (it.next()) |entry| {1238                const ver = if (firstStorePath(entry.value_ptr.*)) |p| pkgFromStorePath(p).version else "";1239                output.listPkg(entry.key_ptr.*, ver);1240            }1241        },1242        .array => |arr| {1243            for (arr.items) |el| {1244                const path = firstStorePath(el) orelse continue;1245                const row = pkgFromStorePath(path);1246                output.listPkg(row.name, row.version);1247            }1248        },1249        else => {},1250    }1251}12521253pub fn tryCmd(ctx: Ctx) !void {1254    const pkg_name_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1255    const shell_pkg = types.NixPackage{ .attr = pkg_name_arg, .pname = pkg_name_arg, .version = "", .description = "" };1256    try tryPkg(ctx, shell_pkg);1257}12581259// --- Home Manager commands ---12601261const home_help = [_][2][]const u8{1262    .{ "init", "set up home manager for the first time" },1263    .{ "init --switch", "set up and activate immediately" },1264    .{ "apply", "apply home-manager configuration" },1265    .{ "apply --dry", "preview changes without activating" },1266    .{ "back", "roll back one generation" },1267    .{ "history", "list all generations" },1268    .{ "edit", "open home.nix" },1269    .{ "check", "validate without applying" },1270    .{ "diff", "compare the latest two generations" },1271    .{ "packages", "list managed packages" },1272};12731274const HomeGen = struct {1275    number: u32,1276    date: []const u8,1277    time: []const u8,1278    path: []const u8,1279};12801281// `home-manager generations` lines read:1282//   2026-06-01 11:56 : id 765 -> /nix/store/<hash>-home-manager-generation1283// Newest first, so index 0 is the current generation.1284fn parseHomeGenerations(gpa: std.mem.Allocator, out_str: []const u8) ![]HomeGen {1285    var gens: std.ArrayList(HomeGen) = .empty;1286    var lines = std.mem.splitScalar(u8, out_str, '\n');1287    while (lines.next()) |line| {1288        const t = std.mem.trim(u8, line, " \t\r");1289        if (t.len == 0) continue;1290        var it = std.mem.tokenizeAny(u8, t, " \t");1291        const date = it.next() orelse continue;1292        const time = it.next() orelse continue;1293        var number: ?u32 = null;1294        var path: []const u8 = "";1295        while (it.next()) |tok| {1296            if (std.mem.eql(u8, tok, "id")) {1297                if (it.next()) |n| number = std.fmt.parseInt(u32, n, 10) catch null;1298            } else if (std.mem.startsWith(u8, tok, "/nix/store/")) {1299                path = tok;1300            }1301        }1302        const num = number orelse continue;1303        try gens.append(gpa, .{1304            .number = num,1305            .date = try gpa.dupe(u8, date),1306            .time = try gpa.dupe(u8, time),1307            .path = try gpa.dupe(u8, path),1308        });1309    }1310    return gens.toOwnedSlice(gpa);1311}13121313fn freeHomeGens(gpa: std.mem.Allocator, gens: []HomeGen) void {1314    for (gens) |g| {1315        gpa.free(g.date);1316        gpa.free(g.time);1317        gpa.free(g.path);1318    }1319    gpa.free(gens);1320}13211322test "parseHomeGenerations reads id, date and store path" {1323    const a = std.testing.allocator;1324    const sample =1325        \\2026-06-01 11:56 : id 765 -> /nix/store/aaaa-home-manager-generation1326        \\2026-05-31 10:29 : id 764 -> /nix/store/bbbb-home-manager-generation1327    ;1328    const gens = try parseHomeGenerations(a, sample);1329    defer freeHomeGens(a, gens);1330    try std.testing.expectEqual(@as(usize, 2), gens.len);1331    try std.testing.expectEqual(@as(u32, 765), gens[0].number);1332    try std.testing.expectEqualStrings("2026-06-01", gens[0].date);1333    try std.testing.expectEqualStrings("11:56", gens[0].time);1334    try std.testing.expectEqualStrings("/nix/store/aaaa-home-manager-generation", gens[0].path);1335    try std.testing.expectEqual(@as(u32, 764), gens[1].number);1336}13371338// Current (newest) home generation number, or 0 if unavailable.1339fn homeCurrentGen(ctx: Ctx) u32 {1340    const out = exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine) catch return 0;1341    defer ctx.gpa.free(out);1342    const gens = parseHomeGenerations(ctx.gpa, out) catch return 0;1343    defer freeHomeGens(ctx.gpa, gens);1344    return if (gens.len > 0) gens[0].number else 0;1345}13461347pub fn home(ctx: Ctx) !void {1348    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help"))1349        return output.subcommandHelp("home", &home_help, null);13501351    // Home Manager manages the local user's environment. Detection (which binary,1352    // ~/.config/home-manager, $HOME/$USER for the flake ref) all read the LOCAL1353    // host, while exec routes over SSH for a remote machine — so `home --on1354    // <remote>` would decide mode/flake-ref from the wrong box. Refuse it cleanly1355    // rather than acting on a mismatch.1356    if (!ctx.machine.local) {1357        output.homeLocalOnly(ctx.machine.name);1358        return;1359    }13601361    // init runs before mode detection: its whole purpose is bootstrapping a host1362    // that has no home-manager yet, so a .none mode must not short-circuit it.1363    if (std.mem.eql(u8, ctx.sub, "init")) return homeInitCmd(ctx);13641365    const mode = exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ);1366    if (mode == .none) {1367        output.homeNotInstalled();1368        return;1369    }13701371    // apply is the only command meaningful in module mode (it redirects to1372    // `nina apply`); everything else needs the standalone home-manager CLI.1373    if (std.mem.eql(u8, ctx.sub, "apply")) return homeApply(ctx, mode);1374    // edit just opens the local home.nix — fine in module mode too.1375    if (std.mem.eql(u8, ctx.sub, "edit")) return homeEdit(ctx);13761377    if (mode == .module) {1378        output.homeModuleManaged();1379        return;1380    }13811382    if (std.mem.eql(u8, ctx.sub, "back")) return homeBack(ctx);1383    if (std.mem.eql(u8, ctx.sub, "history")) return homeHistory(ctx);1384    if (std.mem.eql(u8, ctx.sub, "check")) return homeCheck(ctx);1385    if (std.mem.eql(u8, ctx.sub, "diff")) return homeDiff(ctx);1386    if (std.mem.eql(u8, ctx.sub, "packages")) return homePackages(ctx);13871388    return output.subcommandHelp("home", &home_help, null);1389}13901391fn homePackages(ctx: Ctx) !void {1392    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1393    defer ctx.gpa.free(out);1394    const gens = try parseHomeGenerations(ctx.gpa, out);1395    defer freeHomeGens(ctx.gpa, gens);13961397    output.homePackagesHeader(ctx.machine.name);1398    if (gens.len == 0 or gens[0].path.len == 0) return;13991400    // The generation's OWN references are home-manager's activation deps1401    // (bash, coreutils, ...), not what the user installed. The user's packages1402    // live one level down, in the `…-home-manager-path` env the generation1403    // references — descend into it and list ITS references. Fall back to the1404    // generation refs if that env isn't present (older home-manager layouts).1405    const gen_refs = exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, gens[0].path) catch return;1406    defer ctx.gpa.free(gen_refs);14071408    var refs = gen_refs;1409    var env_refs: ?[]u8 = null;1410    defer if (env_refs) |e| ctx.gpa.free(e);1411    if (findHomeManagerPath(gen_refs)) |pkg_path| {1412        if (exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, pkg_path)) |e| {1413            env_refs = e;1414            refs = e;1415        } else |_| {}1416    }14171418    // Dedup by name: multi-output derivations (jq, jq-lib, jq-doc) collapse to1419    // the same name after the output suffix is stripped. Keys are slices into1420    // `refs`, valid for this function's lifetime.1421    var seen = std.StringHashMap(void).init(ctx.gpa);1422    defer seen.deinit();1423    var lines = std.mem.splitScalar(u8, refs, '\n');1424    while (lines.next()) |line| {1425        const t = std.mem.trim(u8, line, " \t\r");1426        if (t.len == 0) continue;1427        const row = pkgFromStorePath(t);1428        if (row.version.len == 0) continue;1429        if (std.mem.indexOf(u8, row.name, "home-manager") != null) continue;1430        if (seen.contains(row.name)) continue;1431        seen.put(row.name, {}) catch {};1432        output.listPkg(row.name, row.version);1433    }1434}14351436// The `…-home-manager-path` env among a generation's references — the buildEnv1437// of the user's home.packages. Returns the full store-path line, or null.1438fn findHomeManagerPath(refs: []const u8) ?[]const u8 {1439    var lines = std.mem.splitScalar(u8, refs, '\n');1440    while (lines.next()) |line| {1441        const t = std.mem.trim(u8, line, " \t\r");1442        if (std.mem.indexOf(u8, t, "home-manager-path") != null) return t;1443    }1444    return null;1445}14461447test "findHomeManagerPath picks the env, not the generation or infra" {1448    const refs =1449        \\/nix/store/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-bash-5.31450        \\/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path1451        \\/nix/store/cccccccccccccccccccccccccccccccc-coreutils-9.111452    ;1453    try std.testing.expectEqualStrings(1454        "/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path",1455        findHomeManagerPath(refs).?,1456    );1457    try std.testing.expectEqual(@as(?[]const u8, null), findHomeManagerPath("/nix/store/x-bash-5.3\n"));1458}14591460fn homeDiff(ctx: Ctx) !void {1461    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1462    defer ctx.gpa.free(out);1463    const gens = try parseHomeGenerations(ctx.gpa, out);1464    defer freeHomeGens(ctx.gpa, gens);14651466    // Need two generations and both their store paths to diff their closures.1467    if (gens.len < 2 or gens[0].path.len == 0 or gens[1].path.len == 0) {1468        output.homeNothingToDiff();1469        return;1470    }1471    const newer = gens[0];1472    const older = gens[1];1473    output.homeDiffHeader(older.number, newer.number, ctx.machine.name);1474    if (try exec.diffClosuresPaths(ctx.io, &ctx.machine, ctx.gpa, older.path, newer.path) != 0)1475        return error.ProcessFailed;1476}14771478fn homeCheck(ctx: Ctx) !void {1479    output.homeCheckStart(ctx.machine.name);1480    const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa, ctx.passthrough);1481    if (code != 0) return error.BuildFailed;1482    output.homeCheckOk();1483}14841485fn homeEdit(ctx: Ctx) !void {1486    // Standalone home config lives at ~/.config/home-manager/home.nix; the same1487    // path is what detection keys on for module mode, so it resolves for both.1488    const path = exec.homeNixPath(ctx.gpa, ctx.environ) orelse {1489        errors.error_info.setMessage("could not resolve ~/.config/home-manager/home.nix", .{});1490        return error.ConfigNotFound;1491    };1492    defer ctx.gpa.free(path);1493    output.homeEditOpen(path, ctx.cfg.editor);1494    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);1495}14961497fn homeHistory(ctx: Ctx) !void {1498    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1499    defer ctx.gpa.free(out);1500    const gens = try parseHomeGenerations(ctx.gpa, out);1501    defer freeHomeGens(ctx.gpa, gens);1502    output.homeHistoryHeader(ctx.machine.name);1503    // Newest-first from home-manager; the first row is the current generation.1504    for (gens, 0..) |g, i| output.homeHistoryRow(g.number, g.date, g.time, i == 0);1505}15061507fn homeBack(ctx: Ctx) !void {1508    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1509    defer ctx.gpa.free(out);1510    const gens = try parseHomeGenerations(ctx.gpa, out);1511    defer freeHomeGens(ctx.gpa, gens);15121513    // Newest-first: [0] is current, [1] is the generation to roll back to.1514    if (gens.len < 2) {1515        output.alreadyOldest();1516        return;1517    }1518    const current = gens[0].number;1519    const prev = gens[1].number;15201521    output.homeBackStart(ctx.machine.name, current, prev);1522    if (ctx.cfg.confirm and !output.confirm("")) return;1523    const code = try exec.homeManagerRollback(ctx.io, &ctx.machine, ctx.gpa);1524    if (code != 0) return error.BuildFailed;1525    output.homeBackDone(prev);1526}15271528fn homeInitCmd(ctx: Ctx) !void {1529    var switch_on_init = false;1530    var dir: ?[]const u8 = null;1531    for (ctx.args) |arg| {1532        if (std.mem.eql(u8, arg, "--switch")) {1533            switch_on_init = true;1534        } else if (!std.mem.startsWith(u8, arg, "-")) {1535            dir = arg;1536        }1537    }15381539    // Guard only the default location — a custom dir is the user's call, and1540    // home-manager creates it. Never clobber an existing ~/.config/home-manager.1541    if (dir == null) {1542        if (exec.homeNixPath(ctx.gpa, ctx.environ)) |path| {1543            defer ctx.gpa.free(path);1544            if (exec.pathExists(ctx.io, path)) {1545                output.homeInitExists(path);1546                return;1547            }1548        }1549    }15501551    output.homeInitStart(switch_on_init, dir);1552    const code = try exec.homeManagerInit(ctx.io, &ctx.machine, ctx.gpa, switch_on_init, dir);1553    if (code != 0) return error.BuildFailed;1554    output.homeInitDone(switch_on_init);1555}15561557fn homeApply(ctx: Ctx, mode: exec.HomeManagerMode) !void {1558    // NixOS/flake module: home config is rebuilt by nixos-rebuild — redirect.1559    if (mode == .module) {1560        output.homeModuleManaged();1561        return;1562    }1563    if (ctx.dry) {1564        output.homeApplyDry(ctx.machine.name);1565        const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa, ctx.passthrough);1566        if (code != 0) return error.BuildFailed;1567        output.homeApplyDryDone();1568        return;1569    }15701571    if (!try runPreHook(ctx, "pre-home")) {1572        output.aborted();1573        return error.HookAborted;1574    }15751576    output.homeApplyStart(ctx.machine.name);15771578    // Flake-based home config: switch by attribute with a graceful fallback1579    // chain. A channel-based config (no flake.nix) uses a plain switch.1580    const dir = exec.homeFlakeDir(ctx.gpa, ctx.io, ctx.environ);1581    defer if (dir) |d| ctx.gpa.free(d);1582    if (dir) |d| return homeApplyFlake(ctx, d);15831584    output.printSubstep("home-manager switch", .{});1585    const start = std.Io.Clock.awake.now(ctx.io);1586    const code = try exec.homeManagerSwitch(ctx.io, &ctx.machine, ctx.gpa, ctx.passthrough);1587    if (code != 0) return error.BuildFailed;15881589    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());1590    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));1591    output.homeApplyDone(homeCurrentGen(ctx), elapsed);1592    runPostHook(ctx, "post-home");1593}15941595// Switch a flake-based home config, trying the most specific attribute first:1596//   <dir>#<user>-<arch>-<os>  →  <dir>#<user>  →  <dir>  (home-manager resolves)1597// Each fallback fires only on a missing-attribute error, never on a real build1598// failure. Mirrors how ${USER}-${system} homeConfigurations keys are written.1599fn homeApplyFlake(ctx: Ctx, dir: []const u8) !void {1600    const user = ctx.environ.get("USER") orelse "default";16011602    var refs: std.ArrayList([]const u8) = .empty;1603    defer {1604        for (refs.items) |r| ctx.gpa.free(r);1605        refs.deinit(ctx.gpa);1606    }1607    if (exec.homeManagerAttr(ctx.gpa, ctx.io, &ctx.machine, ctx.environ) catch null) |attr| {1608        defer ctx.gpa.free(attr);1609        try refs.append(ctx.gpa, try std.fmt.allocPrint(ctx.gpa, "{s}#{s}", .{ dir, attr }));1610    }1611    try refs.append(ctx.gpa, try std.fmt.allocPrint(ctx.gpa, "{s}#{s}", .{ dir, user }));1612    try refs.append(ctx.gpa, try ctx.gpa.dupe(u8, dir));16131614    const start = std.Io.Clock.awake.now(ctx.io);1615    for (refs.items, 0..) |ref, i| {1616        output.printSubstep("home-manager switch --flake {s}", .{ref});1617        switch (try exec.homeManagerSwitchFlake(ctx.io, &ctx.machine, ctx.gpa, ref, ctx.passthrough)) {1618            .ok => {1619                const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());1620                const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));1621                output.homeApplyDone(homeCurrentGen(ctx), elapsed);1622                runPostHook(ctx, "post-home");1623                return;1624            },1625            // Attr not defined by the flake — drop to the next candidate.1626            .attr_missing => {1627                if (i + 1 < refs.items.len) output.homeAttrFallback(ref);1628                continue;1629            },1630            .failed => return error.BuildFailed,1631        }1632    }1633    return error.BuildFailed;1634}16351636// --- Service commands ---16371638const service_help = [_][2][]const u8{1639    .{ "list", "list running services" },1640    .{ "logs <svc>", "show service logs" },1641    .{ "status <svc>", "service status" },1642    .{ "start <svc>", "start a service" },1643    .{ "stop <svc>", "stop a service" },1644    .{ "restart <svc>", "restart a service" },1645    .{ "enable <svc>", "enable at boot" },1646    .{ "disable <svc>", "disable at boot" },1647};16481649pub fn service(ctx: Ctx) !void {1650    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");1651    if (std.mem.eql(u8, ctx.sub, "list")) {1652        output.serviceListHeader(ctx.machine.name);1653        const svcs = exec.serviceList(ctx.gpa, ctx.io, &ctx.machine, ctx.user) catch &.{};1654        defer ctx.gpa.free(svcs);1655        for (svcs) |s| output.serviceRow(s);1656        return;1657    }1658    if (std.mem.eql(u8, ctx.sub, "logs")) {1659        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1660        const follow = ctx.args.len > 1 and std.mem.eql(u8, ctx.args[1], "-f");1661        output.serviceLogsHeader(name, ctx.last, ctx.machine.name);1662        _ = try exec.serviceLogs(ctx.io, &ctx.machine, ctx.gpa, name, ctx.last, follow, ctx.user);1663        return;1664    }1665    if (std.mem.eql(u8, ctx.sub, "status")) {1666        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1667        output.serviceVerb("status", name, ctx.machine.name);1668        _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, "status", name, ctx.user);1669        return;1670    }1671    // start/stop/restart/enable/disable1672    const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1673    if (ctx.cfg.confirm and (std.mem.eql(u8, ctx.sub, "stop") or std.mem.eql(u8, ctx.sub, "disable"))) {1674        if (!output.confirm("")) return;1675    }1676    output.serviceVerb(ctx.sub, name, ctx.machine.name);1677    _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, ctx.sub, name, ctx.user);1678    output.serviceDone();1679}16801681// --- Flake commands ---16821683const flake_help = [_][2][]const u8{1684    .{ "init", "create a new flake.nix" },1685    .{ "update", "update flake inputs" },1686    .{ "update <in>", "update a specific input" },1687    .{ "check", "validate the flake" },1688    .{ "show", "inspect flake outputs" },1689    .{ "lock", "regenerate flake.lock" },1690    .{ "clone <url>", "clone a flake repository" },1691};16921693pub fn flake(ctx: Ctx) !void {1694    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("flake", &flake_help, null);1695    if (std.mem.eql(u8, ctx.sub, "update")) {1696        output.flakeUpdateStart();1697        const input: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1698        _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input, ctx.passthrough);1699        output.flakeLockWritten();1700        return;1701    }1702    if (std.mem.eql(u8, ctx.sub, "check")) {1703        output.flakeCheckStart();1704        const code = try exec.flakeCheck(ctx.io, &ctx.machine, ctx.gpa, ctx.passthrough);1705        if (code != 0) {1706            output.checkFailed("");1707            return error.CheckFailed;1708        }1709        output.flakeValid();1710        return;1711    }1712    if (std.mem.eql(u8, ctx.sub, "show")) {1713        const json_out = exec.flakeShow(ctx.gpa, ctx.io, &ctx.machine) catch null;1714        if (json_out) |j| {1715            defer ctx.gpa.free(j);1716            output.flakeShowHeader("flake outputs");1717            // Parse and display the flake outputs1718            const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, j, .{}) catch return;1719            defer parsed.deinit();1720            if (parsed.value == .object) {1721                var it = parsed.value.object.iterator();1722                while (it.next()) |entry| {1723                    if (entry.value_ptr.* == .object) {1724                        var inner = entry.value_ptr.object.iterator();1725                        while (inner.next()) |e2| {1726                            const desc = if (e2.value_ptr.* == .object)1727                                if (e2.value_ptr.object.get("description")) |d|1728                                    if (d == .string) d.string else ""1729                                else1730                                    ""1731                            else1732                                "";1733                            output.flakeShowEntry(entry.key_ptr.*, e2.key_ptr.*, desc);1734                        }1735                    }1736                }1737            }1738        }1739        return;1740    }1741    if (std.mem.eql(u8, ctx.sub, "init")) {1742        _ = try exec.flakeInit(ctx.io, &ctx.machine, ctx.gpa);1743        return;1744    }1745    if (std.mem.eql(u8, ctx.sub, "lock")) {1746        _ = try exec.flakeLock(ctx.io, &ctx.machine, ctx.gpa);1747        return;1748    }1749    if (std.mem.eql(u8, ctx.sub, "clone")) {1750        const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1751        _ = try exec.flakeClone(ctx.io, &ctx.machine, ctx.gpa, url);1752        return;1753    }1754}17551756// --- Store commands ---17571758const store_help = [_][2][]const u8{1759    .{ "info", "store size and counts" },1760    .{ "path <attr>", "store path of a package" },1761    .{ "gc", "collect garbage" },1762    .{ "optimise", "deduplicate store paths with hard links" },1763    .{ "verify", "verify store integrity" },1764    .{ "repair", "repair corrupted paths" },1765};17661767pub fn store(ctx: Ctx) !void {1768    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("store", &store_help, null);1769    if (std.mem.eql(u8, ctx.sub, "gc")) {1770        _ = try exec.storeGc(ctx.io, &ctx.machine, ctx.gpa);1771        return;1772    }1773    // Accept both spellings — optimise (en) and optimize (us).1774    if (std.mem.eql(u8, ctx.sub, "optimise") or std.mem.eql(u8, ctx.sub, "optimize")) {1775        output.storeOptimiseStart(ctx.machine.name);1776        _ = try exec.storeOptimise(ctx.io, &ctx.machine, ctx.gpa);1777        output.storeOptimiseDone();1778        return;1779    }1780    if (std.mem.eql(u8, ctx.sub, "verify")) {1781        output.storeVerifyStart();1782        _ = try exec.storeVerify(ctx.io, &ctx.machine, ctx.gpa);1783        return;1784    }1785    if (std.mem.eql(u8, ctx.sub, "repair")) {1786        if (ctx.cfg.confirm and !output.confirm("")) return;1787        output.storeRepairStart();1788        _ = try exec.storeRepair(ctx.io, &ctx.machine, ctx.gpa);1789        return;1790    }1791    if (std.mem.eql(u8, ctx.sub, "info")) {1792        const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1793        output.storeInfo(si);1794        return;1795    }1796    if (std.mem.eql(u8, ctx.sub, "path")) {1797        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1798        const path = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, attr);1799        defer ctx.gpa.free(path);1800        output.storePath(path);1801        return;1802    }1803    // default: info1804    const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1805    output.storeInfo(si);1806}18071808// --- Channel commands ---18091810const channel_help = [_][2][]const u8{1811    .{ "list", "list channels" },1812    .{ "add <url> [name]", "add a channel" },1813    .{ "remove <name>", "remove a channel" },1814    .{ "update", "update all channels" },1815};18161817pub fn channel(ctx: Ctx) !void {1818    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("channel", &channel_help, null);1819    // On a flake-managed system, nix-channel operations generally don't apply.1820    if (flakeSystem(ctx)) output.flakeChannelNote();1821    if (std.mem.eql(u8, ctx.sub, "list")) {1822        output.channelListHeader(ctx.machine.name);1823        const chans = try exec.channelList(ctx.gpa, ctx.io, &ctx.machine);1824        defer ctx.gpa.free(chans);1825        for (chans) |ch| output.channelRow(ch);1826        return;1827    }1828    if (std.mem.eql(u8, ctx.sub, "add")) {1829        const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1830        const name = if (ctx.args.len > 1) ctx.args[1] else "";1831        _ = try exec.channelAdd(ctx.io, &ctx.machine, ctx.gpa, url, name);1832        output.channelDone();1833        return;1834    }1835    if (std.mem.eql(u8, ctx.sub, "remove")) {1836        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1837        _ = try exec.channelRemove(ctx.io, &ctx.machine, ctx.gpa, name);1838        output.channelDone();1839        return;1840    }1841    if (std.mem.eql(u8, ctx.sub, "update")) {1842        return channelUpdateCmd(ctx);1843    }1844}18451846// --- Profile commands ---18471848pub fn profile(ctx: Ctx) !void {1849    if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {1850        output.profileListHeader();1851        const out = exec.profileList(ctx.gpa, ctx.io, &ctx.machine) catch null;1852        if (out) |o| {1853            defer ctx.gpa.free(o);1854            var lines = std.mem.splitScalar(u8, o, '\n');1855            while (lines.next()) |line| {1856                const t = std.mem.trim(u8, line, " \t\r");1857                if (t.len == 0) continue;1858                output.profileRow(t, "", "");1859            }1860        }1861        return;1862    }1863    if (std.mem.eql(u8, ctx.sub, "install")) {1864        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1865        _ = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, ctx.environ, attr, false);1866        output.done();1867        return;1868    }1869    if (std.mem.eql(u8, ctx.sub, "remove")) {1870        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1871        _ = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, attr);1872        output.done();1873        return;1874    }1875    if (std.mem.eql(u8, ctx.sub, "upgrade")) {1876        _ = try exec.profileUpgrade(ctx.io, &ctx.machine, ctx.gpa);1877        output.done();1878        return;1879    }1880}18811882// --- Pkg commands ---18831884const pkg_help = [_][2][]const u8{1885    .{ "why <pkg>", "what pulled it in" },1886    .{ "deps <pkg>", "direct dependencies" },1887    .{ "size <pkg>", "closure size" },1888    .{ "path <pkg>", "store path" },1889    .{ "closure <pkg>", "full closure" },1890};18911892pub fn pkg(ctx: Ctx) !void {1893    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("pkg", &pkg_help, null);1894    const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1895    if (std.mem.eql(u8, ctx.sub, "why")) {1896        if (try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1897        return;1898    }1899    if (std.mem.eql(u8, ctx.sub, "deps")) {1900        if (try exec.pkgDeps(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1901        return;1902    }1903    if (std.mem.eql(u8, ctx.sub, "size")) {1904        const s = try exec.pkgSize(ctx.gpa, ctx.io, &ctx.machine, name);1905        defer ctx.gpa.free(s);1906        output.pkgResult("size", s);1907        return;1908    }1909    if (std.mem.eql(u8, ctx.sub, "path")) {1910        const p = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, name);1911        defer ctx.gpa.free(p);1912        output.pkgResult("path", p);1913        return;1914    }1915    if (std.mem.eql(u8, ctx.sub, "closure")) {1916        if (try exec.pkgClosure(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1917        return;1918    }1919}19201921// Top-level alias for `nina pkg why <pkg>` — surfaces what pulled a package in1922// without the user needing to know about the `pkg` subgroup.1923pub fn why(ctx: Ctx) !void {1924    const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1925    if (try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1926}19271928// --- Pin / Unpin ---19291930pub fn pin(ctx: Ctx) !void {1931    const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1932    const commit = if (ctx.args.len > 1) ctx.args[1] else return error.Internal;1933    exec.editFlakeLock(ctx.gpa, input, commit) catch return error.ProcessFailed;1934    output.pinDone(input, commit);1935}19361937pub fn unpin(ctx: Ctx) !void {1938    const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1939    _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input, &.{});1940    output.unpinDone(input);1941}19421943// --- Hash / Fetch ---19441945pub fn hash(ctx: Ctx) !void {1946    const path = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1947    const h = try exec.nixHash(ctx.gpa, ctx.io, &ctx.machine, path);1948    defer ctx.gpa.free(h);1949    output.hashResult(std.mem.trim(u8, h, " \t\n\r"));1950}19511952pub fn fetch(ctx: Ctx) !void {1953    const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1954    const h = try exec.nixFetch(ctx.gpa, ctx.io, &ctx.machine, url);1955    defer ctx.gpa.free(h);1956    output.fetchResult(std.mem.trim(u8, h, " \t\n\r"), url);1957}19581959// --- Build / Run ---19601961pub fn build(ctx: Ctx) !void {1962    const attr: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1963    output.buildStart(attr orelse "default");1964    const code = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, attr, ctx.passthrough);1965    if (code != 0) return error.BuildFailed;1966    output.buildDone();1967}19681969pub fn runCmd(ctx: Ctx) !void {1970    const pkg_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1971    output.runStart(pkg_arg);1972    _ = try exec.nixRun(ctx.io, &ctx.machine, ctx.gpa, pkg_arg, ctx.passthrough);1973}19741975// --- Hello ---19761977pub fn hello(ctx: Ctx) !void {1978    output.hello(ctx.cfg.machines);1979}19801981const ConfigKind = enum { flake, channel, none };19821983// Scan the conventional /etc/nixos for a flake.nix (flake-based) or a1984// configuration.nix (channel-based) to pre-fill the wizard's defaults.1985fn scanConfig(io: std.Io) ConfigKind {1986    if (exec.pathExists(io, "/etc/nixos/flake.nix")) return .flake;1987    if (exec.pathExists(io, "/etc/nixos/configuration.nix")) return .channel;1988    return .none;1989}19901991// Runs when the config is absent on first invocation (interactive TTY only).1992// Scans for an existing nixos config, detects flake vs channel, and offers a1993// smart default path — flake-ness is detected, never asked.1994pub fn firstRunWizard(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1995    output.firstRunBanner();1996    output.firstRunNoConfig();19971998    var name_buf: [256]u8 = undefined;1999    var path_buf: [256]u8 = undefined;20002001    const machine_name = output.firstRunPrompt("machine name", "my-machine", &name_buf);20022003    output.firstRunScanning();2004    const kind = scanConfig(io);2005    switch (kind) {2006        .flake => output.firstRunDetected("/etc/nixos/flake.nix", true),2007        .channel => output.firstRunDetected("/etc/nixos/configuration.nix", false),2008        .none => output.firstRunNoneFound(),2009    }20102011    // Detected systems default to /etc/nixos (press enter to confirm); when2012    // nothing was found, leave the default empty so the user must type a path.2013    const default_path: []const u8 = if (kind == .none) "" else "/etc/nixos";2014    const config_path = output.firstRunPromptDefault("config path", default_path, kind != .none, &path_buf);20152016    // Re-detect at the chosen path in case the user pointed elsewhere — flake.nix2017    // there means a flake system, recorded so channel commands warn appropriately.2018    const use_flakes = exec.dirHasFlake(gpa, io, config_path);20192020    const conf_path = try config.configPath(gpa, environ);2021    defer gpa.free(conf_path);2022    if (std.fs.path.dirname(conf_path)) |dir| exec.ensureDir(gpa, io, dir);20232024    // `flake` is a top-level config field, so it must precede the [machine] block.2025    const flake_line = if (use_flakes) "flake = true\n" else "";2026    var content_buf: [1024]u8 = undefined;2027    const content = try std.fmt.bufPrint(2028        &content_buf,2029        "{s}[machine]\nname = {s}\nconfig = {s}\nlocal = true\n",2030        .{ flake_line, machine_name, config_path },2031    );20322033    const file = std.Io.Dir.createFile(.cwd(), io, conf_path, .{}) catch {2034        errors.error_info.setMessage("could not write {s}", .{conf_path});2035        return error.Internal;2036    };2037    defer file.close(io);2038    file.writePositionalAll(io, content, 0) catch {2039        errors.error_info.setMessage("could not write {s}", .{conf_path});2040        return error.Internal;2041    };20422043    output.firstRunWritten(conf_path);2044}20452046pub fn setup(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {2047    // Create the config first if it doesn't exist. This makes `nina setup`2048    // a complete onboarding command — not just a nix-features check. Any legacy2049    // ~/.nina.conf is migrated to the XDG path before we decide to run the wizard.2050    config.migrateLegacyConfig(gpa, io, environ);2051    if (config.configPath(gpa, environ)) |conf_path| {2052        defer gpa.free(conf_path);2053        if (std.Io.Dir.openFile(.cwd(), io, conf_path, .{})) |f| {2054            f.close(io);2055        } else |_| {2056            try firstRunWizard(gpa, io, environ);2057            errors.error_info.reset();2058        }2059    } else |_| {}20602061    output.setupCheck();2062    const status = exec.checkNixFeatures(gpa, io, environ);2063    output.setupFeatures(status.nix_command, status.flakes);20642065    if (status.allEnabled()) {2066        output.setupAllSet();2067        api.ensureRegistryPinned(gpa, io, environ);2068        return;2069    }20702071    // On NixOS the features belong in configuration.nix (the declarative,2072    // permanent home), not ~/.config/nix/nix.conf. Offer to add the one line;2073    // the user runs the rebuild. We don't pin the registry here because the2074    // features aren't live until that rebuild lands.2075    if (exec.isNixOS(io)) {2076        const conf_path = "/etc/nixos/configuration.nix";2077        if (exec.nixosConfigEnablesFeatures(gpa, io, conf_path)) {2078            output.setupNixosNeedsRebuild(conf_path);2079            return;2080        }2081        output.setupNixosOffer(exec.NIXOS_FEATURES_LINE, conf_path);2082        if (output.confirmDefaultNo("add it now?")) {2083            if (exec.appendFeaturesToNixosConfig(gpa, io, environ, conf_path)) |_| {2084                output.setupNixosWrote(conf_path);2085            } else |_| {2086                output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);2087            }2088        } else {2089            output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);2090        }2091        return;2092    }20932094    // Non-NixOS: a user-level nix.conf takes effect immediately, no sudo needed.2095    output.setupEnabling();2096    const path = try exec.enableNixFeatures(gpa, io, environ);2097    defer gpa.free(path);20982099    output.setupDone(path);2100    api.ensureRegistryPinned(gpa, io, environ);2101}21022103// --- Log helper ---21042105fn logAction(ctx: Ctx, action: []const u8, gen: u32) void {2106    var ts_buf: [32]u8 = undefined;2107    const ts = nowIso(ctx.io, &ts_buf);2108    var buf: [256]u8 = undefined;2109    const entry = std.fmt.bufPrint(&buf, "{{\"ts\":\"{s}\",\"machine\":\"{s}\",\"command\":\"{s}\",\"outcome\":\"success\",\"gen_before\":null,\"gen_after\":{d},\"duration_ms\":0}}\n", .{2110        ts, ctx.machine.name, action, gen,2111    }) catch return;2112    exec.appendNinaLog(ctx.io, ctx.environ, entry);2113}21142115// Wall-clock UTC as ISO-8601. Uses Io.Clock.real (the settable Unix-epoch clock);2116// Io.Clock.awake is monotonic and unsuitable for timestamps. Falls back to epoch 0.2117fn nowIso(io: std.Io, buf: []u8) []const u8 {2118    const fallback = "1970-01-01T00:00:00Z";2119    const ns = std.Io.Clock.real.now(io).toNanoseconds();2120    if (ns <= 0) return fallback;2121    const secs: u64 = @intCast(@divFloor(ns, 1_000_000_000));2122    const es = std.time.epoch.EpochSeconds{ .secs = secs };2123    const ed = es.getEpochDay();2124    const yd = ed.calculateYearDay();2125    const md = yd.calculateMonthDay();2126    const ds = es.getDaySeconds();2127    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", .{2128        yd.year,              md.month.numeric(),      @as(u32, md.day_index) + 1,2129        ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(),2130    }) catch return fallback;2131}