commands.zig

81.0 KB · raw

1// commands.zig — all command handlers2// Orchestrates exec/api/output. Zero direct stdout writes.3const std = @import("std");4const builtin = @import("builtin");5const types = @import("types.zig");6const errors = @import("errors.zig");7const config = @import("config.zig");8const output = @import("output.zig");9const exec = @import("exec.zig");10const api = @import("api.zig");11const search_tui = @import("search.zig");12const version = @import("version.zig");1314const UPDATE_URL = "https://kepr.uk/api/nina/releases/latest";1516const Semver = struct {17    major: u32,18    minor: u32,19    patch: u32,20};2122pub const Ctx = struct {23    gpa: std.mem.Allocator,24    io: std.Io,25    environ: *const std.process.Environ.Map,26    machine: types.Machine,27    cfg: types.NinaConfig,28    args: []const []const u8, // positional args after subcommand29    sub: []const u8, // subcommand (e.g. "list" in "service list")30    dry: bool,31    check: bool,32    no_apply: bool,33    all: bool,34    last: u32,35    json: bool,36    user: bool, // --user: operate on user (vs system) services37};3839// A system is flake-managed when the config says so OR a flake.nix is present in40// the config dir. Detection means a fresh channel user who points nina at a flake41// dir gets the right behavior without editing config first.42fn flakeSystem(ctx: Ctx) bool {43    return ctx.cfg.flake or exec.configHasFlake(ctx.gpa, ctx.io, &ctx.machine);44}4546fn runPreHook(ctx: Ctx, hook_name: []const u8) !bool {47    const hook = try exec.runHook(ctx.gpa, ctx.io, ctx.environ, hook_name);48    defer ctx.gpa.free(hook.output);49    switch (hook.result) {50        .not_found, .ok => return true,51        .failed => {52            output.hookFailed(hook_name, hook.exit_code, hook.output);53            return output.confirmDefaultNo("continue anyway?");54        },55    }56}5758fn runPostHook(ctx: Ctx, hook_name: []const u8) void {59    const hook = exec.runHook(ctx.gpa, ctx.io, ctx.environ, hook_name) catch return;60    defer ctx.gpa.free(hook.output);61    if (hook.result == .failed) {62        output.hookWarning(hook_name, hook.exit_code, hook.output);63    }64}6566pub fn apply(ctx: Ctx) !void {67    if (ctx.dry) {68        output.applyDry(ctx.machine.name);69        const code = try exec.nixosRebuildDryActivate(ctx.io, &ctx.machine, ctx.gpa);70        if (code != 0) return error.BuildFailed;71        output.applyDryDone();72        return;73    }74    if (ctx.check) {75        return check(ctx);76    }7778    if (!try runPreHook(ctx, "pre-apply")) {79        output.aborted();80        return error.HookAborted;81    }8283    output.applyStart(ctx.machine.name);84    output.buildPanelInit();85    const start = std.Io.Clock.awake.now(ctx.io);8687    var panel = output.BuildPanel{};88    const code = exec.nixosRebuildSwitchWithPanel(ctx.io, &ctx.machine, ctx.gpa, &panel) catch |e| {89        output.buildPanelClear();90        exec.markApplyFailed(ctx.io, ctx.environ);91        return e;92    };93    output.buildPanelClear();9495    if (code != 0) {96        exec.markApplyFailed(ctx.io, ctx.environ);97        return error.BuildFailed;98    }99100    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());101    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));102    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;103    const after_failure = exec.takeApplyFailed(ctx.io, ctx.environ);104    output.applyDone(gen, elapsed, after_failure);105    // Show any nix warnings collected during the build (dim yellow, after success line).106    const warnings = errors.extractWarnings(ctx.gpa, errors.getBuildStderr()) catch &.{};107    defer {108        for (warnings) |w| ctx.gpa.free(w);109        ctx.gpa.free(warnings);110    }111    if (warnings.len > 0) output.buildWarnings(warnings);112    runPostHook(ctx, "post-apply");113    logAction(ctx, "apply", gen);114}115116pub fn check(ctx: Ctx) !void {117    output.checkStart(ctx.machine.name);118    const code = try exec.nixosRebuildBuild(ctx.io, &ctx.machine, ctx.gpa);119    if (code != 0) return error.BuildFailed;120    output.checkOk();121}122123pub fn back(ctx: Ctx) !void {124    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);125    defer ctx.gpa.free(gens);126127    var current: u32 = 0;128    for (gens) |g| if (g.current) {129        current = g.number;130    };131132    // Newest generation older than current. If there is none, we're already at the133    // oldest — stop cleanly instead of letting rollback fail with 'build failed'.134    var prev: u32 = 0;135    var has_prev = false;136    for (gens) |g| {137        if (g.number < current and (!has_prev or g.number > prev)) {138            prev = g.number;139            has_prev = true;140        }141    }142    if (!has_prev) {143        output.alreadyOldest();144        return;145    }146147    if (!try runPreHook(ctx, "pre-back")) {148        output.aborted();149        return error.HookAborted;150    }151152    output.backStart(ctx.machine.name, current, prev);153    if (ctx.cfg.confirm and !output.confirm("")) return;154155    // Flake systems don't have <nixos-config> in the Nix search path, so156    // `nixos-rebuild --rollback` fails. Switch by generation number instead157    // (same path as `nina go N`), which works for both channel and flake.158    const code = if (flakeSystem(ctx))159        try exec.switchGeneration(ctx.io, &ctx.machine, ctx.gpa, prev)160    else161        try exec.rollback(ctx.io, &ctx.machine, ctx.gpa);162    if (code != 0) return error.BuildFailed;163    output.backDone(prev);164    runPostHook(ctx, "post-back");165}166167pub fn go(ctx: Ctx) !void {168    if (ctx.args.len == 0) return error.Internal;169    const target = std.fmt.parseInt(u32, ctx.args[0], 10) catch return error.Internal;170    const current = try exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine);171172    output.goStart(ctx.machine.name, current, target);173    if (ctx.cfg.confirm and !output.confirm("")) return;174175    const code = try exec.switchGeneration(ctx.io, &ctx.machine, ctx.gpa, target);176    if (code != 0) return error.ProcessFailed;177    output.generationDone(target);178}179180pub fn history(ctx: Ctx) !void {181    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);182    defer ctx.gpa.free(gens);183    output.historyHeader(ctx.machine.name);184    for (gens) |g| output.historyRow(g);185}186187const gen_help = [_][2][]const u8{188    .{ "list", "list generations" },189    .{ "current", "show current generation" },190    .{ "delete <n>", "delete generation n" },191    .{ "delete old", "delete old generations" },192};193194pub fn genCmd(ctx: Ctx) !void {195    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("gen", &gen_help, null);196    if (std.mem.eql(u8, ctx.sub, "list")) return history(ctx);197    if (std.mem.eql(u8, ctx.sub, "current")) {198        const n = try exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine);199        output.genCurrent(n);200        return;201    }202    if (std.mem.eql(u8, ctx.sub, "delete")) {203        if (ctx.args.len == 0) return error.Internal;204        if (std.mem.eql(u8, ctx.args[0], "old")) {205            if (ctx.cfg.confirm and !output.confirm("")) return;206            _ = try exec.deleteOldGenerations(ctx.io, &ctx.machine, ctx.gpa);207        } else {208            const n = std.fmt.parseInt(u32, ctx.args[0], 10) catch return error.Internal;209            if (ctx.cfg.confirm and !output.confirm("")) return;210            _ = try exec.deleteGeneration(ctx.io, &ctx.machine, ctx.gpa, n);211        }212        output.done();213        return;214    }215    return error.Internal;216}217218pub fn clean(ctx: Ctx) !void {219    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);220    defer ctx.gpa.free(gens);221    const all = ctx.all or std.mem.eql(u8, ctx.sub, "all");222    const total: u32 = @intCast(gens.len);223    // `clean all` keeps only the current generation; otherwise keep the configured224    // count. With nothing older than the keep limit, there's nothing to collect.225    const keep: u32 = if (all) 1 else ctx.cfg.generations;226    if (total <= keep) {227        output.cleanNothing(ctx.machine.name, total);228        return;229    }230    output.cleanStart(ctx.machine.name, keep, total);231    if (ctx.cfg.confirm and !output.confirm("removing — cannot be undone")) return;232    _ = try exec.collectGarbage(ctx.io, &ctx.machine, ctx.gpa, all, ctx.cfg.generations);233    output.cleanDone();234}235236pub fn statusCmd(ctx: Ctx) !void {237    output.statusHeader();238    // --all renders every configured machine; remotes route through the same SSH239    // path as exec.capture. An unreachable machine is shown in red, not fatal.240    if (ctx.all and ctx.cfg.machines.len > 0) {241        for (ctx.cfg.machines) |m| statusRowFor(ctx, &m);242    } else {243        statusRowFor(ctx, &ctx.machine);244    }245    homeStatusLine(ctx);246}247248// When standalone Home Manager is present, show its current generation as a dim249// line indented under the machine rows. Gated on standalone mode (the only mode250// where we can read a generation), so a machine without HM is unaffected.251fn homeStatusLine(ctx: Ctx) void {252    if (exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ) != .standalone) return;253    const out = exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine) catch return;254    defer ctx.gpa.free(out);255    const gens = parseHomeGenerations(ctx.gpa, out) catch return;256    defer freeHomeGens(ctx.gpa, gens);257    if (gens.len == 0) return;258    output.statusHomeRow(gens[0].number, gens[0].date);259}260261fn statusRowFor(ctx: Ctx, machine: *const types.Machine) void {262    // A failure to read the current generation means we couldn't reach or query263    // the machine — mark it unreachable rather than reporting a bogus gen 0.264    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, machine) catch {265        output.statusRow(machine.name, 0, "", "", false);266        return;267    };268    const st = exec.systemStatus(ctx.gpa, ctx.io, machine);269    defer ctx.gpa.free(st.size);270    defer ctx.gpa.free(st.age);271    output.statusRow(machine.name, gen, st.age, st.size, true);272}273274pub fn diff(ctx: Ctx) !void {275    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);276    defer ctx.gpa.free(gens);277    var current: u32 = 0;278    var prev: u32 = 0;279    for (gens) |g| {280        if (g.current) current = g.number;281        if (!g.current and g.number > prev and g.number < current) prev = g.number;282    }283    if (ctx.args.len >= 2) {284        const a = std.fmt.parseInt(u32, ctx.args[0], 10) catch current - 1;285        const b = std.fmt.parseInt(u32, ctx.args[1], 10) catch current;286        output.diffHeader(a, b, ctx.machine.name);287        if (try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, a, b) != 0) return error.ProcessFailed;288    } else {289        output.diffHeader(if (prev > 0) prev else current - 1, current, ctx.machine.name);290        if (try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, if (prev > 0) prev else current - 1, current) != 0) return error.ProcessFailed;291    }292}293294pub fn mood(ctx: Ctx) !void {295    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;296    const st = exec.systemStatus(ctx.gpa, ctx.io, &ctx.machine);297    defer ctx.gpa.free(st.size);298    defer ctx.gpa.free(st.age);299    const state = exec.systemRunningState(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");300    defer ctx.gpa.free(state);301    output.mood(ctx.machine.name, state, gen, st.age, st.size);302}303304pub fn doctor(ctx: Ctx) !void {305    output.doctorHeader(ctx.machine.name);306    const checks = try exec.runDoctorChecks(ctx.gpa, ctx.io, &ctx.machine);307    defer ctx.gpa.free(checks);308    var warnings: u32 = 0;309    var failures: u32 = 0;310    for (checks) |ch| {311        output.doctorRow(ch);312        if (ch.status == .warn) warnings += 1;313        if (ch.status == .fail) failures += 1;314    }315316    // Home Manager row only when present — absent on a machine without HM, so317    // doctor's table is unchanged there.318    const hm_mode = exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ);319    if (hm_mode != .none) {320        const note = homeDoctorNote(ctx, hm_mode);321        defer ctx.gpa.free(note);322        output.doctorRow(.{ .name = "home manager", .status = .ok, .note = note });323    }324325    output.doctorSummary(warnings, failures);326}327328// "standalone  gen 765" / "module" — the note shown in doctor's home manager row.329// Caller owns the returned slice.330fn homeDoctorNote(ctx: Ctx, mode: exec.HomeManagerMode) []const u8 {331    const label = switch (mode) {332        .standalone => "standalone",333        .module => "module",334        .none => "",335    };336    if (mode == .standalone) {337        const gen = homeCurrentGen(ctx);338        if (gen != 0)339            return std.fmt.allocPrint(ctx.gpa, "{s}  gen {d}", .{ label, gen }) catch340                (ctx.gpa.dupe(u8, label) catch "");341    }342    return ctx.gpa.dupe(u8, label) catch "";343}344345// nina update — kepr self-update for the nina binary itself.346pub fn update(ctx: Ctx) !void {347    output.updateSelfStart();348349    if (comptime std.mem.eql(u8, version.PLATFORM, "unsupported")) {350        output.updateSelfNoPlatform(@tagName(builtin.cpu.arch) ++ "-" ++ @tagName(builtin.os.tag));351        return error.Internal;352    }353354    const env_url = ctx.environ.get("NINA_UPDATE_SOURCE");355    const source_url = env_url orelse UPDATE_URL;356357    const body = exec.fetchUrl(ctx.gpa, ctx.io, source_url) catch |e| switch (e) {358        error.NetworkError, error.HttpError => {359            output.updateSelfNetworkError();360            return;361        },362        else => return e,363    };364    defer ctx.gpa.free(body);365366    const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, body, .{}) catch {367        output.printWarning("could not parse release metadata");368        return;369    };370    defer parsed.deinit();371372    const root = parsed.value;373    if (root != .object) {374        output.printWarning("malformed release metadata");375        return;376    }377378    const remote_ver = blk: {379        const v = root.object.get("version") orelse {380            output.printWarning("malformed release metadata");381            return;382        };383        break :blk switch (v) {384            .string => |s| s,385            else => {386                output.printWarning("malformed release metadata");387                return;388            },389        };390    };391    if (!remoteVersionNewer(version.VERSION, remote_ver)) {392        output.updateSelfCurrent(version.VERSION);393        return;394    }395396    const release_notes = try updateReleaseNotes(ctx.gpa, ctx.io, root, source_url, version.VERSION, remote_ver);397    defer ctx.gpa.free(release_notes);398399    output.updateSelfAvailable(version.VERSION, remote_ver);400    output.updateSelfReleaseNotes(release_notes);401    if (ctx.check) return;402403    var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;404    const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {405        errors.error_info.setMessage("could not determine install path", .{});406        return error.Internal;407    };408409    // When running from the nix store, defer to nix profile upgrade so nix410    // manages the transition (the store is read-only; binary replacement fails).411    // A NixOS system install also resolves into the store but isn't a profile412    // element, so check the profile to avoid a no-op `upgrade` — it updates with413    // the next nixos-rebuild instead.414    if (std.mem.startsWith(u8, install_path, "/nix/store/")) {415        const nina_info = exec.profileNinaInfo(ctx.gpa, ctx.io, &ctx.machine);416        defer {417            if (nina_info) |n| {418                ctx.gpa.free(n.name);419                if (n.original_url) |u| ctx.gpa.free(u);420            }421        }422        if (nina_info == null) {423            output.updateSelfNotInProfile();424            return;425        }426        const nina = nina_info.?;427        output.updateSelfNixManaged(remote_ver);428        if (ctx.cfg.confirm and !output.confirm("")) return;429        // Pass originalUrl as the installable when available. Nix 2.18+ treats a430        // bare element name as a registry lookup (e.g. nixpkgs#nina) which silently431        // no-ops for tarball installs; the original URL targets the right source.432        const upgrade_arg = nina.original_url orelse nina.name;433        const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "upgrade", upgrade_arg }) catch {434            output.updateSelfNixFailed();435            return;436        };437        if (ec != 0) {438            output.updateSelfNixFailed();439            return;440        }441        output.updateSelfDone(version.VERSION, remote_ver);442        output.updateSelfNixRehash();443        return;444    }445446    const plat_info = blk: {447        const pv = root.object.get("platforms") orelse break :blk null;448        if (pv != .object) break :blk null;449        break :blk pv.object.get(version.PLATFORM);450    };451    if (plat_info == null) {452        output.updateSelfNoPlatform(version.PLATFORM);453        return;454    }455456    const dl_url = blk: {457        const v = plat_info.?.object.get("url") orelse {458            output.printWarning("malformed release metadata");459            return;460        };461        break :blk switch (v) {462            .string => |s| s,463            else => {464                output.printWarning("malformed release metadata");465                return;466            },467        };468    };469470    const raw_cksum = blk: {471        if (plat_info.?.object.get("blake3")) |v|472            break :blk switch (v) {473                .string => |s| s,474                else => {475                    output.printWarning("malformed release metadata");476                    return;477                },478            };479        if (plat_info.?.object.get("checksum")) |v|480            break :blk switch (v) {481                .string => |s| s,482                else => {483                    output.printWarning("malformed release metadata");484                    return;485                },486            };487        output.printWarning("missing checksum in release metadata");488        return;489    };490    const expected_hex = if (std.mem.startsWith(u8, raw_cksum, "blake3:")) raw_cksum["blake3:".len..] else raw_cksum;491492    if (ctx.cfg.confirm and !output.confirm("")) return;493494    output.updateSelfDownloading(remote_ver, version.PLATFORM);495    const tmp_path = exec.downloadToTemp(ctx.gpa, ctx.io, dl_url) catch {496        output.printWarning("download failed — check your connection and try again");497        return;498    };499    defer ctx.gpa.free(tmp_path);500501    output.updateSelfVerifying();502    exec.verifyAndInstall(ctx.gpa, ctx.io, tmp_path, expected_hex, install_path) catch |e| switch (e) {503        error.ChecksumMismatch => {504            output.updateSelfChecksumFailed();505            return;506        },507        else => return e,508    };509510    output.updateSelfDone(version.VERSION, remote_ver);511}512513fn updateReleaseNotes(gpa: std.mem.Allocator, io: std.Io, root: std.json.Value, source_url: []const u8, current: []const u8, latest: []const u8) ![]u8 {514    if (releaseNotesFromMetadata(gpa, root)) |notes| {515        if (std.mem.trim(u8, notes, " \t\r\n").len > 0) return notes;516        gpa.free(notes);517    }518    return buildKeprArchiveReleaseNotes(gpa, io, source_url, current, latest) catch gpa.dupe(u8, "");519}520521fn releaseNotesFromMetadata(gpa: std.mem.Allocator, root: std.json.Value) ?[]u8 {522    if (root != .object) return null;523    // `notes` is the one canonical manifest field. The retired `release_notes`524    // and `changelog` fallbacks are gone — Kepr now emits `notes` everywhere, and525    // releases that predate `--notes` fall back to archives.json in the caller.526    const v = root.object.get("notes") orelse return null;527    return switch (v) {528        .string => |s| gpa.dupe(u8, s) catch null,529        else => null,530    };531}532533fn buildKeprArchiveReleaseNotes(gpa: std.mem.Allocator, io: std.Io, source_url: []const u8, current: []const u8, latest: []const u8) ![]u8 {534    const archive_url = try keprArchiveUrl(gpa, source_url);535    defer gpa.free(archive_url);536537    const body = exec.fetchUrl(gpa, io, archive_url) catch return gpa.dupe(u8, "");538    defer gpa.free(body);539540    return releaseNotesFromArchiveJson(gpa, body, current, latest);541}542543fn keprArchiveUrl(gpa: std.mem.Allocator, source_url: []const u8) ![]u8 {544    const scheme = std.mem.indexOf(u8, source_url, "://") orelse return error.InvalidUpdateSource;545    const path_start = std.mem.indexOfScalarPos(u8, source_url, scheme + 3, '/') orelse return error.InvalidUpdateSource;546    const origin = source_url[0..path_start];547    const path = source_url[path_start..];548    if (!std.mem.startsWith(u8, path, "/api/")) return error.InvalidUpdateSource;549550    const after_api = path["/api/".len..];551    const repo_end = std.mem.indexOfScalar(u8, after_api, '/') orelse return error.InvalidUpdateSource;552    const repo = after_api[0..repo_end];553    if (repo.len == 0) return error.InvalidUpdateSource;554555    return std.fmt.allocPrint(gpa, "{s}/{s}/archives.json?limit=100", .{ origin, repo });556}557558// Saves arrive newest-first. For each version in the update range we want the OLDEST559// save message (the one that introduced that version), not a follow-up cleanup/docs save.560// We overwrite the tracked message on each occurrence, so the final stored value per561// version is always the oldest (last-seen in a newest-first stream).562fn releaseNotesFromArchiveJson(gpa: std.mem.Allocator, body: []const u8, current: []const u8, latest: []const u8) ![]u8 {563    const parsed = std.json.parseFromSlice(std.json.Value, gpa, body, .{}) catch return gpa.dupe(u8, "");564    defer parsed.deinit();565566    if (parsed.value != .object) return gpa.dupe(u8, "");567    const saves_v = parsed.value.object.get("saves") orelse return gpa.dupe(u8, "");568    if (saves_v != .array) return gpa.dupe(u8, "");569570    // version string → oldest message seen (both slice into parsed JSON, valid until deinit)571    var best_msg = std.StringHashMap([]const u8).init(gpa);572    defer best_msg.deinit();573    var order: std.ArrayList([]const u8) = .empty;574    defer order.deinit(gpa);575576    for (saves_v.array.items) |save| {577        if (save != .object) continue;578        const ver_v = save.object.get("version") orelse continue;579        const msg_v = save.object.get("message") orelse continue;580        if (ver_v != .string or msg_v != .string) continue;581        const ver = ver_v.string;582        const msg = std.mem.trim(u8, msg_v.string, " \t\r\n");583        if (msg.len == 0 or !versionInUpdateRange(ver, current, latest)) continue;584585        const entry = try best_msg.getOrPut(ver);586        if (!entry.found_existing) try order.append(gpa, ver);587        // Always overwrite: saves are newest-first, so last write = oldest save = version-intro message588        entry.value_ptr.* = msg;589    }590591    if (order.items.len == 0) return gpa.dupe(u8, "");592593    var out: std.ArrayList(u8) = .empty;594    errdefer out.deinit(gpa);595    for (order.items) |ver| {596        const msg = best_msg.get(ver).?;597        // Use only the first line as the summary; multi-line saves may have implementation details below598        const summary_end = std.mem.indexOf(u8, msg, "\n") orelse msg.len;599        const summary = std.mem.trim(u8, msg[0..summary_end], " \t\r");600        if (summary.len == 0) continue;601        try appendLine(&out, gpa, "## {s}\n", .{ver});602        try appendLine(&out, gpa, "- {s}\n\n", .{summary});603    }604605    if (out.items.len == 0) {606        out.deinit(gpa);607        return gpa.dupe(u8, "");608    }609    return out.toOwnedSlice(gpa);610}611612fn appendLine(out: *std.ArrayList(u8), gpa: std.mem.Allocator, comptime template: []const u8, args: anytype) !void {613    const line = try std.fmt.allocPrint(gpa, template, args);614    defer gpa.free(line);615    try out.appendSlice(gpa, line);616}617618fn versionInUpdateRange(candidate: []const u8, current: []const u8, latest: []const u8) bool {619    const cand = parseSemver(candidate) orelse return std.mem.eql(u8, candidate, latest);620    const cur = parseSemver(current) orelse return std.mem.eql(u8, candidate, latest);621    const lat = parseSemver(latest) orelse return std.mem.eql(u8, candidate, latest);622    return compareSemver(cand, cur) == .gt and compareSemver(cand, lat) != .gt;623}624625fn remoteVersionNewer(current: []const u8, remote: []const u8) bool {626    const cur = parseSemver(current) orelse return !std.mem.eql(u8, current, remote);627    const rem = parseSemver(remote) orelse return !std.mem.eql(u8, current, remote);628    return compareSemver(rem, cur) == .gt;629}630631const VersionOrder = enum { lt, eq, gt };632633fn compareSemver(a: Semver, b: Semver) VersionOrder {634    if (a.major != b.major) return if (a.major < b.major) .lt else .gt;635    if (a.minor != b.minor) return if (a.minor < b.minor) .lt else .gt;636    if (a.patch != b.patch) return if (a.patch < b.patch) .lt else .gt;637    return .eq;638}639640fn parseSemver(raw: []const u8) ?Semver {641    const v = if (std.mem.startsWith(u8, raw, "v")) raw[1..] else raw;642    var it = std.mem.splitScalar(u8, v, '.');643    const major_s = it.next() orelse return null;644    const minor_s = it.next() orelse return null;645    const patch_s = it.next() orelse return null;646    if (it.next() != null) return null;647    return .{648        .major = std.fmt.parseInt(u32, major_s, 10) catch return null,649        .minor = std.fmt.parseInt(u32, minor_s, 10) catch return null,650        .patch = std.fmt.parseInt(u32, patch_s, 10) catch return null,651    };652}653654test "versionInUpdateRange includes only newer versions through latest" {655    try std.testing.expect(versionInUpdateRange("3.2.3", "3.1.9", "3.2.3"));656    try std.testing.expect(versionInUpdateRange("3.2.0", "3.1.9", "3.2.3"));657    try std.testing.expect(!versionInUpdateRange("3.1.9", "3.1.9", "3.2.3"));658    try std.testing.expect(!versionInUpdateRange("3.2.4", "3.1.9", "3.2.3"));659}660661test "remoteVersionNewer does not offer downgrades" {662    try std.testing.expect(remoteVersionNewer("3.2.3", "3.2.4"));663    try std.testing.expect(!remoteVersionNewer("3.2.4", "3.2.3"));664    try std.testing.expect(!remoteVersionNewer("3.2.4", "3.2.4"));665}666667test "releaseNotesFromArchiveJson uses oldest save per version" {668    // Saves arrive newest-first. For 3.2.3, the newest save is a CONTINUITY update;669    // the oldest is the version-intro message. We expect the intro message in the output.670    const body =671        \\{672        \\  "saves": [673        \\    {"version":"3.2.3","message":"wip: record verification in CONTINUITY"},674        \\    {"version":"3.2.1","message":"old release"},675        \\    {"version":"3.2.3","message":"add streaming deflate path"}676        \\  ]677        \\}678    ;679    const notes = try releaseNotesFromArchiveJson(std.testing.allocator, body, "3.2.1", "3.2.3");680    defer std.testing.allocator.free(notes);681682    try std.testing.expect(std.mem.indexOf(u8, notes, "## 3.2.3") != null);683    try std.testing.expect(std.mem.indexOf(u8, notes, "- add streaming deflate path") != null);684    try std.testing.expect(std.mem.indexOf(u8, notes, "CONTINUITY") == null);685    try std.testing.expect(std.mem.indexOf(u8, notes, "old release") == null);686}687688test "releaseNotesFromMetadata reads canonical notes and ignores retired keys" {689    const a = std.testing.allocator;690691    // Canonical field is read.692    {693        var parsed = try std.json.parseFromSlice(std.json.Value, a, "{\"notes\":\"colored progress bar\"}", .{});694        defer parsed.deinit();695        const got = releaseNotesFromMetadata(a, parsed.value).?;696        defer a.free(got);697        try std.testing.expectEqualStrings("colored progress bar", got);698    }699700    // Retired field names are no longer honoured — they fall through to null so701    // the caller drops to the archives.json derivation instead.702    {703        var parsed = try std.json.parseFromSlice(std.json.Value, a, "{\"release_notes\":\"x\",\"changelog\":\"y\"}", .{});704        defer parsed.deinit();705        try std.testing.expect(releaseNotesFromMetadata(a, parsed.value) == null);706    }707}708709// nina goodbye — clean uninstall. Three install paths:710// - nix profile (binary in nix store with a profile element) → nix profile remove711// - koh build or source build (plain binary on PATH) → delete the file712pub fn goodbye(ctx: Ctx) !void {713    output.goodbyeStart();714715    var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;716    const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {717        errors.error_info.setMessage("could not determine install path", .{});718        return error.Internal;719    };720721    // A binary outside the nix store is a koh build or source build — delete it.722    if (!std.mem.startsWith(u8, install_path, "/nix/store/")) {723        output.goodbyeFile(install_path);724        if (ctx.cfg.confirm and !output.confirm("")) return;725        std.Io.Dir.deleteFileAbsolute(ctx.io, install_path) catch |e| {726            errors.error_info.setMessage("could not remove {s}", .{install_path});727            return e;728        };729        output.goodbyeDone();730        return;731    }732733    // Binary is in the nix store — find and remove the profile element.734    const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);735    defer {736        if (nina_element) |n| ctx.gpa.free(n);737    }738739    if (nina_element == null) {740        errors.error_info.setMessage("nina not found in nix profile — was it installed via 'nix profile add'?", .{});741        return error.Internal;742    }743744    output.goodbyeNix();745    if (ctx.cfg.confirm and !output.confirm("")) return;746    const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "remove", nina_element.? }) catch {747        output.goodbyeFailed("nix profile remove failed");748        return;749    };750    if (ec != 0) {751        output.goodbyeFailed("nix profile remove failed");752        return;753    }754    output.goodbyeDone();755}756757fn channelUpdateCmd(ctx: Ctx) !void {758    output.updateStart(ctx.machine.name);759    _ = try exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa);760    output.updateDone();761}762763pub fn upgrade(ctx: Ctx) !void {764    if (!try runPreHook(ctx, "pre-upgrade")) {765        output.aborted();766        return error.HookAborted;767    }768769    output.upgradeStart(ctx.machine.name);770    // Flake systems update inputs (flake.lock); channel systems update channels.771    // Running nix-channel --update on a flake system is a no-op at best. The772    // rebuild below is already flake-aware via exec.nixosRebuildSwitch.773    if (flakeSystem(ctx)) {774        output.printSubstep("updating flake inputs", .{});775        _ = exec.flakeUpdateAt(ctx.io, &ctx.machine, ctx.gpa, ctx.machine.config_path) catch {};776    } else {777        output.printSubstep("updating channels", .{});778        _ = exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa) catch {};779    }780    output.printSubstep("rebuilding", .{});781    output.buildPanelInit();782    const start = std.Io.Clock.awake.now(ctx.io);783    var panel = output.BuildPanel{};784    const code = exec.nixosRebuildSwitchWithPanel(ctx.io, &ctx.machine, ctx.gpa, &panel) catch |e| {785        output.buildPanelClear();786        return e;787    };788    output.buildPanelClear();789    if (code != 0) {790        output.applyFailed("");791        return error.BuildFailed;792    }793    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());794    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));795    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;796    output.applyDone(gen, elapsed, false);797    runPostHook(ctx, "post-upgrade");798}799800pub fn log(ctx: Ctx) !void {801    output.logHeader(ctx.machine.name);802    const content = exec.readNinaLog(ctx.gpa, ctx.io, ctx.environ, ctx.last) catch {803        // No log yet — that's fine804        return;805    };806    defer ctx.gpa.free(content);807    var lines = std.mem.splitScalar(u8, content, '\n');808    while (lines.next()) |line| {809        const t = std.mem.trim(u8, line, " \t\r");810        if (t.len == 0) continue;811        if (t[0] == '{') {812            renderJsonLogLine(ctx.gpa, t);813        } else {814            // legacy tab-separated format815            var parts = std.mem.tokenizeScalar(u8, t, '\t');816            const date = parts.next() orelse continue;817            const time = parts.next() orelse "";818            const action = parts.next() orelse "";819            const detail = parts.next() orelse "";820            output.logRow(date, time, action, detail);821        }822    }823}824825// The on-disk log is JSON Lines: {"ts","machine","command","outcome","gen_after",...}.826// Render ts -> date/time columns, command -> action, outcome(+gen) -> detail.827fn renderJsonLogLine(gpa: std.mem.Allocator, line: []const u8) void {828    const parsed = std.json.parseFromSlice(std.json.Value, gpa, line, .{}) catch {829        output.logRow(line, "", "", ""); // unparseable — show raw rather than drop830        return;831    };832    defer parsed.deinit();833    if (parsed.value != .object) return;834    const o = parsed.value.object;835836    const ts = jsonStr(o, "ts");837    const date = if (ts.len >= 10) ts[0..10] else ts;838    const time = if (ts.len >= 16) ts[11..16] else "";839    const action = jsonStr(o, "command");840    const outcome = jsonStr(o, "outcome");841842    var buf: [160]u8 = undefined;843    var detail: []const u8 = outcome;844    if (o.get("gen_after")) |g| {845        if (g == .integer) {846            detail = std.fmt.bufPrint(&buf, "{s}   -> gen {d}", .{ outcome, g.integer }) catch outcome;847        }848    }849    output.logRow(date, time, action, detail);850}851852fn jsonStr(o: std.json.ObjectMap, key: []const u8) []const u8 {853    if (o.get(key)) |v| {854        if (v == .string) return v.string;855    }856    return "";857}858859pub fn edit(ctx: Ctx) !void {860    // `edit` is multi-word, so a bare positional ("hardware") arrives as ctx.sub.861    // hardware-configuration.nix is generated by nixos-generate-config and warns862    // against hand-editing — refuse rather than silently opening the wrong file.863    if (std.mem.eql(u8, ctx.sub, "hardware")) {864        output.editHardwareWarning();865        return;866    }867868    // --dir opens the whole config directory (for editors that work better with869    // a folder open), as root so root-owned config trees like /etc/nixos work.870    var open_dir = false;871    for (ctx.args) |arg| {872        if (std.mem.eql(u8, arg, "--dir")) open_dir = true;873    }874    if (open_dir) {875        output.editOpen(ctx.machine.config_path, ctx.cfg.editor);876        _ = try exec.openEditorSudo(ctx.io, ctx.gpa, ctx.cfg.editor, ctx.machine.config_path);877        return;878    }879880    const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});881    defer ctx.gpa.free(path);882    output.editOpen(path, ctx.cfg.editor);883    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);884}885886pub fn fmt(ctx: Ctx) !void {887    const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});888    defer ctx.gpa.free(path);889    if (ctx.check) {890        const code = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, true);891        if (code != 0) output.fmtNeedsFormat() else output.fmtDone();892        return;893    }894    output.fmtStart(path);895    _ = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, false);896    output.fmtDone();897}898899pub fn repl(ctx: Ctx) !void {900    output.replStart();901    _ = try exec.nixRepl(ctx.io, &ctx.machine, ctx.gpa);902}903904pub fn develop(ctx: Ctx) !void {905    if (std.mem.eql(u8, ctx.sub, "show")) {906        _ = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, null);907        return;908    }909    const run_cmd: ?[]const u8 = if (ctx.args.len > 0 and std.mem.eql(u8, ctx.sub, "run"))910        ctx.args[0]911    else912        null;913    output.developStart(&.{});914    _ = try exec.nixDevelopPs1(ctx.io, &ctx.machine, ctx.gpa, run_cmd, ctx.environ);915    output.developDone();916}917918pub fn info(ctx: Ctx) !void {919    output.infoHeader(ctx.machine.name);920    const nixos_ver = exec.systemInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");921    defer ctx.gpa.free(nixos_ver);922    output.infoRow("nixos", std.mem.trim(u8, nixos_ver, " \t\n\r"));923924    const kernel = exec.kernelInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");925    defer ctx.gpa.free(kernel);926    output.infoRow("kernel", std.mem.trim(u8, kernel, " \t\n\r"));927928    const uptime = exec.uptimeInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");929    defer ctx.gpa.free(uptime);930    output.infoRow("uptime", std.mem.trim(u8, uptime, " \t\n\r"));931}932933pub fn boot(ctx: Ctx) !void {934    output.bootHeader(ctx.machine.name);935    const entries = exec.bootEntries(ctx.gpa, ctx.io, &ctx.machine) catch &.{};936    defer ctx.gpa.free(entries);937    for (entries, 0..) |entry, i| output.bootEntry(entry, i);938}939940pub fn searchCmd(ctx: Ctx) !void {941    const query = if (ctx.args.len > 0) ctx.args[0] else "";942    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);943    const selected = try search_tui.run(ctx.gpa, ctx.io, query, .packages);944    if (selected) |npkg| try selectAndInstall(ctx, npkg);945}946947pub fn optionCmd(ctx: Ctx) !void {948    const query = if (ctx.args.len > 0) ctx.args[0] else "";949    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);950    _ = try search_tui.run(ctx.gpa, ctx.io, query, .options);951}952953pub fn install(ctx: Ctx) !void {954    const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;955956    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);957958    // Search for the package to get the attr959    const pkgs = api.searchPackages(ctx.gpa, ctx.io, pkg_name) catch {960        errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});961        errors.error_info.setSuggestion("nina search {s}", .{pkg_name});962        return error.PackageNotFound;963    };964965    if (pkgs.len == 0) {966        // No matches — likely a typo. Suggest the closest real package and offer it.967        if (closestPackage(ctx, pkg_name)) |sugg| {968            output.didYouMean(pkg_name, sugg.pname);969            if (output.confirm("")) try selectAndInstall(ctx, sugg);970            return;971        }972        errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});973        errors.error_info.setSuggestion("nina search {s}", .{pkg_name});974        return error.PackageNotFound;975    }976977    // Prefer an exact name match over the first search result — `install ripgrep`978    // must pick "ripgrep", not the alphabetically-first match like "repgrep".979    var found = pkgs[0];980    for (pkgs) |p| {981        if (std.mem.eql(u8, p.pname, pkg_name)) {982            found = p;983            break;984        }985    }986    try selectAndInstall(ctx, found);987}988989// Find the real package whose name is closest to a not-found query (typo help).990// Typos usually keep the leading characters, so gather candidates with a prefix991// search and rank by edit distance; return the best only if it's typo-close.992fn closestPackage(ctx: Ctx, query: []const u8) ?types.NixPackage {993    if (query.len < 2) return null;994    var candidates = api.searchPackages(ctx.gpa, ctx.io, query[0..@min(query.len, 4)]) catch &.{};995    if (candidates.len == 0 and query.len > 2) {996        candidates = api.searchPackages(ctx.gpa, ctx.io, query[0..2]) catch &.{};997    }998    if (candidates.len == 0) return null;9991000    var best: ?types.NixPackage = null;1001    var best_dist: usize = std.math.maxInt(usize);1002    for (candidates) |p| {1003        const d = editDistance(query, p.pname);1004        if (d > 0 and d < best_dist) {1005            best_dist = d;1006            best = p;1007        }1008    }1009    // Only suggest a genuinely close name, scaled to query length.1010    const threshold = @max(@as(usize, 2), query.len / 3);1011    return if (best_dist <= threshold) best else null;1012}10131014// Case-insensitive Levenshtein distance. Names longer than the row buffer are1015// treated as far away (never suggested).1016fn editDistance(a: []const u8, b: []const u8) usize {1017    const n = b.len;1018    if (a.len == 0) return n;1019    if (n == 0) return a.len;1020    if (n + 1 > 128) return std.math.maxInt(usize);1021    var prev: [128]usize = undefined;1022    var curr: [128]usize = undefined;1023    var j: usize = 0;1024    while (j <= n) : (j += 1) prev[j] = j;1025    var i: usize = 1;1026    while (i <= a.len) : (i += 1) {1027        curr[0] = i;1028        j = 1;1029        while (j <= n) : (j += 1) {1030            const cost: usize = if (std.ascii.toLower(a[i - 1]) == std.ascii.toLower(b[j - 1])) 0 else 1;1031            curr[j] = @min(prev[j] + 1, @min(curr[j - 1] + 1, prev[j - 1] + cost));1032        }1033        @memcpy(prev[0 .. n + 1], curr[0 .. n + 1]);1034    }1035    return prev[n];1036}10371038test "editDistance is case-insensitive Levenshtein" {1039    try std.testing.expectEqual(@as(usize, 1), editDistance("firefux", "firefox"));1040    try std.testing.expectEqual(@as(usize, 0), editDistance("git", "GIT"));1041    try std.testing.expectEqual(@as(usize, 2), editDistance("fierfox", "firefox"));1042    try std.testing.expectEqual(@as(usize, 7), editDistance("", "firefox"));1043}10441045// Prompt for the install method (profile / system / try) and dispatch. Shared by1046// `nina install <pkg>` and the search widget's Enter-to-select — the letter keys1047// are read here, after the search widget's raw mode is gone, so they don't1048// collide with typing a query.1049fn selectAndInstall(ctx: Ctx, npkg: types.NixPackage) !void {1050    output.installSelectPrompt(npkg.pname, npkg.version);10511052    var choice_buf: [8]u8 = undefined;1053    var choice_len: usize = 0;1054    while (choice_len < choice_buf.len) {1055        const n = std.posix.read(std.posix.STDIN_FILENO, choice_buf[choice_len .. choice_len + 1]) catch break;1056        if (n == 0) break;1057        if (choice_buf[choice_len] == '\n') break;1058        choice_len += 1;1059    }1060    const choice = std.mem.trim(u8, choice_buf[0..choice_len], " \t");10611062    if (choice.len == 0 or choice[0] == 'i' or choice[0] == 'I') {1063        try profileInstallPkg(ctx, npkg);1064    } else if (choice[0] == 's' or choice[0] == 'S') {1065        try systemInstallPkg(ctx, npkg);1066    } else if (choice[0] == 't' or choice[0] == 'T') {1067        try tryPkg(ctx, npkg);1068    }1069}10701071fn profileInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {1072    output.installStart(npkg.pname, .profile);1073    output.printSubstep("nix profile add nixpkgs#{s}", .{npkg.attr});1074    output.printTeach(try std.fmt.allocPrint(ctx.gpa, "nix profile add nixpkgs#{s}", .{npkg.attr}));1075    const code = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, npkg.attr);1076    if (code != 0) return error.ProcessFailed;1077    output.installDone(npkg.pname);1078}10791080fn systemInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {1081    const config_path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});1082    defer ctx.gpa.free(config_path);1083    const line = api.findSystemPackagesLine(ctx.io, config_path) orelse 1;1084    output.installEditorPrompt(npkg.pname, config_path, line, ctx.cfg.editor);1085    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, config_path, line);1086    if (ctx.cfg.confirm) {1087        if (output.confirm("apply now? ")) {1088            try apply(ctx);1089        }1090    }1091}10921093fn tryPkg(ctx: Ctx, npkg: types.NixPackage) !void {1094    output.tryStart(npkg.pname);1095    output.printSubstep("nix shell nixpkgs#{s}", .{npkg.attr});1096    output.tryExitHint();1097    _ = try exec.nixShellPs1(ctx.io, &ctx.machine, ctx.gpa, npkg.attr, ctx.environ);1098    output.tryDone();1099}11001101pub fn remove(ctx: Ctx) !void {1102    const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1103    output.removeStart(pkg_name);1104    const code = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, pkg_name);1105    if (code != 0) return error.ProcessFailed;1106    output.done();1107}11081109pub fn list(ctx: Ctx) !void {1110    output.listHeader(ctx.machine.name);11111112    // Profile packages: parse `nix profile list --json` into clean name+version1113    // rows instead of dumping nix's verbose multi-line "Name:/Flake attribute:"1114    // blocks.1115    if (exec.profileListJson(ctx.gpa, ctx.io, &ctx.machine) catch null) |json| {1116        defer ctx.gpa.free(json);1117        output.listSection("profile");1118        renderProfileJson(ctx.gpa, json);1119    }11201121    // System packages: the references of /run/current-system/sw, each a1122    // <hash>-<name>-<version> store path.1123    if (exec.systemPackagePaths(ctx.gpa, ctx.io, &ctx.machine) catch null) |paths| {1124        defer ctx.gpa.free(paths);1125        output.blankLine();1126        output.listSection("system");1127        var lines = std.mem.splitScalar(u8, paths, '\n');1128        while (lines.next()) |line| {1129            const t = std.mem.trim(u8, line, " \t\r");1130            if (t.len == 0) continue;1131            const row = pkgFromStorePath(t);1132            // Skip support paths with no parseable version (man pages, wrappers).1133            if (row.version.len == 0) continue;1134            output.listPkg(row.name, row.version);1135        }1136    }1137}11381139const PkgRow = struct { name: []const u8, version: []const u8 };11401141// Split a nix store path basename (<hash>-<name>-<version>) into name + version.1142// Version begins at the first '-' followed by a digit, which reliably lands on1143// the name/version boundary since the 32-char hash and package names start with1144// non-digits.1145fn pkgFromStorePath(path: []const u8) PkgRow {1146    const base = std.fs.path.basename(path);1147    const after_hash = if (base.len > 33 and base[32] == '-') base[33..] else base;1148    var i: usize = 0;1149    while (i + 1 < after_hash.len) : (i += 1) {1150        if (after_hash[i] == '-' and std.ascii.isDigit(after_hash[i + 1])) {1151            return .{ .name = after_hash[0..i], .version = stripOutputSuffix(after_hash[i + 1 ..]) };1152        }1153    }1154    return .{ .name = after_hash, .version = "" };1155}11561157// Multi-output derivations append the output name to the store path (e.g.1158// curl-8.20.0-bin, less-692-man). Strip that suffix so the version column reads1159// as just the version.1160fn stripOutputSuffix(ver: []const u8) []const u8 {1161    const suffixes = [_][]const u8{ "-bin", "-man", "-dev", "-doc", "-lib", "-info", "-out", "-static", "-devdoc" };1162    for (suffixes) |s| {1163        if (std.mem.endsWith(u8, ver, s)) return ver[0 .. ver.len - s.len];1164    }1165    return ver;1166}11671168test "pkgFromStorePath splits name and version at first dash-digit" {1169    const a = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-ripgrep-15.1.0");1170    try std.testing.expectEqualStrings("ripgrep", a.name);1171    try std.testing.expectEqualStrings("15.1.0", a.version);11721173    const b = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-helix-25.01");1174    try std.testing.expectEqualStrings("helix", b.name);1175    try std.testing.expectEqualStrings("25.01", b.version);11761177    // multi-output store paths drop their output-name suffix1178    const c = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-curl-8.20.0-bin");1179    try std.testing.expectEqualStrings("curl", c.name);1180    try std.testing.expectEqualStrings("8.20.0", c.version);1181}11821183fn firstStorePath(el: std.json.Value) ?[]const u8 {1184    if (el != .object) return null;1185    const sp = el.object.get("storePaths") orelse return null;1186    if (sp != .array or sp.array.items.len == 0) return null;1187    const first = sp.array.items[0];1188    return if (first == .string) first.string else null;1189}11901191// `nix profile list --json` has two shapes across nix versions: newer keys each1192// element by name (object), older lists them positionally (array). Handle both.1193fn renderProfileJson(gpa: std.mem.Allocator, json: []const u8) void {1194    const parsed = std.json.parseFromSlice(std.json.Value, gpa, json, .{}) catch return;1195    defer parsed.deinit();1196    if (parsed.value != .object) return;1197    const elements = parsed.value.object.get("elements") orelse return;1198    switch (elements) {1199        .object => |obj| {1200            var it = obj.iterator();1201            while (it.next()) |entry| {1202                const ver = if (firstStorePath(entry.value_ptr.*)) |p| pkgFromStorePath(p).version else "";1203                output.listPkg(entry.key_ptr.*, ver);1204            }1205        },1206        .array => |arr| {1207            for (arr.items) |el| {1208                const path = firstStorePath(el) orelse continue;1209                const row = pkgFromStorePath(path);1210                output.listPkg(row.name, row.version);1211            }1212        },1213        else => {},1214    }1215}12161217pub fn tryCmd(ctx: Ctx) !void {1218    const pkg_name_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1219    const shell_pkg = types.NixPackage{ .attr = pkg_name_arg, .pname = pkg_name_arg, .version = "", .description = "" };1220    try tryPkg(ctx, shell_pkg);1221}12221223// --- Home Manager commands ---12241225const home_help = [_][2][]const u8{1226    .{ "init", "set up home manager for the first time" },1227    .{ "init --switch", "set up and activate immediately" },1228    .{ "apply", "apply home-manager configuration" },1229    .{ "apply --dry", "preview changes without activating" },1230    .{ "back", "roll back one generation" },1231    .{ "history", "list all generations" },1232    .{ "edit", "open home.nix" },1233    .{ "check", "validate without applying" },1234    .{ "diff", "compare the latest two generations" },1235    .{ "packages", "list managed packages" },1236};12371238const HomeGen = struct {1239    number: u32,1240    date: []const u8,1241    time: []const u8,1242    path: []const u8,1243};12441245// `home-manager generations` lines read:1246//   2026-06-01 11:56 : id 765 -> /nix/store/<hash>-home-manager-generation1247// Newest first, so index 0 is the current generation.1248fn parseHomeGenerations(gpa: std.mem.Allocator, out_str: []const u8) ![]HomeGen {1249    var gens: std.ArrayList(HomeGen) = .empty;1250    var lines = std.mem.splitScalar(u8, out_str, '\n');1251    while (lines.next()) |line| {1252        const t = std.mem.trim(u8, line, " \t\r");1253        if (t.len == 0) continue;1254        var it = std.mem.tokenizeAny(u8, t, " \t");1255        const date = it.next() orelse continue;1256        const time = it.next() orelse continue;1257        var number: ?u32 = null;1258        var path: []const u8 = "";1259        while (it.next()) |tok| {1260            if (std.mem.eql(u8, tok, "id")) {1261                if (it.next()) |n| number = std.fmt.parseInt(u32, n, 10) catch null;1262            } else if (std.mem.startsWith(u8, tok, "/nix/store/")) {1263                path = tok;1264            }1265        }1266        const num = number orelse continue;1267        try gens.append(gpa, .{1268            .number = num,1269            .date = try gpa.dupe(u8, date),1270            .time = try gpa.dupe(u8, time),1271            .path = try gpa.dupe(u8, path),1272        });1273    }1274    return gens.toOwnedSlice(gpa);1275}12761277fn freeHomeGens(gpa: std.mem.Allocator, gens: []HomeGen) void {1278    for (gens) |g| {1279        gpa.free(g.date);1280        gpa.free(g.time);1281        gpa.free(g.path);1282    }1283    gpa.free(gens);1284}12851286test "parseHomeGenerations reads id, date and store path" {1287    const a = std.testing.allocator;1288    const sample =1289        \\2026-06-01 11:56 : id 765 -> /nix/store/aaaa-home-manager-generation1290        \\2026-05-31 10:29 : id 764 -> /nix/store/bbbb-home-manager-generation1291    ;1292    const gens = try parseHomeGenerations(a, sample);1293    defer freeHomeGens(a, gens);1294    try std.testing.expectEqual(@as(usize, 2), gens.len);1295    try std.testing.expectEqual(@as(u32, 765), gens[0].number);1296    try std.testing.expectEqualStrings("2026-06-01", gens[0].date);1297    try std.testing.expectEqualStrings("11:56", gens[0].time);1298    try std.testing.expectEqualStrings("/nix/store/aaaa-home-manager-generation", gens[0].path);1299    try std.testing.expectEqual(@as(u32, 764), gens[1].number);1300}13011302// Current (newest) home generation number, or 0 if unavailable.1303fn homeCurrentGen(ctx: Ctx) u32 {1304    const out = exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine) catch return 0;1305    defer ctx.gpa.free(out);1306    const gens = parseHomeGenerations(ctx.gpa, out) catch return 0;1307    defer freeHomeGens(ctx.gpa, gens);1308    return if (gens.len > 0) gens[0].number else 0;1309}13101311pub fn home(ctx: Ctx) !void {1312    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help"))1313        return output.subcommandHelp("home", &home_help, null);13141315    // Home Manager manages the local user's environment. Detection (which binary,1316    // ~/.config/home-manager, $HOME/$USER for the flake ref) all read the LOCAL1317    // host, while exec routes over SSH for a remote machine — so `home --on1318    // <remote>` would decide mode/flake-ref from the wrong box. Refuse it cleanly1319    // rather than acting on a mismatch.1320    if (!ctx.machine.local) {1321        output.homeLocalOnly(ctx.machine.name);1322        return;1323    }13241325    // init runs before mode detection: its whole purpose is bootstrapping a host1326    // that has no home-manager yet, so a .none mode must not short-circuit it.1327    if (std.mem.eql(u8, ctx.sub, "init")) return homeInitCmd(ctx);13281329    const mode = exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ);1330    if (mode == .none) {1331        output.homeNotInstalled();1332        return;1333    }13341335    // apply is the only command meaningful in module mode (it redirects to1336    // `nina apply`); everything else needs the standalone home-manager CLI.1337    if (std.mem.eql(u8, ctx.sub, "apply")) return homeApply(ctx, mode);1338    // edit just opens the local home.nix — fine in module mode too.1339    if (std.mem.eql(u8, ctx.sub, "edit")) return homeEdit(ctx);13401341    if (mode == .module) {1342        output.homeModuleManaged();1343        return;1344    }13451346    if (std.mem.eql(u8, ctx.sub, "back")) return homeBack(ctx);1347    if (std.mem.eql(u8, ctx.sub, "history")) return homeHistory(ctx);1348    if (std.mem.eql(u8, ctx.sub, "check")) return homeCheck(ctx);1349    if (std.mem.eql(u8, ctx.sub, "diff")) return homeDiff(ctx);1350    if (std.mem.eql(u8, ctx.sub, "packages")) return homePackages(ctx);13511352    return output.subcommandHelp("home", &home_help, null);1353}13541355fn homePackages(ctx: Ctx) !void {1356    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1357    defer ctx.gpa.free(out);1358    const gens = try parseHomeGenerations(ctx.gpa, out);1359    defer freeHomeGens(ctx.gpa, gens);13601361    output.homePackagesHeader(ctx.machine.name);1362    if (gens.len == 0 or gens[0].path.len == 0) return;13631364    // The generation's OWN references are home-manager's activation deps1365    // (bash, coreutils, ...), not what the user installed. The user's packages1366    // live one level down, in the `…-home-manager-path` env the generation1367    // references — descend into it and list ITS references. Fall back to the1368    // generation refs if that env isn't present (older home-manager layouts).1369    const gen_refs = exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, gens[0].path) catch return;1370    defer ctx.gpa.free(gen_refs);13711372    var refs = gen_refs;1373    var env_refs: ?[]u8 = null;1374    defer if (env_refs) |e| ctx.gpa.free(e);1375    if (findHomeManagerPath(gen_refs)) |pkg_path| {1376        if (exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, pkg_path)) |e| {1377            env_refs = e;1378            refs = e;1379        } else |_| {}1380    }13811382    // Dedup by name: multi-output derivations (jq, jq-lib, jq-doc) collapse to1383    // the same name after the output suffix is stripped. Keys are slices into1384    // `refs`, valid for this function's lifetime.1385    var seen = std.StringHashMap(void).init(ctx.gpa);1386    defer seen.deinit();1387    var lines = std.mem.splitScalar(u8, refs, '\n');1388    while (lines.next()) |line| {1389        const t = std.mem.trim(u8, line, " \t\r");1390        if (t.len == 0) continue;1391        const row = pkgFromStorePath(t);1392        if (row.version.len == 0) continue;1393        if (std.mem.indexOf(u8, row.name, "home-manager") != null) continue;1394        if (seen.contains(row.name)) continue;1395        seen.put(row.name, {}) catch {};1396        output.listPkg(row.name, row.version);1397    }1398}13991400// The `…-home-manager-path` env among a generation's references — the buildEnv1401// of the user's home.packages. Returns the full store-path line, or null.1402fn findHomeManagerPath(refs: []const u8) ?[]const u8 {1403    var lines = std.mem.splitScalar(u8, refs, '\n');1404    while (lines.next()) |line| {1405        const t = std.mem.trim(u8, line, " \t\r");1406        if (std.mem.indexOf(u8, t, "home-manager-path") != null) return t;1407    }1408    return null;1409}14101411test "findHomeManagerPath picks the env, not the generation or infra" {1412    const refs =1413        \\/nix/store/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-bash-5.31414        \\/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path1415        \\/nix/store/cccccccccccccccccccccccccccccccc-coreutils-9.111416    ;1417    try std.testing.expectEqualStrings(1418        "/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path",1419        findHomeManagerPath(refs).?,1420    );1421    try std.testing.expectEqual(@as(?[]const u8, null), findHomeManagerPath("/nix/store/x-bash-5.3\n"));1422}14231424fn homeDiff(ctx: Ctx) !void {1425    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1426    defer ctx.gpa.free(out);1427    const gens = try parseHomeGenerations(ctx.gpa, out);1428    defer freeHomeGens(ctx.gpa, gens);14291430    // Need two generations and both their store paths to diff their closures.1431    if (gens.len < 2 or gens[0].path.len == 0 or gens[1].path.len == 0) {1432        output.homeNothingToDiff();1433        return;1434    }1435    const newer = gens[0];1436    const older = gens[1];1437    output.homeDiffHeader(older.number, newer.number, ctx.machine.name);1438    if (try exec.diffClosuresPaths(ctx.io, &ctx.machine, ctx.gpa, older.path, newer.path) != 0)1439        return error.ProcessFailed;1440}14411442fn homeCheck(ctx: Ctx) !void {1443    output.homeCheckStart(ctx.machine.name);1444    const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa);1445    if (code != 0) return error.BuildFailed;1446    output.homeCheckOk();1447}14481449fn homeEdit(ctx: Ctx) !void {1450    // Standalone home config lives at ~/.config/home-manager/home.nix; the same1451    // path is what detection keys on for module mode, so it resolves for both.1452    const path = exec.homeNixPath(ctx.gpa, ctx.environ) orelse {1453        errors.error_info.setMessage("could not resolve ~/.config/home-manager/home.nix", .{});1454        return error.ConfigNotFound;1455    };1456    defer ctx.gpa.free(path);1457    output.homeEditOpen(path, ctx.cfg.editor);1458    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);1459}14601461fn homeHistory(ctx: Ctx) !void {1462    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1463    defer ctx.gpa.free(out);1464    const gens = try parseHomeGenerations(ctx.gpa, out);1465    defer freeHomeGens(ctx.gpa, gens);1466    output.homeHistoryHeader(ctx.machine.name);1467    // Newest-first from home-manager; the first row is the current generation.1468    for (gens, 0..) |g, i| output.homeHistoryRow(g.number, g.date, g.time, i == 0);1469}14701471fn homeBack(ctx: Ctx) !void {1472    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1473    defer ctx.gpa.free(out);1474    const gens = try parseHomeGenerations(ctx.gpa, out);1475    defer freeHomeGens(ctx.gpa, gens);14761477    // Newest-first: [0] is current, [1] is the generation to roll back to.1478    if (gens.len < 2) {1479        output.alreadyOldest();1480        return;1481    }1482    const current = gens[0].number;1483    const prev = gens[1].number;14841485    output.homeBackStart(ctx.machine.name, current, prev);1486    if (ctx.cfg.confirm and !output.confirm("")) return;1487    const code = try exec.homeManagerRollback(ctx.io, &ctx.machine, ctx.gpa);1488    if (code != 0) return error.BuildFailed;1489    output.homeBackDone(prev);1490}14911492fn homeInitCmd(ctx: Ctx) !void {1493    var switch_on_init = false;1494    var dir: ?[]const u8 = null;1495    for (ctx.args) |arg| {1496        if (std.mem.eql(u8, arg, "--switch")) {1497            switch_on_init = true;1498        } else if (!std.mem.startsWith(u8, arg, "-")) {1499            dir = arg;1500        }1501    }15021503    // Guard only the default location — a custom dir is the user's call, and1504    // home-manager creates it. Never clobber an existing ~/.config/home-manager.1505    if (dir == null) {1506        if (exec.homeNixPath(ctx.gpa, ctx.environ)) |path| {1507            defer ctx.gpa.free(path);1508            if (exec.pathExists(ctx.io, path)) {1509                output.homeInitExists(path);1510                return;1511            }1512        }1513    }15141515    output.homeInitStart(switch_on_init, dir);1516    const code = try exec.homeManagerInit(ctx.io, &ctx.machine, ctx.gpa, switch_on_init, dir);1517    if (code != 0) return error.BuildFailed;1518    output.homeInitDone(switch_on_init);1519}15201521fn homeApply(ctx: Ctx, mode: exec.HomeManagerMode) !void {1522    // NixOS/flake module: home config is rebuilt by nixos-rebuild — redirect.1523    if (mode == .module) {1524        output.homeModuleManaged();1525        return;1526    }1527    if (ctx.dry) {1528        output.homeApplyDry(ctx.machine.name);1529        const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa);1530        if (code != 0) return error.BuildFailed;1531        output.homeApplyDryDone();1532        return;1533    }15341535    if (!try runPreHook(ctx, "pre-home")) {1536        output.aborted();1537        return error.HookAborted;1538    }15391540    output.homeApplyStart(ctx.machine.name);15411542    // Flake-based home config: switch by attribute with a graceful fallback1543    // chain. A channel-based config (no flake.nix) uses a plain switch.1544    const dir = exec.homeFlakeDir(ctx.gpa, ctx.io, ctx.environ);1545    defer if (dir) |d| ctx.gpa.free(d);1546    if (dir) |d| return homeApplyFlake(ctx, d);15471548    output.printSubstep("home-manager switch", .{});1549    const start = std.Io.Clock.awake.now(ctx.io);1550    const code = try exec.homeManagerSwitch(ctx.io, &ctx.machine, ctx.gpa);1551    if (code != 0) return error.BuildFailed;15521553    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());1554    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));1555    output.homeApplyDone(homeCurrentGen(ctx), elapsed);1556    runPostHook(ctx, "post-home");1557}15581559// Switch a flake-based home config, trying the most specific attribute first:1560//   <dir>#<user>-<arch>-<os>  →  <dir>#<user>  →  <dir>  (home-manager resolves)1561// Each fallback fires only on a missing-attribute error, never on a real build1562// failure. Mirrors how ${USER}-${system} homeConfigurations keys are written.1563fn homeApplyFlake(ctx: Ctx, dir: []const u8) !void {1564    const user = ctx.environ.get("USER") orelse "default";15651566    var refs: std.ArrayList([]const u8) = .empty;1567    defer {1568        for (refs.items) |r| ctx.gpa.free(r);1569        refs.deinit(ctx.gpa);1570    }1571    if (exec.homeManagerAttr(ctx.gpa, ctx.io, &ctx.machine, ctx.environ) catch null) |attr| {1572        defer ctx.gpa.free(attr);1573        try refs.append(ctx.gpa, try std.fmt.allocPrint(ctx.gpa, "{s}#{s}", .{ dir, attr }));1574    }1575    try refs.append(ctx.gpa, try std.fmt.allocPrint(ctx.gpa, "{s}#{s}", .{ dir, user }));1576    try refs.append(ctx.gpa, try ctx.gpa.dupe(u8, dir));15771578    const start = std.Io.Clock.awake.now(ctx.io);1579    for (refs.items, 0..) |ref, i| {1580        output.printSubstep("home-manager switch --flake {s}", .{ref});1581        switch (try exec.homeManagerSwitchFlake(ctx.io, &ctx.machine, ctx.gpa, ref)) {1582            .ok => {1583                const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());1584                const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));1585                output.homeApplyDone(homeCurrentGen(ctx), elapsed);1586                runPostHook(ctx, "post-home");1587                return;1588            },1589            // Attr not defined by the flake — drop to the next candidate.1590            .attr_missing => {1591                if (i + 1 < refs.items.len) output.homeAttrFallback(ref);1592                continue;1593            },1594            .failed => return error.BuildFailed,1595        }1596    }1597    return error.BuildFailed;1598}15991600// --- Service commands ---16011602const service_help = [_][2][]const u8{1603    .{ "list", "list running services" },1604    .{ "logs <svc>", "show service logs" },1605    .{ "status <svc>", "service status" },1606    .{ "start <svc>", "start a service" },1607    .{ "stop <svc>", "stop a service" },1608    .{ "restart <svc>", "restart a service" },1609    .{ "enable <svc>", "enable at boot" },1610    .{ "disable <svc>", "disable at boot" },1611};16121613pub fn service(ctx: Ctx) !void {1614    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");1615    if (std.mem.eql(u8, ctx.sub, "list")) {1616        output.serviceListHeader(ctx.machine.name);1617        const svcs = exec.serviceList(ctx.gpa, ctx.io, &ctx.machine, ctx.user) catch &.{};1618        defer ctx.gpa.free(svcs);1619        for (svcs) |s| output.serviceRow(s);1620        return;1621    }1622    if (std.mem.eql(u8, ctx.sub, "logs")) {1623        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1624        const follow = ctx.args.len > 1 and std.mem.eql(u8, ctx.args[1], "-f");1625        output.serviceLogsHeader(name, ctx.last, ctx.machine.name);1626        _ = try exec.serviceLogs(ctx.io, &ctx.machine, ctx.gpa, name, ctx.last, follow, ctx.user);1627        return;1628    }1629    if (std.mem.eql(u8, ctx.sub, "status")) {1630        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1631        output.serviceVerb("status", name, ctx.machine.name);1632        _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, "status", name, ctx.user);1633        return;1634    }1635    // start/stop/restart/enable/disable1636    const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1637    if (ctx.cfg.confirm and (std.mem.eql(u8, ctx.sub, "stop") or std.mem.eql(u8, ctx.sub, "disable"))) {1638        if (!output.confirm("")) return;1639    }1640    output.serviceVerb(ctx.sub, name, ctx.machine.name);1641    _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, ctx.sub, name, ctx.user);1642    output.serviceDone();1643}16441645// --- Flake commands ---16461647const flake_help = [_][2][]const u8{1648    .{ "init", "create a new flake.nix" },1649    .{ "update", "update flake inputs" },1650    .{ "update <in>", "update a specific input" },1651    .{ "check", "validate the flake" },1652    .{ "show", "inspect flake outputs" },1653    .{ "lock", "regenerate flake.lock" },1654    .{ "clone <url>", "clone a flake repository" },1655};16561657pub fn flake(ctx: Ctx) !void {1658    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("flake", &flake_help, null);1659    if (std.mem.eql(u8, ctx.sub, "update")) {1660        output.flakeUpdateStart();1661        const input: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1662        _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1663        output.flakeLockWritten();1664        return;1665    }1666    if (std.mem.eql(u8, ctx.sub, "check")) {1667        output.flakeCheckStart();1668        const code = try exec.flakeCheck(ctx.io, &ctx.machine, ctx.gpa);1669        if (code == 0) output.flakeValid() else output.checkFailed("");1670        return;1671    }1672    if (std.mem.eql(u8, ctx.sub, "show")) {1673        const json_out = exec.flakeShow(ctx.gpa, ctx.io, &ctx.machine) catch null;1674        if (json_out) |j| {1675            defer ctx.gpa.free(j);1676            output.flakeShowHeader("flake outputs");1677            // Parse and display the flake outputs1678            const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, j, .{}) catch return;1679            defer parsed.deinit();1680            if (parsed.value == .object) {1681                var it = parsed.value.object.iterator();1682                while (it.next()) |entry| {1683                    if (entry.value_ptr.* == .object) {1684                        var inner = entry.value_ptr.object.iterator();1685                        while (inner.next()) |e2| {1686                            const desc = if (e2.value_ptr.* == .object)1687                                if (e2.value_ptr.object.get("description")) |d|1688                                    if (d == .string) d.string else ""1689                                else1690                                    ""1691                            else1692                                "";1693                            output.flakeShowEntry(entry.key_ptr.*, e2.key_ptr.*, desc);1694                        }1695                    }1696                }1697            }1698        }1699        return;1700    }1701    if (std.mem.eql(u8, ctx.sub, "init")) {1702        _ = try exec.flakeInit(ctx.io, &ctx.machine, ctx.gpa);1703        return;1704    }1705    if (std.mem.eql(u8, ctx.sub, "lock")) {1706        _ = try exec.flakeLock(ctx.io, &ctx.machine, ctx.gpa);1707        return;1708    }1709    if (std.mem.eql(u8, ctx.sub, "clone")) {1710        const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1711        _ = try exec.flakeClone(ctx.io, &ctx.machine, ctx.gpa, url);1712        return;1713    }1714}17151716// --- Store commands ---17171718const store_help = [_][2][]const u8{1719    .{ "info", "store size and counts" },1720    .{ "path <attr>", "store path of a package" },1721    .{ "gc", "collect garbage" },1722    .{ "optimise", "deduplicate store paths with hard links" },1723    .{ "verify", "verify store integrity" },1724    .{ "repair", "repair corrupted paths" },1725};17261727pub fn store(ctx: Ctx) !void {1728    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("store", &store_help, null);1729    if (std.mem.eql(u8, ctx.sub, "gc")) {1730        _ = try exec.storeGc(ctx.io, &ctx.machine, ctx.gpa);1731        return;1732    }1733    // Accept both spellings — optimise (en) and optimize (us).1734    if (std.mem.eql(u8, ctx.sub, "optimise") or std.mem.eql(u8, ctx.sub, "optimize")) {1735        output.storeOptimiseStart(ctx.machine.name);1736        _ = try exec.storeOptimise(ctx.io, &ctx.machine, ctx.gpa);1737        output.storeOptimiseDone();1738        return;1739    }1740    if (std.mem.eql(u8, ctx.sub, "verify")) {1741        output.storeVerifyStart();1742        _ = try exec.storeVerify(ctx.io, &ctx.machine, ctx.gpa);1743        return;1744    }1745    if (std.mem.eql(u8, ctx.sub, "repair")) {1746        if (ctx.cfg.confirm and !output.confirm("")) return;1747        output.storeRepairStart();1748        _ = try exec.storeRepair(ctx.io, &ctx.machine, ctx.gpa);1749        return;1750    }1751    if (std.mem.eql(u8, ctx.sub, "info")) {1752        const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1753        output.storeInfo(si);1754        return;1755    }1756    if (std.mem.eql(u8, ctx.sub, "path")) {1757        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1758        const path = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, attr);1759        defer ctx.gpa.free(path);1760        output.storePath(path);1761        return;1762    }1763    // default: info1764    const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1765    output.storeInfo(si);1766}17671768// --- Channel commands ---17691770const channel_help = [_][2][]const u8{1771    .{ "list", "list channels" },1772    .{ "add <url> [name]", "add a channel" },1773    .{ "remove <name>", "remove a channel" },1774    .{ "update", "update all channels" },1775};17761777pub fn channel(ctx: Ctx) !void {1778    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("channel", &channel_help, null);1779    // On a flake-managed system, nix-channel operations generally don't apply.1780    if (flakeSystem(ctx)) output.flakeChannelNote();1781    if (std.mem.eql(u8, ctx.sub, "list")) {1782        output.channelListHeader(ctx.machine.name);1783        const chans = try exec.channelList(ctx.gpa, ctx.io, &ctx.machine);1784        defer ctx.gpa.free(chans);1785        for (chans) |ch| output.channelRow(ch);1786        return;1787    }1788    if (std.mem.eql(u8, ctx.sub, "add")) {1789        const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1790        const name = if (ctx.args.len > 1) ctx.args[1] else "";1791        _ = try exec.channelAdd(ctx.io, &ctx.machine, ctx.gpa, url, name);1792        output.channelDone();1793        return;1794    }1795    if (std.mem.eql(u8, ctx.sub, "remove")) {1796        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1797        _ = try exec.channelRemove(ctx.io, &ctx.machine, ctx.gpa, name);1798        output.channelDone();1799        return;1800    }1801    if (std.mem.eql(u8, ctx.sub, "update")) {1802        return channelUpdateCmd(ctx);1803    }1804}18051806// --- Profile commands ---18071808pub fn profile(ctx: Ctx) !void {1809    if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {1810        output.profileListHeader();1811        const out = exec.profileList(ctx.gpa, ctx.io, &ctx.machine) catch null;1812        if (out) |o| {1813            defer ctx.gpa.free(o);1814            var lines = std.mem.splitScalar(u8, o, '\n');1815            while (lines.next()) |line| {1816                const t = std.mem.trim(u8, line, " \t\r");1817                if (t.len == 0) continue;1818                output.profileRow(t, "", "");1819            }1820        }1821        return;1822    }1823    if (std.mem.eql(u8, ctx.sub, "install")) {1824        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1825        _ = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, attr);1826        output.done();1827        return;1828    }1829    if (std.mem.eql(u8, ctx.sub, "remove")) {1830        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1831        _ = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, attr);1832        output.done();1833        return;1834    }1835    if (std.mem.eql(u8, ctx.sub, "upgrade")) {1836        _ = try exec.profileUpgrade(ctx.io, &ctx.machine, ctx.gpa);1837        output.done();1838        return;1839    }1840}18411842// --- Pkg commands ---18431844const pkg_help = [_][2][]const u8{1845    .{ "why <pkg>", "what pulled it in" },1846    .{ "deps <pkg>", "direct dependencies" },1847    .{ "size <pkg>", "closure size" },1848    .{ "path <pkg>", "store path" },1849    .{ "closure <pkg>", "full closure" },1850};18511852pub fn pkg(ctx: Ctx) !void {1853    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("pkg", &pkg_help, null);1854    const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1855    if (std.mem.eql(u8, ctx.sub, "why")) {1856        if (try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1857        return;1858    }1859    if (std.mem.eql(u8, ctx.sub, "deps")) {1860        if (try exec.pkgDeps(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1861        return;1862    }1863    if (std.mem.eql(u8, ctx.sub, "size")) {1864        const s = try exec.pkgSize(ctx.gpa, ctx.io, &ctx.machine, name);1865        defer ctx.gpa.free(s);1866        output.pkgResult("size", s);1867        return;1868    }1869    if (std.mem.eql(u8, ctx.sub, "path")) {1870        const p = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, name);1871        defer ctx.gpa.free(p);1872        output.pkgResult("path", p);1873        return;1874    }1875    if (std.mem.eql(u8, ctx.sub, "closure")) {1876        if (try exec.pkgClosure(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1877        return;1878    }1879}18801881// Top-level alias for `nina pkg why <pkg>` — surfaces what pulled a package in1882// without the user needing to know about the `pkg` subgroup.1883pub fn why(ctx: Ctx) !void {1884    const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1885    if (try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1886}18871888// --- Pin / Unpin ---18891890pub fn pin(ctx: Ctx) !void {1891    const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1892    const commit = if (ctx.args.len > 1) ctx.args[1] else return error.Internal;1893    exec.editFlakeLock(ctx.gpa, input, commit) catch return error.ProcessFailed;1894    output.pinDone(input, commit);1895}18961897pub fn unpin(ctx: Ctx) !void {1898    const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1899    _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1900    output.unpinDone(input);1901}19021903// --- Hash / Fetch ---19041905pub fn hash(ctx: Ctx) !void {1906    const path = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1907    const h = try exec.nixHash(ctx.gpa, ctx.io, &ctx.machine, path);1908    defer ctx.gpa.free(h);1909    output.hashResult(std.mem.trim(u8, h, " \t\n\r"));1910}19111912pub fn fetch(ctx: Ctx) !void {1913    const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1914    const h = try exec.nixFetch(ctx.gpa, ctx.io, &ctx.machine, url);1915    defer ctx.gpa.free(h);1916    output.fetchResult(std.mem.trim(u8, h, " \t\n\r"), url);1917}19181919// --- Build / Run ---19201921pub fn build(ctx: Ctx) !void {1922    const attr: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1923    output.buildStart(attr orelse "default");1924    const code = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, attr);1925    if (code != 0) return error.BuildFailed;1926    output.buildDone();1927}19281929pub fn runCmd(ctx: Ctx) !void {1930    const pkg_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1931    output.runStart(pkg_arg);1932    _ = try exec.nixRun(ctx.io, &ctx.machine, ctx.gpa, pkg_arg);1933}19341935// --- Hello ---19361937pub fn hello(ctx: Ctx) !void {1938    output.hello(ctx.cfg.machines);1939}19401941const ConfigKind = enum { flake, channel, none };19421943// Scan the conventional /etc/nixos for a flake.nix (flake-based) or a1944// configuration.nix (channel-based) to pre-fill the wizard's defaults.1945fn scanConfig(io: std.Io) ConfigKind {1946    if (exec.pathExists(io, "/etc/nixos/flake.nix")) return .flake;1947    if (exec.pathExists(io, "/etc/nixos/configuration.nix")) return .channel;1948    return .none;1949}19501951// Runs when the config is absent on first invocation (interactive TTY only).1952// Scans for an existing nixos config, detects flake vs channel, and offers a1953// smart default path — flake-ness is detected, never asked.1954pub fn firstRunWizard(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1955    output.firstRunBanner();1956    output.firstRunNoConfig();19571958    var name_buf: [256]u8 = undefined;1959    var path_buf: [256]u8 = undefined;19601961    const machine_name = output.firstRunPrompt("machine name", "my-machine", &name_buf);19621963    output.firstRunScanning();1964    const kind = scanConfig(io);1965    switch (kind) {1966        .flake => output.firstRunDetected("/etc/nixos/flake.nix", true),1967        .channel => output.firstRunDetected("/etc/nixos/configuration.nix", false),1968        .none => output.firstRunNoneFound(),1969    }19701971    // Detected systems default to /etc/nixos (press enter to confirm); when1972    // nothing was found, leave the default empty so the user must type a path.1973    const default_path: []const u8 = if (kind == .none) "" else "/etc/nixos";1974    const config_path = output.firstRunPromptDefault("config path", default_path, kind != .none, &path_buf);19751976    // Re-detect at the chosen path in case the user pointed elsewhere — flake.nix1977    // there means a flake system, recorded so channel commands warn appropriately.1978    const use_flakes = exec.dirHasFlake(gpa, io, config_path);19791980    const conf_path = try config.configPath(gpa, environ);1981    defer gpa.free(conf_path);1982    if (std.fs.path.dirname(conf_path)) |dir| exec.ensureDir(gpa, io, dir);19831984    // `flake` is a top-level config field, so it must precede the [machine] block.1985    const flake_line = if (use_flakes) "flake = true\n" else "";1986    var content_buf: [1024]u8 = undefined;1987    const content = try std.fmt.bufPrint(1988        &content_buf,1989        "{s}[machine]\nname = {s}\nconfig = {s}\nlocal = true\n",1990        .{ flake_line, machine_name, config_path },1991    );19921993    const file = std.Io.Dir.createFile(.cwd(), io, conf_path, .{}) catch {1994        errors.error_info.setMessage("could not write {s}", .{conf_path});1995        return error.Internal;1996    };1997    defer file.close(io);1998    file.writePositionalAll(io, content, 0) catch {1999        errors.error_info.setMessage("could not write {s}", .{conf_path});2000        return error.Internal;2001    };20022003    output.firstRunWritten(conf_path);2004}20052006pub fn setup(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {2007    // Create the config first if it doesn't exist. This makes `nina setup`2008    // a complete onboarding command — not just a nix-features check. Any legacy2009    // ~/.nina.conf is migrated to the XDG path before we decide to run the wizard.2010    config.migrateLegacyConfig(gpa, io, environ);2011    if (config.configPath(gpa, environ)) |conf_path| {2012        defer gpa.free(conf_path);2013        if (std.Io.Dir.openFile(.cwd(), io, conf_path, .{})) |f| {2014            f.close(io);2015        } else |_| {2016            try firstRunWizard(gpa, io, environ);2017            errors.error_info.reset();2018        }2019    } else |_| {}20202021    output.setupCheck();2022    const status = exec.checkNixFeatures(gpa, io, environ);2023    output.setupFeatures(status.nix_command, status.flakes);20242025    if (status.allEnabled()) {2026        output.setupAllSet();2027        api.ensureRegistryPinned(gpa, io, environ);2028        return;2029    }20302031    // On NixOS the features belong in configuration.nix (the declarative,2032    // permanent home), not ~/.config/nix/nix.conf. Offer to add the one line;2033    // the user runs the rebuild. We don't pin the registry here because the2034    // features aren't live until that rebuild lands.2035    if (exec.isNixOS(io)) {2036        const conf_path = "/etc/nixos/configuration.nix";2037        if (exec.nixosConfigEnablesFeatures(gpa, io, conf_path)) {2038            output.setupNixosNeedsRebuild(conf_path);2039            return;2040        }2041        output.setupNixosOffer(exec.NIXOS_FEATURES_LINE, conf_path);2042        if (output.confirmDefaultNo("add it now?")) {2043            if (exec.appendFeaturesToNixosConfig(gpa, io, environ, conf_path)) |_| {2044                output.setupNixosWrote(conf_path);2045            } else |_| {2046                output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);2047            }2048        } else {2049            output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);2050        }2051        return;2052    }20532054    // Non-NixOS: a user-level nix.conf takes effect immediately, no sudo needed.2055    output.setupEnabling();2056    const path = try exec.enableNixFeatures(gpa, io, environ);2057    defer gpa.free(path);20582059    output.setupDone(path);2060    api.ensureRegistryPinned(gpa, io, environ);2061}20622063// --- Log helper ---20642065fn logAction(ctx: Ctx, action: []const u8, gen: u32) void {2066    var ts_buf: [32]u8 = undefined;2067    const ts = nowIso(ctx.io, &ts_buf);2068    var buf: [256]u8 = undefined;2069    const entry = std.fmt.bufPrint(&buf, "{{\"ts\":\"{s}\",\"machine\":\"{s}\",\"command\":\"{s}\",\"outcome\":\"success\",\"gen_before\":null,\"gen_after\":{d},\"duration_ms\":0}}\n", .{2070        ts, ctx.machine.name, action, gen,2071    }) catch return;2072    exec.appendNinaLog(ctx.io, ctx.environ, entry);2073}20742075// Wall-clock UTC as ISO-8601. Uses Io.Clock.real (the settable Unix-epoch clock);2076// Io.Clock.awake is monotonic and unsuitable for timestamps. Falls back to epoch 0.2077fn nowIso(io: std.Io, buf: []u8) []const u8 {2078    const fallback = "1970-01-01T00:00:00Z";2079    const ns = std.Io.Clock.real.now(io).toNanoseconds();2080    if (ns <= 0) return fallback;2081    const secs: u64 = @intCast(@divFloor(ns, 1_000_000_000));2082    const es = std.time.epoch.EpochSeconds{ .secs = secs };2083    const ed = es.getEpochDay();2084    const yd = ed.calculateYearDay();2085    const md = yd.calculateMonthDay();2086    const ds = es.getDaySeconds();2087    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", .{2088        yd.year,              md.month.numeric(),      @as(u32, md.day_index) + 1,2089        ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(),2090    }) catch return fallback;2091}