commands.zig

93.5 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(ctx.gpa, 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}275276// Pure decision for `nina diff`'s generation targets, split out so it can be277// unit tested without shelling out. Returns null when there's nothing safe to278// diff — no generation is marked current (a non-standard profile layout, a279// transient readlink failure, or a non-GNU remote host can all produce this)280// or fewer than two generations exist and no explicit pair was given. Nina281// ships ReleaseSafe, so leaving `current - 1` reachable with current == 0282// would be a u32 underflow panic, not silent wraparound.283fn diffTargets(gens: []const types.GenerationInfo, args: []const []const u8) ?struct { a: u32, b: u32 } {284    var current: u32 = 0;285    var prev: u32 = 0;286    for (gens) |g| {287        if (g.current) current = g.number;288        if (!g.current and g.number > prev and g.number < current) prev = g.number;289    }290    if (args.len >= 2) {291        const a = std.fmt.parseInt(u32, args[0], 10) catch blk: {292            if (current == 0) return null;293            break :blk current - 1;294        };295        const b = std.fmt.parseInt(u32, args[1], 10) catch blk: {296            if (current == 0) return null;297            break :blk current;298        };299        return .{ .a = a, .b = b };300    }301    if (current == 0 or gens.len < 2) return null;302    return .{ .a = if (prev > 0) prev else current - 1, .b = current };303}304305pub fn diff(ctx: Ctx) !void {306    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);307    defer ctx.gpa.free(gens);308    const targets = diffTargets(gens, ctx.args) orelse {309        output.diffCannotDetermine();310        return;311    };312    output.diffHeader(targets.a, targets.b, ctx.machine.name);313    if (try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, targets.a, targets.b) != 0) return error.ProcessFailed;314}315316test "diffTargets returns null when no generation is marked current" {317    const gens = [_]types.GenerationInfo{318        .{ .number = 1, .date = "", .time = "", .current = false },319        .{ .number = 2, .date = "", .time = "", .current = false },320    };321    try std.testing.expect(diffTargets(&gens, &.{}) == null);322}323324test "diffTargets returns null with fewer than two generations and no explicit args" {325    const gens = [_]types.GenerationInfo{326        .{ .number = 1, .date = "", .time = "", .current = true },327    };328    try std.testing.expect(diffTargets(&gens, &.{}) == null);329}330331test "diffTargets falls back to prev/current when both are known" {332    const gens = [_]types.GenerationInfo{333        .{ .number = 1, .date = "", .time = "", .current = false },334        .{ .number = 2, .date = "", .time = "", .current = true },335    };336    const targets = diffTargets(&gens, &.{}).?;337    try std.testing.expectEqual(@as(u32, 1), targets.a);338    try std.testing.expectEqual(@as(u32, 2), targets.b);339}340341test "diffTargets returns null when explicit args fail to parse and no current generation exists" {342    const gens = [_]types.GenerationInfo{343        .{ .number = 1, .date = "", .time = "", .current = false },344    };345    try std.testing.expect(diffTargets(&gens, &.{ "not-a-number", "2" }) == null);346}347348test "diffTargets uses explicit args verbatim when both parse" {349    const gens = [_]types.GenerationInfo{350        .{ .number = 1, .date = "", .time = "", .current = false },351    };352    const targets = diffTargets(&gens, &.{ "3", "5" }).?;353    try std.testing.expectEqual(@as(u32, 3), targets.a);354    try std.testing.expectEqual(@as(u32, 5), targets.b);355}356357pub fn mood(ctx: Ctx) !void {358    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;359    const st = exec.systemStatus(ctx.gpa, ctx.io, &ctx.machine);360    defer ctx.gpa.free(st.size);361    defer ctx.gpa.free(st.age);362    const state = exec.systemRunningState(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");363    defer ctx.gpa.free(state);364    output.mood(ctx.machine.name, state, gen, st.age, st.size);365}366367pub fn doctor(ctx: Ctx) !void {368    output.doctorHeader(ctx.machine.name);369    const checks = try exec.runDoctorChecks(ctx.gpa, ctx.io, &ctx.machine);370    defer ctx.gpa.free(checks);371    var warnings: u32 = 0;372    var failures: u32 = 0;373    for (checks) |ch| {374        output.doctorRow(ch);375        if (ch.status == .warn) warnings += 1;376        if (ch.status == .fail) failures += 1;377    }378379    // Home Manager row only when present — absent on a machine without HM, so380    // doctor's table is unchanged there.381    const hm_mode = exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ);382    if (hm_mode != .none) {383        const note = homeDoctorNote(ctx, hm_mode);384        defer ctx.gpa.free(note);385        output.doctorRow(.{ .name = "home manager", .status = .ok, .note = note });386    }387388    output.doctorSummary(warnings, failures);389}390391// "standalone  gen 765" / "module" — the note shown in doctor's home manager row.392// Caller owns the returned slice.393fn homeDoctorNote(ctx: Ctx, mode: exec.HomeManagerMode) []const u8 {394    const label = switch (mode) {395        .standalone => "standalone",396        .module => "module",397        .none => "",398    };399    if (mode == .standalone) {400        const gen = homeCurrentGen(ctx);401        if (gen != 0)402            return std.fmt.allocPrint(ctx.gpa, "{s}  gen {d}", .{ label, gen }) catch403                (ctx.gpa.dupe(u8, label) catch "");404    }405    return ctx.gpa.dupe(u8, label) catch "";406}407408// nina update — kepr self-update for the nina binary itself.409pub fn update(ctx: Ctx) !void {410    output.updateSelfStart();411412    if (comptime std.mem.eql(u8, version.PLATFORM, "unsupported")) {413        output.updateSelfNoPlatform(@tagName(builtin.cpu.arch) ++ "-" ++ @tagName(builtin.os.tag));414        return error.Internal;415    }416417    const env_url = ctx.environ.get("NINA_UPDATE_SOURCE");418    const source_url = env_url orelse UPDATE_URL;419420    const body = exec.fetchUrl(ctx.gpa, ctx.io, source_url) catch |e| switch (e) {421        error.NetworkError, error.HttpError => {422            output.updateSelfNetworkError();423            return;424        },425        else => return e,426    };427    defer ctx.gpa.free(body);428429    const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, body, .{}) catch {430        output.printWarning("could not parse release metadata");431        return;432    };433    defer parsed.deinit();434435    const root = parsed.value;436    if (root != .object) {437        output.printWarning("malformed release metadata");438        return;439    }440441    const remote_ver = blk: {442        const v = root.object.get("version") orelse {443            output.printWarning("malformed release metadata");444            return;445        };446        break :blk switch (v) {447            .string => |s| s,448            else => {449                output.printWarning("malformed release metadata");450                return;451            },452        };453    };454    if (!remoteVersionNewer(version.VERSION, remote_ver)) {455        output.updateSelfCurrent(version.VERSION);456        return;457    }458459    const release_notes = try updateReleaseNotes(ctx.gpa, ctx.io, root, source_url, version.VERSION, remote_ver);460    defer ctx.gpa.free(release_notes);461462    output.updateSelfAvailable(version.VERSION, remote_ver);463    output.updateSelfReleaseNotes(release_notes);464    if (ctx.check) return;465466    var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;467    const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {468        errors.error_info.setMessage("could not determine install path", .{});469        return error.Internal;470    };471472    // When running from the nix store, defer to nix profile upgrade so nix473    // manages the transition (the store is read-only; binary replacement fails).474    // A NixOS system install also resolves into the store but isn't a profile475    // element, so check the profile to avoid a no-op `upgrade` — it updates with476    // the next nixos-rebuild instead.477    if (std.mem.startsWith(u8, install_path, "/nix/store/")) {478        const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);479        defer if (nina_element) |n| ctx.gpa.free(n);480        if (nina_element == null) {481            output.updateSelfSystemManaged();482            return;483        }484        const element = nina_element.?;485        output.updateSelfNixManaged(remote_ver);486        if (ctx.cfg.confirm and !output.confirm("")) return;487        // Build the new version into the store BEFORE touching the profile. A488        // network drop or eval failure here leaves the old element untouched —489        // this is the only step that can fail for reasons outside our control,490        // so it must happen first. Once this succeeds, the subsequent491        // remove+add operates on an already-warm local store and is not492        // expected to fail for the same reasons, closing the window a raw493        // remove-then-add would leave open between the two profile edits.494        const prefetch_r = exec.capture(ctx.gpa, ctx.io, &ctx.machine, &.{ "nix", "build", "--no-link", "--refresh", FLAKE_URL }) catch {495            output.updateSelfNixPrefetchFailed();496            return;497        };498        defer ctx.gpa.free(prefetch_r.stdout);499        defer ctx.gpa.free(prefetch_r.stderr);500        if (prefetch_r.exit_code != 0) {501            output.raw(prefetch_r.stdout);502            output.raw(prefetch_r.stderr);503            output.updateSelfNixPrefetchFailed();504            return;505        }506        // `nix profile upgrade` re-resolves the element's own originalUrl. The507        // archive install runs with --no-write-lock-file, so nix has nowhere to508        // persist the lock it takes at install time except baking it into that509        // originalUrl as a `?narHash=` pin — which then never changes no matter510        // how far kepr's HEAD moves. Upgrading against that pin is a permanent511        // no-op: exit 0, "upgrading from X to X", nothing installed. Remove and512        // re-add against the plain (unpinned) archive URL instead, so nix513        // actually re-resolves HEAD and picks up a fresh narHash.514        const remove_r = exec.capture(ctx.gpa, ctx.io, &ctx.machine, &.{ "nix", "profile", "remove", element }) catch {515            output.updateSelfNixFailed();516            return;517        };518        defer ctx.gpa.free(remove_r.stdout);519        defer ctx.gpa.free(remove_r.stderr);520        if (remove_r.exit_code != 0) {521            output.raw(remove_r.stdout);522            output.raw(remove_r.stderr);523            output.updateSelfNixFailed();524            return;525        }526        // Even against the plain unpinned URL, nix caches its resolution for527        // `tarball-ttl` seconds (default 3600) regardless of HTTP cache-control528        // headers — so within an hour of any prior nix operation touching this529        // URL, add would silently reuse the stale narHash and reinstall the530        // same old version. --refresh forces nix to actually re-check HEAD.531        const add_r = exec.capture(ctx.gpa, ctx.io, &ctx.machine, &.{ "nix", "profile", "add", "--no-write-lock-file", "--refresh", FLAKE_URL }) catch {532            output.updateSelfNixReinstallFailed();533            return;534        };535        defer ctx.gpa.free(add_r.stdout);536        defer ctx.gpa.free(add_r.stderr);537        if (add_r.exit_code != 0) {538            output.raw(add_r.stdout);539            output.raw(add_r.stderr);540            output.updateSelfNixReinstallFailed();541            return;542        }543        output.updateSelfDone(version.VERSION, remote_ver);544        output.updateSelfNixRehash();545        return;546    }547548    const plat_info = blk: {549        const pv = root.object.get("platforms") orelse break :blk null;550        if (pv != .object) break :blk null;551        break :blk pv.object.get(version.PLATFORM);552    };553    if (plat_info == null) {554        output.updateSelfNoPlatform(version.PLATFORM);555        return;556    }557558    const dl_url = blk: {559        const v = plat_info.?.object.get("url") orelse {560            output.printWarning("malformed release metadata");561            return;562        };563        break :blk switch (v) {564            .string => |s| s,565            else => {566                output.printWarning("malformed release metadata");567                return;568            },569        };570    };571572    const raw_cksum = blk: {573        if (plat_info.?.object.get("blake3")) |v|574            break :blk switch (v) {575                .string => |s| s,576                else => {577                    output.printWarning("malformed release metadata");578                    return;579                },580            };581        if (plat_info.?.object.get("checksum")) |v|582            break :blk switch (v) {583                .string => |s| s,584                else => {585                    output.printWarning("malformed release metadata");586                    return;587                },588            };589        output.printWarning("missing checksum in release metadata");590        return;591    };592    const expected_hex = if (std.mem.startsWith(u8, raw_cksum, "blake3:")) raw_cksum["blake3:".len..] else raw_cksum;593594    if (ctx.cfg.confirm and !output.confirm("")) return;595596    output.updateSelfDownloading(remote_ver, version.PLATFORM);597    const tmp_path = exec.downloadToTemp(ctx.gpa, ctx.io, dl_url) catch {598        output.printWarning("download failed — check your connection and try again");599        return;600    };601    defer ctx.gpa.free(tmp_path);602    // Clean up the downloaded temp file whether install succeeds or fails —603    // it's only ever a scratch copy verified against the release checksum.604    defer std.Io.Dir.deleteFileAbsolute(ctx.io, tmp_path) catch {};605606    output.updateSelfVerifying();607    exec.verifyAndInstall(ctx.gpa, ctx.io, tmp_path, expected_hex, install_path) catch |e| switch (e) {608        error.ChecksumMismatch => {609            output.updateSelfChecksumFailed();610            return;611        },612        else => return e,613    };614615    output.updateSelfDone(version.VERSION, remote_ver);616}617618// archives.json covers every version between current and latest; the manifest's619// `notes` field only ever describes the single latest release. Try the full-range620// changelog first so an update spanning several versions doesn't collapse down to621// just the newest one's notes — fall back to `notes` only when the archive has622// nothing (e.g. releases predating archives.json, or the fetch failing).623fn updateReleaseNotes(gpa: std.mem.Allocator, io: std.Io, root: std.json.Value, source_url: []const u8, current: []const u8, latest: []const u8) ![]u8 {624    if (buildKeprArchiveReleaseNotes(gpa, io, source_url, current, latest) catch null) |notes| {625        if (std.mem.trim(u8, notes, " \t\r\n").len > 0) return notes;626        gpa.free(notes);627    }628    if (releaseNotesFromMetadata(gpa, root)) |notes| return notes;629    return gpa.dupe(u8, "");630}631632fn releaseNotesFromMetadata(gpa: std.mem.Allocator, root: std.json.Value) ?[]u8 {633    if (root != .object) return null;634    // `notes` is the one canonical manifest field. The retired `release_notes`635    // and `changelog` fallbacks are gone — Kepr now emits `notes` everywhere, and636    // releases that predate `--notes` fall back to archives.json in the caller.637    const v = root.object.get("notes") orelse return null;638    return switch (v) {639        .string => |s| gpa.dupe(u8, s) catch null,640        else => null,641    };642}643644fn buildKeprArchiveReleaseNotes(gpa: std.mem.Allocator, io: std.Io, source_url: []const u8, current: []const u8, latest: []const u8) ![]u8 {645    const archive_url = try keprArchiveUrl(gpa, source_url);646    defer gpa.free(archive_url);647648    const body = exec.fetchUrl(gpa, io, archive_url) catch return gpa.dupe(u8, "");649    defer gpa.free(body);650651    return releaseNotesFromArchiveJson(gpa, body, current, latest);652}653654fn keprArchiveUrl(gpa: std.mem.Allocator, source_url: []const u8) ![]u8 {655    const scheme = std.mem.indexOf(u8, source_url, "://") orelse return error.InvalidUpdateSource;656    const path_start = std.mem.indexOfScalarPos(u8, source_url, scheme + 3, '/') orelse return error.InvalidUpdateSource;657    const origin = source_url[0..path_start];658    const path = source_url[path_start..];659    if (!std.mem.startsWith(u8, path, "/api/")) return error.InvalidUpdateSource;660661    const after_api = path["/api/".len..];662    const repo_end = std.mem.indexOfScalar(u8, after_api, '/') orelse return error.InvalidUpdateSource;663    const repo = after_api[0..repo_end];664    if (repo.len == 0) return error.InvalidUpdateSource;665666    return std.fmt.allocPrint(gpa, "{s}/{s}/archives.json?limit=100", .{ origin, repo });667}668669// Saves arrive newest-first. For each version in the update range we want the OLDEST670// save message (the one that introduced that version), not a follow-up cleanup/docs save.671// We overwrite the tracked message on each occurrence, so the final stored value per672// version is always the oldest (last-seen in a newest-first stream).673fn releaseNotesFromArchiveJson(gpa: std.mem.Allocator, body: []const u8, current: []const u8, latest: []const u8) ![]u8 {674    const parsed = std.json.parseFromSlice(std.json.Value, gpa, body, .{}) catch return gpa.dupe(u8, "");675    defer parsed.deinit();676677    if (parsed.value != .object) return gpa.dupe(u8, "");678    const saves_v = parsed.value.object.get("saves") orelse return gpa.dupe(u8, "");679    if (saves_v != .array) return gpa.dupe(u8, "");680681    // version string → oldest message seen (both slice into parsed JSON, valid until deinit)682    var best_msg = std.StringHashMap([]const u8).init(gpa);683    defer best_msg.deinit();684    var order: std.ArrayList([]const u8) = .empty;685    defer order.deinit(gpa);686687    for (saves_v.array.items) |save| {688        if (save != .object) continue;689        const ver_v = save.object.get("version") orelse continue;690        const msg_v = save.object.get("message") orelse continue;691        if (ver_v != .string or msg_v != .string) continue;692        const ver = ver_v.string;693        const msg = std.mem.trim(u8, msg_v.string, " \t\r\n");694        if (msg.len == 0 or !versionInUpdateRange(ver, current, latest)) continue;695696        const entry = try best_msg.getOrPut(ver);697        if (!entry.found_existing) try order.append(gpa, ver);698        // Always overwrite: saves are newest-first, so last write = oldest save = version-intro message699        entry.value_ptr.* = msg;700    }701702    if (order.items.len == 0) return gpa.dupe(u8, "");703704    var out: std.ArrayList(u8) = .empty;705    errdefer out.deinit(gpa);706    for (order.items) |ver| {707        const msg = best_msg.get(ver).?;708        // Use only the first line as the summary; multi-line saves may have implementation details below709        const summary_end = std.mem.indexOf(u8, msg, "\n") orelse msg.len;710        const summary = std.mem.trim(u8, msg[0..summary_end], " \t\r");711        if (summary.len == 0) continue;712        try appendLine(&out, gpa, "## {s}\n", .{ver});713        try appendLine(&out, gpa, "- {s}\n\n", .{summary});714    }715716    if (out.items.len == 0) {717        out.deinit(gpa);718        return gpa.dupe(u8, "");719    }720    return out.toOwnedSlice(gpa);721}722723fn appendLine(out: *std.ArrayList(u8), gpa: std.mem.Allocator, comptime template: []const u8, args: anytype) !void {724    const line = try std.fmt.allocPrint(gpa, template, args);725    defer gpa.free(line);726    try out.appendSlice(gpa, line);727}728729fn versionInUpdateRange(candidate: []const u8, current: []const u8, latest: []const u8) bool {730    const cand = parseSemver(candidate) orelse return std.mem.eql(u8, candidate, latest);731    const cur = parseSemver(current) orelse return std.mem.eql(u8, candidate, latest);732    const lat = parseSemver(latest) orelse return std.mem.eql(u8, candidate, latest);733    return compareSemver(cand, cur) == .gt and compareSemver(cand, lat) != .gt;734}735736fn remoteVersionNewer(current: []const u8, remote: []const u8) bool {737    const cur = parseSemver(current) orelse return !std.mem.eql(u8, current, remote);738    const rem = parseSemver(remote) orelse return !std.mem.eql(u8, current, remote);739    return compareSemver(rem, cur) == .gt;740}741742const VersionOrder = enum { lt, eq, gt };743744fn compareSemver(a: Semver, b: Semver) VersionOrder {745    if (a.major != b.major) return if (a.major < b.major) .lt else .gt;746    if (a.minor != b.minor) return if (a.minor < b.minor) .lt else .gt;747    if (a.patch != b.patch) return if (a.patch < b.patch) .lt else .gt;748    return .eq;749}750751fn parseSemver(raw: []const u8) ?Semver {752    const v = if (std.mem.startsWith(u8, raw, "v")) raw[1..] else raw;753    var it = std.mem.splitScalar(u8, v, '.');754    const major_s = it.next() orelse return null;755    const minor_s = it.next() orelse return null;756    const patch_s = it.next() orelse return null;757    if (it.next() != null) return null;758    return .{759        .major = std.fmt.parseInt(u32, major_s, 10) catch return null,760        .minor = std.fmt.parseInt(u32, minor_s, 10) catch return null,761        .patch = std.fmt.parseInt(u32, patch_s, 10) catch return null,762    };763}764765test "versionInUpdateRange includes only newer versions through latest" {766    try std.testing.expect(versionInUpdateRange("3.2.3", "3.1.9", "3.2.3"));767    try std.testing.expect(versionInUpdateRange("3.2.0", "3.1.9", "3.2.3"));768    try std.testing.expect(!versionInUpdateRange("3.1.9", "3.1.9", "3.2.3"));769    try std.testing.expect(!versionInUpdateRange("3.2.4", "3.1.9", "3.2.3"));770}771772test "remoteVersionNewer does not offer downgrades" {773    try std.testing.expect(remoteVersionNewer("3.2.3", "3.2.4"));774    try std.testing.expect(!remoteVersionNewer("3.2.4", "3.2.3"));775    try std.testing.expect(!remoteVersionNewer("3.2.4", "3.2.4"));776}777778test "releaseNotesFromArchiveJson uses oldest save per version" {779    // Saves arrive newest-first. For 3.2.3, the newest save is a CONTINUITY update;780    // the oldest is the version-intro message. We expect the intro message in the output.781    const body =782        \\{783        \\  "saves": [784        \\    {"version":"3.2.3","message":"wip: record verification in CONTINUITY"},785        \\    {"version":"3.2.1","message":"old release"},786        \\    {"version":"3.2.3","message":"add streaming deflate path"}787        \\  ]788        \\}789    ;790    const notes = try releaseNotesFromArchiveJson(std.testing.allocator, body, "3.2.1", "3.2.3");791    defer std.testing.allocator.free(notes);792793    try std.testing.expect(std.mem.indexOf(u8, notes, "## 3.2.3") != null);794    try std.testing.expect(std.mem.indexOf(u8, notes, "- add streaming deflate path") != null);795    try std.testing.expect(std.mem.indexOf(u8, notes, "CONTINUITY") == null);796    try std.testing.expect(std.mem.indexOf(u8, notes, "old release") == null);797}798799test "releaseNotesFromMetadata reads canonical notes and ignores retired keys" {800    const a = std.testing.allocator;801802    // Canonical field is read.803    {804        var parsed = try std.json.parseFromSlice(std.json.Value, a, "{\"notes\":\"colored progress bar\"}", .{});805        defer parsed.deinit();806        const got = releaseNotesFromMetadata(a, parsed.value).?;807        defer a.free(got);808        try std.testing.expectEqualStrings("colored progress bar", got);809    }810811    // Retired field names are no longer honoured — they fall through to null so812    // the caller drops to the archives.json derivation instead.813    {814        var parsed = try std.json.parseFromSlice(std.json.Value, a, "{\"release_notes\":\"x\",\"changelog\":\"y\"}", .{});815        defer parsed.deinit();816        try std.testing.expect(releaseNotesFromMetadata(a, parsed.value) == null);817    }818}819820// nina goodbye — clean uninstall. Three install paths:821// - nix profile (binary in nix store with a profile element) → nix profile remove822// - koh build or source build (plain binary on PATH) → delete the file823pub fn goodbye(ctx: Ctx) !void {824    output.goodbyeStart();825826    var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;827    const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {828        errors.error_info.setMessage("could not determine install path", .{});829        return error.Internal;830    };831832    // A binary outside the nix store is a koh build or source build — delete it.833    if (!std.mem.startsWith(u8, install_path, "/nix/store/")) {834        output.goodbyeFile(install_path);835        if (ctx.cfg.confirm and !output.confirm("")) return;836        std.Io.Dir.deleteFileAbsolute(ctx.io, install_path) catch |e| {837            errors.error_info.setMessage("could not remove {s}", .{install_path});838            return e;839        };840        output.goodbyeDone();841        return;842    }843844    // Binary is in the nix store — find and remove the profile element.845    const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);846    defer {847        if (nina_element) |n| ctx.gpa.free(n);848    }849850    if (nina_element == null) {851        errors.error_info.setMessage("nina not found in nix profile — was it installed via 'nix profile add'?", .{});852        return error.Internal;853    }854855    output.goodbyeNix();856    if (ctx.cfg.confirm and !output.confirm("")) return;857    const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "remove", nina_element.? }) catch {858        output.goodbyeFailed("nix profile remove failed");859        return;860    };861    if (ec != 0) {862        output.goodbyeFailed("nix profile remove failed");863        return;864    }865    output.goodbyeDone();866}867868fn channelUpdateCmd(ctx: Ctx) !void {869    output.updateStart(ctx.machine.name);870    _ = try exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa);871    output.updateDone();872}873874pub fn upgrade(ctx: Ctx) !void {875    if (!try runPreHook(ctx, "pre-upgrade")) {876        output.aborted();877        return error.HookAborted;878    }879880    output.upgradeStart(ctx.machine.name);881    // Flake systems update inputs (flake.lock); channel systems update channels.882    // Running nix-channel --update on a flake system is a no-op at best. The883    // rebuild below is already flake-aware via exec.nixosRebuildSwitch.884    if (flakeSystem(ctx)) {885        output.printSubstep("updating flake inputs", .{});886        _ = exec.flakeUpdateAt(ctx.io, &ctx.machine, ctx.gpa, ctx.machine.config_path) catch {};887    } else {888        output.printSubstep("updating channels", .{});889        _ = exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa) catch {};890    }891    output.printSubstep("rebuilding", .{});892    output.buildPanelInit();893    const start = std.Io.Clock.awake.now(ctx.io);894    var panel = output.BuildPanel{};895    const code = exec.nixosRebuildSwitchWithPanel(ctx.io, &ctx.machine, ctx.gpa, &panel, ctx.passthrough) catch |e| {896        output.buildPanelClear();897        return e;898    };899    output.buildPanelClear();900    if (code != 0) {901        output.applyFailed("");902        return error.BuildFailed;903    }904    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());905    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));906    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;907    output.applyDone(gen, elapsed, false);908    runPostHook(ctx, "post-upgrade");909}910911pub fn log(ctx: Ctx) !void {912    output.logHeader(ctx.machine.name);913    const content = exec.readNinaLog(ctx.gpa, ctx.io, ctx.environ, ctx.last) catch {914        // No log yet — that's fine915        return;916    };917    defer ctx.gpa.free(content);918    var lines = std.mem.splitScalar(u8, content, '\n');919    while (lines.next()) |line| {920        const t = std.mem.trim(u8, line, " \t\r");921        if (t.len == 0) continue;922        if (t[0] == '{') {923            renderJsonLogLine(ctx.gpa, t);924        } else {925            // legacy tab-separated format926            var parts = std.mem.tokenizeScalar(u8, t, '\t');927            const date = parts.next() orelse continue;928            const time = parts.next() orelse "";929            const action = parts.next() orelse "";930            const detail = parts.next() orelse "";931            output.logRow(date, time, action, detail);932        }933    }934}935936// The on-disk log is JSON Lines: {"ts","machine","command","outcome","gen_after",...}.937// Render ts -> date/time columns, command -> action, outcome(+gen) -> detail.938fn renderJsonLogLine(gpa: std.mem.Allocator, line: []const u8) void {939    const parsed = std.json.parseFromSlice(std.json.Value, gpa, line, .{}) catch {940        // Unparseable — show raw rather than drop, but sanitized: a corrupted or941        // tampered-with log entry is untrusted text by the time we get here942        // (NINA-016).943        const cleaned = output.sanitize(gpa, line) catch line;944        defer if (cleaned.ptr != line.ptr) gpa.free(cleaned);945        output.logRow(cleaned, "", "", "");946        return;947    };948    defer parsed.deinit();949    if (parsed.value != .object) return;950    const o = parsed.value.object;951952    const ts = jsonStr(o, "ts");953    const date = if (ts.len >= 10) ts[0..10] else ts;954    const time = if (ts.len >= 16) ts[11..16] else "";955    const action = jsonStr(o, "command");956    const outcome = jsonStr(o, "outcome");957958    var buf: [160]u8 = undefined;959    var detail: []const u8 = outcome;960    if (o.get("gen_after")) |g| {961        if (g == .integer) {962            detail = std.fmt.bufPrint(&buf, "{s}   -> gen {d}", .{ outcome, g.integer }) catch outcome;963        }964    }965    output.logRow(date, time, action, detail);966}967968fn jsonStr(o: std.json.ObjectMap, key: []const u8) []const u8 {969    if (o.get(key)) |v| {970        if (v == .string) return v.string;971    }972    return "";973}974975pub fn edit(ctx: Ctx) !void {976    // `edit` is multi-word, so a bare positional ("hardware") arrives as ctx.sub.977    // hardware-configuration.nix is generated by nixos-generate-config and warns978    // against hand-editing — refuse rather than silently opening the wrong file.979    if (std.mem.eql(u8, ctx.sub, "hardware")) {980        output.editHardwareWarning();981        return;982    }983984    // --dir opens the whole config directory (for editors that work better with985    // a folder open), as root so root-owned config trees like /etc/nixos work.986    var open_dir = false;987    for (ctx.args) |arg| {988        if (std.mem.eql(u8, arg, "--dir")) open_dir = true;989    }990    if (open_dir) {991        output.editOpen(ctx.machine.config_path, ctx.cfg.editor);992        _ = try exec.openEditorSudo(ctx.io, ctx.gpa, ctx.cfg.editor, ctx.machine.config_path);993        return;994    }995996    const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});997    defer ctx.gpa.free(path);998    output.editOpen(path, ctx.cfg.editor);999    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);1000}10011002pub fn fmt(ctx: Ctx) !void {1003    const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});1004    defer ctx.gpa.free(path);1005    if (ctx.check) {1006        const code = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, true);1007        if (code != 0) output.fmtNeedsFormat() else output.fmtDone();1008        return;1009    }1010    output.fmtStart(path);1011    _ = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, false);1012    output.fmtDone();1013}10141015pub fn repl(ctx: Ctx) !void {1016    output.replStart();1017    _ = try exec.nixRepl(ctx.io, &ctx.machine, ctx.gpa);1018}10191020pub fn develop(ctx: Ctx) !void {1021    if (std.mem.eql(u8, ctx.sub, "show")) {1022        _ = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, null, ctx.passthrough);1023        return;1024    }1025    const run_cmd: ?[]const u8 = if (ctx.args.len > 0 and std.mem.eql(u8, ctx.sub, "run"))1026        ctx.args[0]1027    else1028        null;1029    output.developStart(&.{});1030    _ = try exec.nixDevelopPs1(ctx.io, &ctx.machine, ctx.gpa, run_cmd, ctx.environ, ctx.passthrough);1031    output.developDone();1032}10331034pub fn info(ctx: Ctx) !void {1035    output.infoHeader(ctx.machine.name);1036    const nixos_ver = exec.systemInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");1037    defer ctx.gpa.free(nixos_ver);1038    output.infoRow("nixos", std.mem.trim(u8, nixos_ver, " \t\n\r"));10391040    const kernel = exec.kernelInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");1041    defer ctx.gpa.free(kernel);1042    output.infoRow("kernel", std.mem.trim(u8, kernel, " \t\n\r"));10431044    const uptime = exec.uptimeInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");1045    defer ctx.gpa.free(uptime);1046    output.infoRow("uptime", std.mem.trim(u8, uptime, " \t\n\r"));1047}10481049pub fn boot(ctx: Ctx) !void {1050    output.bootHeader(ctx.machine.name);1051    const entries = exec.bootEntries(ctx.gpa, ctx.io, &ctx.machine) catch &.{};1052    defer ctx.gpa.free(entries);1053    for (entries, 0..) |entry, i| output.bootEntry(entry, i);1054}10551056pub fn searchCmd(ctx: Ctx) !void {1057    const query = if (ctx.args.len > 0) ctx.args[0] else "";1058    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);1059    const selected = try search_tui.run(ctx.gpa, ctx.io, query, .packages, ctx.environ);1060    if (selected) |npkg| try selectAndInstall(ctx, npkg);1061}10621063pub fn optionCmd(ctx: Ctx) !void {1064    const query = if (ctx.args.len > 0) ctx.args[0] else "";1065    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);1066    _ = try search_tui.run(ctx.gpa, ctx.io, query, .options, ctx.environ);1067}10681069pub fn install(ctx: Ctx) !void {1070    const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;10711072    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);10731074    // Search for the package to get the attr1075    const pkgs = api.searchPackages(ctx.gpa, ctx.io, ctx.environ, pkg_name) catch {1076        errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});1077        errors.error_info.setSuggestion("nina search {s}", .{pkg_name});1078        return error.PackageNotFound;1079    };10801081    if (pkgs.len == 0) {1082        // No matches — likely a typo. Suggest the closest real package and offer it.1083        if (closestPackage(ctx, pkg_name)) |sugg| {1084            output.didYouMean(pkg_name, sugg.pname);1085            if (output.confirm("")) try selectAndInstall(ctx, sugg);1086            return;1087        }1088        errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});1089        errors.error_info.setSuggestion("nina search {s}", .{pkg_name});1090        return error.PackageNotFound;1091    }10921093    // Prefer an exact name match over the first search result — `install ripgrep`1094    // must pick "ripgrep", not the alphabetically-first match like "repgrep".1095    var found = pkgs[0];1096    for (pkgs) |p| {1097        if (std.mem.eql(u8, p.pname, pkg_name)) {1098            found = p;1099            break;1100        }1101    }1102    try selectAndInstall(ctx, found);1103}11041105// Find the real package whose name is closest to a not-found query (typo help).1106// Typos usually keep the leading characters, so gather candidates with a prefix1107// search and rank by edit distance; return the best only if it's typo-close.1108fn closestPackage(ctx: Ctx, query: []const u8) ?types.NixPackage {1109    if (query.len < 2) return null;1110    var candidates = api.searchPackages(ctx.gpa, ctx.io, ctx.environ, query[0..@min(query.len, 4)]) catch &.{};1111    if (candidates.len == 0 and query.len > 2) {1112        candidates = api.searchPackages(ctx.gpa, ctx.io, ctx.environ, query[0..2]) catch &.{};1113    }1114    if (candidates.len == 0) return null;11151116    var best: ?types.NixPackage = null;1117    var best_dist: usize = std.math.maxInt(usize);1118    for (candidates) |p| {1119        const d = editDistance(query, p.pname);1120        if (d > 0 and d < best_dist) {1121            best_dist = d;1122            best = p;1123        }1124    }1125    // Only suggest a genuinely close name, scaled to query length.1126    const threshold = @max(@as(usize, 2), query.len / 3);1127    return if (best_dist <= threshold) best else null;1128}11291130// Case-insensitive Levenshtein distance. Names longer than the row buffer are1131// treated as far away (never suggested).1132fn editDistance(a: []const u8, b: []const u8) usize {1133    const n = b.len;1134    if (a.len == 0) return n;1135    if (n == 0) return a.len;1136    if (n + 1 > 128) return std.math.maxInt(usize);1137    var prev: [128]usize = undefined;1138    var curr: [128]usize = undefined;1139    var j: usize = 0;1140    while (j <= n) : (j += 1) prev[j] = j;1141    var i: usize = 1;1142    while (i <= a.len) : (i += 1) {1143        curr[0] = i;1144        j = 1;1145        while (j <= n) : (j += 1) {1146            const cost: usize = if (std.ascii.toLower(a[i - 1]) == std.ascii.toLower(b[j - 1])) 0 else 1;1147            curr[j] = @min(prev[j] + 1, @min(curr[j - 1] + 1, prev[j - 1] + cost));1148        }1149        @memcpy(prev[0 .. n + 1], curr[0 .. n + 1]);1150    }1151    return prev[n];1152}11531154test "editDistance is case-insensitive Levenshtein" {1155    try std.testing.expectEqual(@as(usize, 1), editDistance("firefux", "firefox"));1156    try std.testing.expectEqual(@as(usize, 0), editDistance("git", "GIT"));1157    try std.testing.expectEqual(@as(usize, 2), editDistance("fierfox", "firefox"));1158    try std.testing.expectEqual(@as(usize, 7), editDistance("", "firefox"));1159}11601161// Prompt for the install method (profile / system / try) and dispatch. Shared by1162// `nina install <pkg>` and the search widget's Enter-to-select — the letter keys1163// are read here, after the search widget's raw mode is gone, so they don't1164// collide with typing a query.1165fn selectAndInstall(ctx: Ctx, npkg: types.NixPackage) !void {1166    output.installSelectPrompt(npkg.pname, npkg.version);11671168    var choice_buf: [8]u8 = undefined;1169    var choice_len: usize = 0;1170    while (choice_len < choice_buf.len) {1171        const n = std.posix.read(std.posix.STDIN_FILENO, choice_buf[choice_len .. choice_len + 1]) catch break;1172        if (n == 0) break;1173        if (choice_buf[choice_len] == '\n') break;1174        choice_len += 1;1175    }1176    const choice = std.mem.trim(u8, choice_buf[0..choice_len], " \t");11771178    if (choice.len == 0 or choice[0] == 'i' or choice[0] == 'I') {1179        try profileInstallPkg(ctx, npkg);1180    } else if (choice[0] == 's' or choice[0] == 'S') {1181        try systemInstallPkg(ctx, npkg);1182    } else if (choice[0] == 't' or choice[0] == 'T') {1183        try tryPkg(ctx, npkg);1184    }1185}11861187fn profileInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {1188    output.installStart(npkg.pname, .profile);1189    if (npkg.unfree) {1190        output.printSubstep("NIXPKGS_ALLOW_UNFREE=1 nix profile add --impure nixpkgs#{s}", .{npkg.attr});1191        output.printTeach(try std.fmt.allocPrint(ctx.gpa, "NIXPKGS_ALLOW_UNFREE=1 nix profile add --impure nixpkgs#{s}", .{npkg.attr}));1192    } else {1193        output.printSubstep("nix profile add nixpkgs#{s}", .{npkg.attr});1194        output.printTeach(try std.fmt.allocPrint(ctx.gpa, "nix profile add nixpkgs#{s}", .{npkg.attr}));1195    }1196    const code = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, ctx.environ, npkg.attr, npkg.unfree);1197    if (code != 0) return error.ProcessFailed;1198    output.installDone(npkg.pname);1199}12001201fn systemInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {1202    const config_path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});1203    defer ctx.gpa.free(config_path);1204    const line = api.findSystemPackagesLine(ctx.io, config_path) orelse 1;1205    output.installEditorPrompt(npkg.pname, config_path, line, ctx.cfg.editor);1206    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, config_path, line);1207    if (ctx.cfg.confirm) {1208        if (output.confirm("apply now? ")) {1209            try apply(ctx);1210        }1211    }1212}12131214fn tryPkg(ctx: Ctx, npkg: types.NixPackage) !void {1215    output.tryStart(npkg.pname);1216    output.printSubstep("nix shell nixpkgs#{s}", .{npkg.attr});1217    output.tryExitHint();1218    _ = try exec.nixShellPs1(ctx.io, &ctx.machine, ctx.gpa, npkg.attr, ctx.environ);1219    output.tryDone();1220}12211222pub fn remove(ctx: Ctx) !void {1223    const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1224    output.removeStart(pkg_name);1225    const code = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, pkg_name);1226    if (code != 0) return error.ProcessFailed;1227    output.done();1228}12291230pub fn list(ctx: Ctx) !void {1231    output.listHeader(ctx.machine.name);12321233    // Profile packages: parse `nix profile list --json` into clean name+version1234    // rows instead of dumping nix's verbose multi-line "Name:/Flake attribute:"1235    // blocks.1236    if (exec.profileListJson(ctx.gpa, ctx.io, &ctx.machine) catch null) |json| {1237        defer ctx.gpa.free(json);1238        output.listSection("profile");1239        renderProfileJson(ctx.gpa, json);1240    }12411242    // System packages: the references of /run/current-system/sw, each a1243    // <hash>-<name>-<version> store path.1244    if (exec.systemPackagePaths(ctx.gpa, ctx.io, &ctx.machine) catch null) |paths| {1245        defer ctx.gpa.free(paths);1246        output.blankLine();1247        output.listSection("system");1248        var lines = std.mem.splitScalar(u8, paths, '\n');1249        while (lines.next()) |line| {1250            const t = std.mem.trim(u8, line, " \t\r");1251            if (t.len == 0) continue;1252            const row = pkgFromStorePath(t);1253            // Skip support paths with no parseable version (man pages, wrappers).1254            if (row.version.len == 0) continue;1255            output.listPkg(row.name, row.version);1256        }1257    }1258}12591260const PkgRow = struct { name: []const u8, version: []const u8 };12611262// Split a nix store path basename (<hash>-<name>-<version>) into name + version.1263// Version begins at the first '-' followed by a digit, which reliably lands on1264// the name/version boundary since the 32-char hash and package names start with1265// non-digits.1266fn pkgFromStorePath(path: []const u8) PkgRow {1267    const base = std.fs.path.basename(path);1268    const after_hash = if (base.len > 33 and base[32] == '-') base[33..] else base;1269    var i: usize = 0;1270    while (i + 1 < after_hash.len) : (i += 1) {1271        if (after_hash[i] == '-' and std.ascii.isDigit(after_hash[i + 1])) {1272            return .{ .name = after_hash[0..i], .version = stripOutputSuffix(after_hash[i + 1 ..]) };1273        }1274    }1275    return .{ .name = after_hash, .version = "" };1276}12771278// Multi-output derivations append the output name to the store path (e.g.1279// curl-8.20.0-bin, less-692-man). Strip that suffix so the version column reads1280// as just the version.1281fn stripOutputSuffix(ver: []const u8) []const u8 {1282    const suffixes = [_][]const u8{ "-bin", "-man", "-dev", "-doc", "-lib", "-info", "-out", "-static", "-devdoc" };1283    for (suffixes) |s| {1284        if (std.mem.endsWith(u8, ver, s)) return ver[0 .. ver.len - s.len];1285    }1286    return ver;1287}12881289test "pkgFromStorePath splits name and version at first dash-digit" {1290    const a = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-ripgrep-15.1.0");1291    try std.testing.expectEqualStrings("ripgrep", a.name);1292    try std.testing.expectEqualStrings("15.1.0", a.version);12931294    const b = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-helix-25.01");1295    try std.testing.expectEqualStrings("helix", b.name);1296    try std.testing.expectEqualStrings("25.01", b.version);12971298    // multi-output store paths drop their output-name suffix1299    const c = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-curl-8.20.0-bin");1300    try std.testing.expectEqualStrings("curl", c.name);1301    try std.testing.expectEqualStrings("8.20.0", c.version);1302}13031304fn firstStorePath(el: std.json.Value) ?[]const u8 {1305    if (el != .object) return null;1306    const sp = el.object.get("storePaths") orelse return null;1307    if (sp != .array or sp.array.items.len == 0) return null;1308    const first = sp.array.items[0];1309    return if (first == .string) first.string else null;1310}13111312// `nix profile list --json` has two shapes across nix versions: newer keys each1313// element by name (object), older lists them positionally (array). Handle both.1314fn renderProfileJson(gpa: std.mem.Allocator, json: []const u8) void {1315    const parsed = std.json.parseFromSlice(std.json.Value, gpa, json, .{}) catch return;1316    defer parsed.deinit();1317    if (parsed.value != .object) return;1318    const elements = parsed.value.object.get("elements") orelse return;1319    switch (elements) {1320        .object => |obj| {1321            var it = obj.iterator();1322            while (it.next()) |entry| {1323                const ver = if (firstStorePath(entry.value_ptr.*)) |p| pkgFromStorePath(p).version else "";1324                output.listPkg(entry.key_ptr.*, ver);1325            }1326        },1327        .array => |arr| {1328            for (arr.items) |el| {1329                const path = firstStorePath(el) orelse continue;1330                const row = pkgFromStorePath(path);1331                output.listPkg(row.name, row.version);1332            }1333        },1334        else => {},1335    }1336}13371338pub fn tryCmd(ctx: Ctx) !void {1339    const pkg_name_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1340    const shell_pkg = types.NixPackage{ .attr = pkg_name_arg, .pname = pkg_name_arg, .version = "", .description = "" };1341    try tryPkg(ctx, shell_pkg);1342}13431344// --- Home Manager commands ---13451346const home_help = [_][2][]const u8{1347    .{ "init", "set up home manager for the first time" },1348    .{ "init --switch", "set up and activate immediately" },1349    .{ "apply", "apply home-manager configuration" },1350    .{ "apply --dry", "preview changes without activating" },1351    .{ "back", "roll back one generation" },1352    .{ "history", "list all generations" },1353    .{ "edit", "open home.nix" },1354    .{ "check", "validate without applying" },1355    .{ "diff", "compare the latest two generations" },1356    .{ "packages", "list managed packages" },1357};13581359const HomeGen = struct {1360    number: u32,1361    date: []const u8,1362    time: []const u8,1363    path: []const u8,1364};13651366// `home-manager generations` lines read:1367//   2026-06-01 11:56 : id 765 -> /nix/store/<hash>-home-manager-generation1368// Newest first, so index 0 is the current generation.1369fn parseHomeGenerations(gpa: std.mem.Allocator, out_str: []const u8) ![]HomeGen {1370    var gens: std.ArrayList(HomeGen) = .empty;1371    var lines = std.mem.splitScalar(u8, out_str, '\n');1372    while (lines.next()) |line| {1373        const t = std.mem.trim(u8, line, " \t\r");1374        if (t.len == 0) continue;1375        var it = std.mem.tokenizeAny(u8, t, " \t");1376        const date = it.next() orelse continue;1377        const time = it.next() orelse continue;1378        var number: ?u32 = null;1379        var path: []const u8 = "";1380        while (it.next()) |tok| {1381            if (std.mem.eql(u8, tok, "id")) {1382                if (it.next()) |n| number = std.fmt.parseInt(u32, n, 10) catch null;1383            } else if (std.mem.startsWith(u8, tok, "/nix/store/")) {1384                path = tok;1385            }1386        }1387        const num = number orelse continue;1388        try gens.append(gpa, .{1389            .number = num,1390            .date = try gpa.dupe(u8, date),1391            .time = try gpa.dupe(u8, time),1392            .path = try gpa.dupe(u8, path),1393        });1394    }1395    return gens.toOwnedSlice(gpa);1396}13971398fn freeHomeGens(gpa: std.mem.Allocator, gens: []HomeGen) void {1399    for (gens) |g| {1400        gpa.free(g.date);1401        gpa.free(g.time);1402        gpa.free(g.path);1403    }1404    gpa.free(gens);1405}14061407test "parseHomeGenerations reads id, date and store path" {1408    const a = std.testing.allocator;1409    const sample =1410        \\2026-06-01 11:56 : id 765 -> /nix/store/aaaa-home-manager-generation1411        \\2026-05-31 10:29 : id 764 -> /nix/store/bbbb-home-manager-generation1412    ;1413    const gens = try parseHomeGenerations(a, sample);1414    defer freeHomeGens(a, gens);1415    try std.testing.expectEqual(@as(usize, 2), gens.len);1416    try std.testing.expectEqual(@as(u32, 765), gens[0].number);1417    try std.testing.expectEqualStrings("2026-06-01", gens[0].date);1418    try std.testing.expectEqualStrings("11:56", gens[0].time);1419    try std.testing.expectEqualStrings("/nix/store/aaaa-home-manager-generation", gens[0].path);1420    try std.testing.expectEqual(@as(u32, 764), gens[1].number);1421}14221423// Current (newest) home generation number, or 0 if unavailable.1424fn homeCurrentGen(ctx: Ctx) u32 {1425    const out = exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine) catch return 0;1426    defer ctx.gpa.free(out);1427    const gens = parseHomeGenerations(ctx.gpa, out) catch return 0;1428    defer freeHomeGens(ctx.gpa, gens);1429    return if (gens.len > 0) gens[0].number else 0;1430}14311432pub fn home(ctx: Ctx) !void {1433    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help"))1434        return output.subcommandHelp("home", &home_help, null);14351436    // Home Manager manages the local user's environment. Detection (which binary,1437    // ~/.config/home-manager, $HOME/$USER for the flake ref) all read the LOCAL1438    // host, while exec routes over SSH for a remote machine — so `home --on1439    // <remote>` would decide mode/flake-ref from the wrong box. Refuse it cleanly1440    // rather than acting on a mismatch.1441    if (!ctx.machine.local) {1442        output.homeLocalOnly(ctx.machine.name);1443        return;1444    }14451446    // init runs before mode detection: its whole purpose is bootstrapping a host1447    // that has no home-manager yet, so a .none mode must not short-circuit it.1448    if (std.mem.eql(u8, ctx.sub, "init")) return homeInitCmd(ctx);14491450    const mode = exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ);1451    if (mode == .none) {1452        output.homeNotInstalled();1453        return;1454    }14551456    // apply is the only command meaningful in module mode (it redirects to1457    // `nina apply`); everything else needs the standalone home-manager CLI.1458    if (std.mem.eql(u8, ctx.sub, "apply")) return homeApply(ctx, mode);1459    // edit just opens the local home.nix — fine in module mode too.1460    if (std.mem.eql(u8, ctx.sub, "edit")) return homeEdit(ctx);14611462    if (mode == .module) {1463        output.homeModuleManaged();1464        return;1465    }14661467    if (std.mem.eql(u8, ctx.sub, "back")) return homeBack(ctx);1468    if (std.mem.eql(u8, ctx.sub, "history")) return homeHistory(ctx);1469    if (std.mem.eql(u8, ctx.sub, "check")) return homeCheck(ctx);1470    if (std.mem.eql(u8, ctx.sub, "diff")) return homeDiff(ctx);1471    if (std.mem.eql(u8, ctx.sub, "packages")) return homePackages(ctx);14721473    return output.subcommandHelp("home", &home_help, null);1474}14751476fn homePackages(ctx: Ctx) !void {1477    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1478    defer ctx.gpa.free(out);1479    const gens = try parseHomeGenerations(ctx.gpa, out);1480    defer freeHomeGens(ctx.gpa, gens);14811482    output.homePackagesHeader(ctx.machine.name);1483    if (gens.len == 0 or gens[0].path.len == 0) return;14841485    // The generation's OWN references are home-manager's activation deps1486    // (bash, coreutils, ...), not what the user installed. The user's packages1487    // live one level down, in the `…-home-manager-path` env the generation1488    // references — descend into it and list ITS references. Fall back to the1489    // generation refs if that env isn't present (older home-manager layouts).1490    const gen_refs = exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, gens[0].path) catch return;1491    defer ctx.gpa.free(gen_refs);14921493    var refs = gen_refs;1494    var env_refs: ?[]u8 = null;1495    defer if (env_refs) |e| ctx.gpa.free(e);1496    if (findHomeManagerPath(gen_refs)) |pkg_path| {1497        if (exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, pkg_path)) |e| {1498            env_refs = e;1499            refs = e;1500        } else |_| {}1501    }15021503    // Dedup by name: multi-output derivations (jq, jq-lib, jq-doc) collapse to1504    // the same name after the output suffix is stripped. Keys are slices into1505    // `refs`, valid for this function's lifetime.1506    var seen = std.StringHashMap(void).init(ctx.gpa);1507    defer seen.deinit();1508    var lines = std.mem.splitScalar(u8, refs, '\n');1509    while (lines.next()) |line| {1510        const t = std.mem.trim(u8, line, " \t\r");1511        if (t.len == 0) continue;1512        const row = pkgFromStorePath(t);1513        if (row.version.len == 0) continue;1514        if (std.mem.indexOf(u8, row.name, "home-manager") != null) continue;1515        if (seen.contains(row.name)) continue;1516        seen.put(row.name, {}) catch {};1517        output.listPkg(row.name, row.version);1518    }1519}15201521// The `…-home-manager-path` env among a generation's references — the buildEnv1522// of the user's home.packages. Returns the full store-path line, or null.1523fn findHomeManagerPath(refs: []const u8) ?[]const u8 {1524    var lines = std.mem.splitScalar(u8, refs, '\n');1525    while (lines.next()) |line| {1526        const t = std.mem.trim(u8, line, " \t\r");1527        if (std.mem.indexOf(u8, t, "home-manager-path") != null) return t;1528    }1529    return null;1530}15311532test "findHomeManagerPath picks the env, not the generation or infra" {1533    const refs =1534        \\/nix/store/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-bash-5.31535        \\/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path1536        \\/nix/store/cccccccccccccccccccccccccccccccc-coreutils-9.111537    ;1538    try std.testing.expectEqualStrings(1539        "/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path",1540        findHomeManagerPath(refs).?,1541    );1542    try std.testing.expectEqual(@as(?[]const u8, null), findHomeManagerPath("/nix/store/x-bash-5.3\n"));1543}15441545fn homeDiff(ctx: Ctx) !void {1546    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1547    defer ctx.gpa.free(out);1548    const gens = try parseHomeGenerations(ctx.gpa, out);1549    defer freeHomeGens(ctx.gpa, gens);15501551    // Need two generations and both their store paths to diff their closures.1552    if (gens.len < 2 or gens[0].path.len == 0 or gens[1].path.len == 0) {1553        output.homeNothingToDiff();1554        return;1555    }1556    const newer = gens[0];1557    const older = gens[1];1558    output.homeDiffHeader(older.number, newer.number, ctx.machine.name);1559    if (try exec.diffClosuresPaths(ctx.io, &ctx.machine, ctx.gpa, older.path, newer.path) != 0)1560        return error.ProcessFailed;1561}15621563fn homeCheck(ctx: Ctx) !void {1564    output.homeCheckStart(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.homeCheckOk();1568}15691570fn homeEdit(ctx: Ctx) !void {1571    // Standalone home config lives at ~/.config/home-manager/home.nix; the same1572    // path is what detection keys on for module mode, so it resolves for both.1573    const path = exec.homeNixPath(ctx.gpa, ctx.environ) orelse {1574        errors.error_info.setMessage("could not resolve ~/.config/home-manager/home.nix", .{});1575        return error.ConfigNotFound;1576    };1577    defer ctx.gpa.free(path);1578    output.homeEditOpen(path, ctx.cfg.editor);1579    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);1580}15811582fn homeHistory(ctx: Ctx) !void {1583    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1584    defer ctx.gpa.free(out);1585    const gens = try parseHomeGenerations(ctx.gpa, out);1586    defer freeHomeGens(ctx.gpa, gens);1587    output.homeHistoryHeader(ctx.machine.name);1588    // Newest-first from home-manager; the first row is the current generation.1589    for (gens, 0..) |g, i| output.homeHistoryRow(g.number, g.date, g.time, i == 0);1590}15911592fn homeBack(ctx: Ctx) !void {1593    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1594    defer ctx.gpa.free(out);1595    const gens = try parseHomeGenerations(ctx.gpa, out);1596    defer freeHomeGens(ctx.gpa, gens);15971598    // Newest-first: [0] is current, [1] is the generation to roll back to.1599    if (gens.len < 2) {1600        output.alreadyOldest();1601        return;1602    }1603    const current = gens[0].number;1604    const prev = gens[1].number;16051606    output.homeBackStart(ctx.machine.name, current, prev);1607    if (ctx.cfg.confirm and !output.confirm("")) return;1608    const code = try exec.homeManagerRollback(ctx.io, &ctx.machine, ctx.gpa);1609    if (code != 0) return error.BuildFailed;1610    output.homeBackDone(prev);1611}16121613fn homeInitCmd(ctx: Ctx) !void {1614    var switch_on_init = false;1615    var dir: ?[]const u8 = null;1616    for (ctx.args) |arg| {1617        if (std.mem.eql(u8, arg, "--switch")) {1618            switch_on_init = true;1619        } else if (!std.mem.startsWith(u8, arg, "-")) {1620            dir = arg;1621        }1622    }16231624    // Guard only the default location — a custom dir is the user's call, and1625    // home-manager creates it. Never clobber an existing ~/.config/home-manager.1626    if (dir == null) {1627        if (exec.homeNixPath(ctx.gpa, ctx.environ)) |path| {1628            defer ctx.gpa.free(path);1629            if (exec.pathExists(ctx.io, path)) {1630                output.homeInitExists(path);1631                return;1632            }1633        }1634    }16351636    output.homeInitStart(switch_on_init, dir);1637    const code = try exec.homeManagerInit(ctx.io, &ctx.machine, ctx.gpa, switch_on_init, dir);1638    if (code != 0) return error.BuildFailed;1639    output.homeInitDone(switch_on_init);1640}16411642fn homeApply(ctx: Ctx, mode: exec.HomeManagerMode) !void {1643    // NixOS/flake module: home config is rebuilt by nixos-rebuild — redirect.1644    if (mode == .module) {1645        output.homeModuleManaged();1646        return;1647    }1648    if (ctx.dry) {1649        output.homeApplyDry(ctx.machine.name);1650        const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa, ctx.passthrough);1651        if (code != 0) return error.BuildFailed;1652        output.homeApplyDryDone();1653        return;1654    }16551656    if (!try runPreHook(ctx, "pre-home")) {1657        output.aborted();1658        return error.HookAborted;1659    }16601661    output.homeApplyStart(ctx.machine.name);16621663    // Flake-based home config: switch by attribute with a graceful fallback1664    // chain. A channel-based config (no flake.nix) uses a plain switch.1665    const dir = exec.homeFlakeDir(ctx.gpa, ctx.io, ctx.environ);1666    defer if (dir) |d| ctx.gpa.free(d);1667    if (dir) |d| return homeApplyFlake(ctx, d);16681669    output.printSubstep("home-manager switch", .{});1670    const start = std.Io.Clock.awake.now(ctx.io);1671    const code = try exec.homeManagerSwitch(ctx.io, &ctx.machine, ctx.gpa, ctx.passthrough);1672    if (code != 0) return error.BuildFailed;16731674    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());1675    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));1676    output.homeApplyDone(homeCurrentGen(ctx), elapsed);1677    runPostHook(ctx, "post-home");1678}16791680// Switch a flake-based home config, trying the most specific attribute first:1681//   <dir>#<user>-<arch>-<os>  →  <dir>#<user>  →  <dir>  (home-manager resolves)1682// Each fallback fires only on a missing-attribute error, never on a real build1683// failure. Mirrors how ${USER}-${system} homeConfigurations keys are written.1684fn homeApplyFlake(ctx: Ctx, dir: []const u8) !void {1685    const user = ctx.environ.get("USER") orelse "default";16861687    var refs: std.ArrayList([]const u8) = .empty;1688    defer {1689        for (refs.items) |r| ctx.gpa.free(r);1690        refs.deinit(ctx.gpa);1691    }1692    if (exec.homeManagerAttr(ctx.gpa, ctx.io, &ctx.machine, ctx.environ) catch null) |attr| {1693        defer ctx.gpa.free(attr);1694        try refs.append(ctx.gpa, try std.fmt.allocPrint(ctx.gpa, "{s}#{s}", .{ dir, attr }));1695    }1696    try refs.append(ctx.gpa, try std.fmt.allocPrint(ctx.gpa, "{s}#{s}", .{ dir, user }));1697    try refs.append(ctx.gpa, try ctx.gpa.dupe(u8, dir));16981699    const start = std.Io.Clock.awake.now(ctx.io);1700    for (refs.items, 0..) |ref, i| {1701        output.printSubstep("home-manager switch --flake {s}", .{ref});1702        switch (try exec.homeManagerSwitchFlake(ctx.io, &ctx.machine, ctx.gpa, ref, ctx.passthrough)) {1703            .ok => {1704                const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());1705                const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));1706                output.homeApplyDone(homeCurrentGen(ctx), elapsed);1707                runPostHook(ctx, "post-home");1708                return;1709            },1710            // Attr not defined by the flake — drop to the next candidate.1711            .attr_missing => {1712                if (i + 1 < refs.items.len) output.homeAttrFallback(ref);1713                continue;1714            },1715            .failed => return error.BuildFailed,1716        }1717    }1718    return error.BuildFailed;1719}17201721// --- Service commands ---17221723const service_help = [_][2][]const u8{1724    .{ "list", "list running services" },1725    .{ "logs <svc>", "show service logs" },1726    .{ "status <svc>", "service status" },1727    .{ "start <svc>", "start a service" },1728    .{ "stop <svc>", "stop a service" },1729    .{ "restart <svc>", "restart a service" },1730    .{ "enable <svc>", "enable at boot" },1731    .{ "disable <svc>", "disable at boot" },1732};17331734// Verbs service() is willing to forward to `sudo systemctl`. Anything else1735// (mask, kill, revert, edit, isolate, ...) used to reach systemctl with no1736// confirmation and without appearing in service_help, since the dispatcher1737// forwarded ctx.sub verbatim after list/logs/status (NINA-011).1738fn serviceVerbAllowed(verb: []const u8) bool {1739    const known = [_][]const u8{ "start", "stop", "restart", "enable", "disable" };1740    for (known) |v| {1741        if (std.mem.eql(u8, verb, v)) return true;1742    }1743    return false;1744}17451746pub fn service(ctx: Ctx) !void {1747    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");1748    if (std.mem.eql(u8, ctx.sub, "list")) {1749        output.serviceListHeader(ctx.machine.name);1750        const svcs = exec.serviceList(ctx.gpa, ctx.io, &ctx.machine, ctx.user) catch &.{};1751        defer ctx.gpa.free(svcs);1752        for (svcs) |s| output.serviceRow(s);1753        return;1754    }1755    if (std.mem.eql(u8, ctx.sub, "logs")) {1756        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1757        const follow = ctx.args.len > 1 and std.mem.eql(u8, ctx.args[1], "-f");1758        output.serviceLogsHeader(name, ctx.last, ctx.machine.name);1759        _ = try exec.serviceLogs(ctx.io, &ctx.machine, ctx.gpa, name, ctx.last, follow, ctx.user);1760        return;1761    }1762    if (std.mem.eql(u8, ctx.sub, "status")) {1763        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1764        output.serviceVerb("status", name, ctx.machine.name);1765        _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, "status", name, ctx.user);1766        return;1767    }1768    // start/stop/restart/enable/disable — checked against the allowlist before1769    // ctx.args is even read, so an unrecognized verb never gets far enough to1770    // touch a target service name.1771    if (!serviceVerbAllowed(ctx.sub)) {1772        output.subcommandHelp("service", &service_help, "add --user to act on user services");1773        return error.Internal;1774    }1775    const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1776    if (ctx.cfg.confirm and (std.mem.eql(u8, ctx.sub, "stop") or std.mem.eql(u8, ctx.sub, "disable"))) {1777        if (!output.confirm("")) return;1778    }1779    output.serviceVerb(ctx.sub, name, ctx.machine.name);1780    _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, ctx.sub, name, ctx.user);1781    output.serviceDone();1782}17831784test "serviceVerbAllowed allows only the verbs listed in service_help" {1785    try std.testing.expect(serviceVerbAllowed("start"));1786    try std.testing.expect(serviceVerbAllowed("stop"));1787    try std.testing.expect(serviceVerbAllowed("restart"));1788    try std.testing.expect(serviceVerbAllowed("enable"));1789    try std.testing.expect(serviceVerbAllowed("disable"));1790}17911792test "serviceVerbAllowed rejects verbs systemctl accepts but nina never confirmed or documented" {1793    try std.testing.expect(!serviceVerbAllowed("mask"));1794    try std.testing.expect(!serviceVerbAllowed("kill"));1795    try std.testing.expect(!serviceVerbAllowed("revert"));1796    try std.testing.expect(!serviceVerbAllowed("edit"));1797    try std.testing.expect(!serviceVerbAllowed("isolate"));1798    try std.testing.expect(!serviceVerbAllowed("starting")); // no substring match on "start"1799}18001801// True when `sub` matches one of the verbs advertised in a dispatcher's help1802// table, ignoring any "<arg>"/"[opt]" suffix (e.g. "add <url> [name]" -> "add").1803// Shared by flake/channel/profile/pkg so an unrecognized subcommand (a typo1804// like `nina flake updtae`) fails loudly instead of falling off the end of the1805// if-chain and exiting 0 (NINA-012).1806fn subcommandKnown(help_rows: []const [2][]const u8, sub: []const u8) bool {1807    for (help_rows) |row| {1808        const verb = if (std.mem.indexOfScalar(u8, row[0], ' ')) |i| row[0][0..i] else row[0];1809        if (std.mem.eql(u8, verb, sub)) return true;1810    }1811    return false;1812}18131814// --- Flake commands ---18151816const flake_help = [_][2][]const u8{1817    .{ "init", "create a new flake.nix" },1818    .{ "update", "update flake inputs" },1819    .{ "update <in>", "update a specific input" },1820    .{ "check", "validate the flake" },1821    .{ "show", "inspect flake outputs" },1822    .{ "lock", "regenerate flake.lock" },1823    .{ "clone <url>", "clone a flake repository" },1824};18251826pub fn flake(ctx: Ctx) !void {1827    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("flake", &flake_help, null);1828    if (!subcommandKnown(&flake_help, ctx.sub)) {1829        output.subcommandHelp("flake", &flake_help, null);1830        return error.Internal;1831    }1832    if (std.mem.eql(u8, ctx.sub, "update")) {1833        output.flakeUpdateStart();1834        const input: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1835        _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input, ctx.passthrough);1836        output.flakeLockWritten();1837        return;1838    }1839    if (std.mem.eql(u8, ctx.sub, "check")) {1840        output.flakeCheckStart();1841        const code = try exec.flakeCheck(ctx.io, &ctx.machine, ctx.gpa, ctx.passthrough);1842        if (code != 0) {1843            output.checkFailed("");1844            return error.CheckFailed;1845        }1846        output.flakeValid();1847        return;1848    }1849    if (std.mem.eql(u8, ctx.sub, "show")) {1850        const json_out = exec.flakeShow(ctx.gpa, ctx.io, &ctx.machine) catch null;1851        if (json_out) |j| {1852            defer ctx.gpa.free(j);1853            output.flakeShowHeader("flake outputs");1854            // Parse and display the flake outputs1855            const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, j, .{}) catch return;1856            defer parsed.deinit();1857            if (parsed.value == .object) {1858                var it = parsed.value.object.iterator();1859                while (it.next()) |entry| {1860                    if (entry.value_ptr.* == .object) {1861                        var inner = entry.value_ptr.object.iterator();1862                        while (inner.next()) |e2| {1863                            const desc = if (e2.value_ptr.* == .object)1864                                if (e2.value_ptr.object.get("description")) |d|1865                                    if (d == .string) d.string else ""1866                                else1867                                    ""1868                            else1869                                "";1870                            output.flakeShowEntry(entry.key_ptr.*, e2.key_ptr.*, desc);1871                        }1872                    }1873                }1874            }1875        }1876        return;1877    }1878    if (std.mem.eql(u8, ctx.sub, "init")) {1879        _ = try exec.flakeInit(ctx.io, &ctx.machine, ctx.gpa);1880        return;1881    }1882    if (std.mem.eql(u8, ctx.sub, "lock")) {1883        _ = try exec.flakeLock(ctx.io, &ctx.machine, ctx.gpa);1884        return;1885    }1886    if (std.mem.eql(u8, ctx.sub, "clone")) {1887        const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1888        _ = try exec.flakeClone(ctx.io, &ctx.machine, ctx.gpa, url);1889        return;1890    }1891}18921893// --- Store commands ---18941895const store_help = [_][2][]const u8{1896    .{ "info", "store size and counts" },1897    .{ "path <attr>", "store path of a package" },1898    .{ "gc", "collect garbage" },1899    .{ "optimise", "deduplicate store paths with hard links" },1900    .{ "verify", "verify store integrity" },1901    .{ "repair", "repair corrupted paths" },1902};19031904pub fn store(ctx: Ctx) !void {1905    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("store", &store_help, null);1906    if (std.mem.eql(u8, ctx.sub, "gc")) {1907        _ = try exec.storeGc(ctx.io, &ctx.machine, ctx.gpa);1908        return;1909    }1910    // Accept both spellings — optimise (en) and optimize (us).1911    if (std.mem.eql(u8, ctx.sub, "optimise") or std.mem.eql(u8, ctx.sub, "optimize")) {1912        output.storeOptimiseStart(ctx.machine.name);1913        _ = try exec.storeOptimise(ctx.io, &ctx.machine, ctx.gpa);1914        output.storeOptimiseDone();1915        return;1916    }1917    if (std.mem.eql(u8, ctx.sub, "verify")) {1918        output.storeVerifyStart();1919        _ = try exec.storeVerify(ctx.io, &ctx.machine, ctx.gpa);1920        return;1921    }1922    if (std.mem.eql(u8, ctx.sub, "repair")) {1923        if (ctx.cfg.confirm and !output.confirm("")) return;1924        output.storeRepairStart();1925        _ = try exec.storeRepair(ctx.io, &ctx.machine, ctx.gpa);1926        return;1927    }1928    if (std.mem.eql(u8, ctx.sub, "info")) {1929        const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1930        output.storeInfo(si);1931        return;1932    }1933    if (std.mem.eql(u8, ctx.sub, "path")) {1934        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1935        const path = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, attr);1936        defer ctx.gpa.free(path);1937        output.storePath(path);1938        return;1939    }1940    // default: info1941    const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1942    output.storeInfo(si);1943}19441945// --- Channel commands ---19461947const channel_help = [_][2][]const u8{1948    .{ "list", "list channels" },1949    .{ "add <url> [name]", "add a channel" },1950    .{ "remove <name>", "remove a channel" },1951    .{ "update", "update all channels" },1952};19531954pub fn channel(ctx: Ctx) !void {1955    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("channel", &channel_help, null);1956    if (!subcommandKnown(&channel_help, ctx.sub)) {1957        output.subcommandHelp("channel", &channel_help, null);1958        return error.Internal;1959    }1960    // On a flake-managed system, nix-channel operations generally don't apply.1961    if (flakeSystem(ctx)) output.flakeChannelNote();1962    if (std.mem.eql(u8, ctx.sub, "list")) {1963        output.channelListHeader(ctx.machine.name);1964        const chans = try exec.channelList(ctx.gpa, ctx.io, &ctx.machine);1965        defer ctx.gpa.free(chans);1966        for (chans) |ch| output.channelRow(ch);1967        return;1968    }1969    if (std.mem.eql(u8, ctx.sub, "add")) {1970        const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1971        const name = if (ctx.args.len > 1) ctx.args[1] else "";1972        _ = try exec.channelAdd(ctx.io, &ctx.machine, ctx.gpa, url, name);1973        output.channelDone();1974        return;1975    }1976    if (std.mem.eql(u8, ctx.sub, "remove")) {1977        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1978        _ = try exec.channelRemove(ctx.io, &ctx.machine, ctx.gpa, name);1979        output.channelDone();1980        return;1981    }1982    if (std.mem.eql(u8, ctx.sub, "update")) {1983        return channelUpdateCmd(ctx);1984    }1985}19861987// --- Profile commands ---19881989const profile_help = [_][2][]const u8{1990    .{ "list", "list profile packages" },1991    .{ "install <attr>", "install a package into your profile" },1992    .{ "remove <attr>", "remove a package from your profile" },1993    .{ "upgrade", "upgrade all profile packages" },1994};19951996pub fn profile(ctx: Ctx) !void {1997    if (std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("profile", &profile_help, null);1998    if (ctx.sub.len > 0 and !subcommandKnown(&profile_help, ctx.sub)) {1999        output.subcommandHelp("profile", &profile_help, null);2000        return error.Internal;2001    }2002    if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {2003        output.profileListHeader();2004        const out = exec.profileList(ctx.gpa, ctx.io, &ctx.machine) catch null;2005        if (out) |o| {2006            defer ctx.gpa.free(o);2007            var lines = std.mem.splitScalar(u8, o, '\n');2008            while (lines.next()) |line| {2009                const t = std.mem.trim(u8, line, " \t\r");2010                if (t.len == 0) continue;2011                output.profileRow(t, "", "");2012            }2013        }2014        return;2015    }2016    if (std.mem.eql(u8, ctx.sub, "install")) {2017        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;2018        _ = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, ctx.environ, attr, false);2019        output.done();2020        return;2021    }2022    if (std.mem.eql(u8, ctx.sub, "remove")) {2023        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;2024        _ = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, attr);2025        output.done();2026        return;2027    }2028    if (std.mem.eql(u8, ctx.sub, "upgrade")) {2029        _ = try exec.profileUpgrade(ctx.io, &ctx.machine, ctx.gpa);2030        output.done();2031        return;2032    }2033}20342035// --- Pkg commands ---20362037const pkg_help = [_][2][]const u8{2038    .{ "why <pkg>", "what pulled it in" },2039    .{ "deps <pkg>", "direct dependencies" },2040    .{ "size <pkg>", "closure size" },2041    .{ "path <pkg>", "store path" },2042    .{ "closure <pkg>", "full closure" },2043};20442045pub fn pkg(ctx: Ctx) !void {2046    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("pkg", &pkg_help, null);2047    if (!subcommandKnown(&pkg_help, ctx.sub)) {2048        output.subcommandHelp("pkg", &pkg_help, null);2049        return error.Internal;2050    }2051    const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;2052    if (std.mem.eql(u8, ctx.sub, "why")) {2053        if (try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;2054        return;2055    }2056    if (std.mem.eql(u8, ctx.sub, "deps")) {2057        if (try exec.pkgDeps(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;2058        return;2059    }2060    if (std.mem.eql(u8, ctx.sub, "size")) {2061        const s = try exec.pkgSize(ctx.gpa, ctx.io, &ctx.machine, name);2062        defer ctx.gpa.free(s);2063        output.pkgResult("size", s);2064        return;2065    }2066    if (std.mem.eql(u8, ctx.sub, "path")) {2067        const p = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, name);2068        defer ctx.gpa.free(p);2069        output.pkgResult("path", p);2070        return;2071    }2072    if (std.mem.eql(u8, ctx.sub, "closure")) {2073        if (try exec.pkgClosure(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;2074        return;2075    }2076}20772078test "subcommandKnown rejects a garbage subcommand for each of flake/channel/profile/pkg" {2079    try std.testing.expect(subcommandKnown(&flake_help, "update"));2080    try std.testing.expect(!subcommandKnown(&flake_help, "updtae"));20812082    try std.testing.expect(subcommandKnown(&channel_help, "add"));2083    try std.testing.expect(!subcommandKnown(&channel_help, "addd"));20842085    try std.testing.expect(subcommandKnown(&profile_help, "install"));2086    try std.testing.expect(!subcommandKnown(&profile_help, "instal"));20872088    try std.testing.expect(subcommandKnown(&pkg_help, "closure"));2089    try std.testing.expect(!subcommandKnown(&pkg_help, "closures"));2090}20912092// Top-level alias for `nina pkg why <pkg>` — surfaces what pulled a package in2093// without the user needing to know about the `pkg` subgroup.2094pub fn why(ctx: Ctx) !void {2095    const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;2096    if (try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;2097}20982099// --- Pin / Unpin ---21002101pub fn pin(ctx: Ctx) !void {2102    const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;2103    const rev = if (ctx.args.len > 1) ctx.args[1] else return error.Internal;2104    const flake_ref = try exec.flakeLockOverrideRef(ctx.gpa, ctx.io, &ctx.machine, input, rev);2105    defer ctx.gpa.free(flake_ref);2106    _ = try exec.flakeLockOverrideInput(ctx.io, &ctx.machine, ctx.gpa, input, flake_ref);2107    output.pinDone(input, rev);2108}21092110pub fn unpin(ctx: Ctx) !void {2111    const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;2112    _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input, &.{});2113    output.unpinDone(input);2114}21152116// --- Hash / Fetch ---21172118pub fn hash(ctx: Ctx) !void {2119    const path = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;2120    const h = try exec.nixHash(ctx.gpa, ctx.io, &ctx.machine, path);2121    defer ctx.gpa.free(h);2122    output.hashResult(std.mem.trim(u8, h, " \t\n\r"));2123}21242125pub fn fetch(ctx: Ctx) !void {2126    const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;2127    const h = try exec.nixFetch(ctx.gpa, ctx.io, &ctx.machine, url);2128    defer ctx.gpa.free(h);2129    output.fetchResult(std.mem.trim(u8, h, " \t\n\r"), url);2130}21312132// --- Build / Run ---21332134pub fn build(ctx: Ctx) !void {2135    const attr: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;2136    output.buildStart(attr orelse "default");2137    const code = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, attr, ctx.passthrough);2138    if (code != 0) return error.BuildFailed;2139    output.buildDone();2140}21412142pub fn runCmd(ctx: Ctx) !void {2143    const pkg_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;2144    output.runStart(pkg_arg);2145    _ = try exec.nixRun(ctx.io, &ctx.machine, ctx.gpa, pkg_arg, ctx.passthrough);2146}21472148// --- Hello ---21492150pub fn hello(ctx: Ctx) !void {2151    output.hello(ctx.cfg.machines);2152}21532154const ConfigKind = enum { flake, channel, none };21552156// Scan the conventional /etc/nixos for a flake.nix (flake-based) or a2157// configuration.nix (channel-based) to pre-fill the wizard's defaults.2158fn scanConfig(io: std.Io) ConfigKind {2159    if (exec.pathExists(io, "/etc/nixos/flake.nix")) return .flake;2160    if (exec.pathExists(io, "/etc/nixos/configuration.nix")) return .channel;2161    return .none;2162}21632164// Runs when the config is absent on first invocation (interactive TTY only).2165// Scans for an existing nixos config, detects flake vs channel, and offers a2166// smart default path — flake-ness is detected, never asked.2167pub fn firstRunWizard(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {2168    output.firstRunBanner();2169    output.firstRunNoConfig();21702171    var name_buf: [256]u8 = undefined;2172    var path_buf: [256]u8 = undefined;21732174    const machine_name = output.firstRunPrompt("machine name", "my-machine", &name_buf);21752176    output.firstRunScanning();2177    const kind = scanConfig(io);2178    switch (kind) {2179        .flake => output.firstRunDetected("/etc/nixos/flake.nix", true),2180        .channel => output.firstRunDetected("/etc/nixos/configuration.nix", false),2181        .none => output.firstRunNoneFound(),2182    }21832184    // Detected systems default to /etc/nixos (press enter to confirm); when2185    // nothing was found, leave the default empty so the user must type a path.2186    const default_path: []const u8 = if (kind == .none) "" else "/etc/nixos";2187    const config_path = output.firstRunPromptDefault("config path", default_path, kind != .none, &path_buf);21882189    // Re-detect at the chosen path in case the user pointed elsewhere — flake.nix2190    // there means a flake system, recorded so channel commands warn appropriately.2191    const use_flakes = exec.dirHasFlake(gpa, io, config_path);21922193    const conf_path = try config.configPath(gpa, environ);2194    defer gpa.free(conf_path);2195    if (std.fs.path.dirname(conf_path)) |dir| exec.ensureDir(gpa, io, dir);21962197    // `flake` is a top-level config field, so it must precede the [machine] block.2198    const flake_line = if (use_flakes) "flake = true\n" else "";2199    var content_buf: [1024]u8 = undefined;2200    const content = try std.fmt.bufPrint(2201        &content_buf,2202        "{s}[machine]\nname = {s}\nconfig = {s}\nlocal = true\n",2203        .{ flake_line, machine_name, config_path },2204    );22052206    const file = std.Io.Dir.createFile(.cwd(), io, conf_path, .{}) catch {2207        errors.error_info.setMessage("could not write {s}", .{conf_path});2208        return error.Internal;2209    };2210    defer file.close(io);2211    file.writePositionalAll(io, content, 0) catch {2212        errors.error_info.setMessage("could not write {s}", .{conf_path});2213        return error.Internal;2214    };22152216    output.firstRunWritten(conf_path);2217}22182219pub fn setup(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {2220    // Create the config first if it doesn't exist. This makes `nina setup`2221    // a complete onboarding command — not just a nix-features check. Any legacy2222    // ~/.nina.conf is migrated to the XDG path before we decide to run the wizard.2223    config.migrateLegacyConfig(gpa, io, environ);2224    if (config.configPath(gpa, environ)) |conf_path| {2225        defer gpa.free(conf_path);2226        if (std.Io.Dir.openFile(.cwd(), io, conf_path, .{})) |f| {2227            f.close(io);2228        } else |_| {2229            try firstRunWizard(gpa, io, environ);2230            errors.error_info.reset();2231        }2232    } else |_| {}22332234    output.setupCheck();2235    const status = exec.checkNixFeatures(gpa, io, environ);2236    output.setupFeatures(status.nix_command, status.flakes);22372238    if (status.allEnabled()) {2239        output.setupAllSet();2240        api.ensureRegistryPinned(gpa, io, environ);2241        return;2242    }22432244    // On NixOS the features belong in configuration.nix (the declarative,2245    // permanent home), not ~/.config/nix/nix.conf. Offer to add the one line;2246    // the user runs the rebuild. We don't pin the registry here because the2247    // features aren't live until that rebuild lands.2248    if (exec.isNixOS(io)) {2249        const conf_path = "/etc/nixos/configuration.nix";2250        if (exec.nixosConfigEnablesFeatures(gpa, io, conf_path)) {2251            output.setupNixosNeedsRebuild(conf_path);2252            return;2253        }2254        output.setupNixosOffer(exec.NIXOS_FEATURES_LINE, conf_path);2255        if (output.confirmDefaultNo("add it now?")) {2256            if (exec.appendFeaturesToNixosConfig(gpa, io, environ, conf_path)) |_| {2257                output.setupNixosWrote(conf_path);2258            } else |_| {2259                output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);2260            }2261        } else {2262            output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);2263        }2264        return;2265    }22662267    // Non-NixOS: a user-level nix.conf takes effect immediately, no sudo needed.2268    output.setupEnabling();2269    const path = try exec.enableNixFeatures(gpa, io, environ);2270    defer gpa.free(path);22712272    output.setupDone(path);2273    api.ensureRegistryPinned(gpa, io, environ);2274}22752276// --- Log helper ---22772278// Escapes a string for embedding inside a JSON string literal. Truncates2279// (rather than overflows `buf`) if the escaped form doesn't fit — used for a2280// single log line where losing the tail of an implausibly long machine name is2281// preferable to corrupting the line.2282fn jsonEscape(buf: []u8, s: []const u8) []const u8 {2283    var i: usize = 0;2284    for (s) |ch| {2285        const esc: ?u8 = switch (ch) {2286            '"' => '"',2287            '\\' => '\\',2288            '\n' => 'n',2289            '\r' => 'r',2290            '\t' => 't',2291            else => null,2292        };2293        if (esc) |e| {2294            if (i + 2 > buf.len) break;2295            buf[i] = '\\';2296            buf[i + 1] = e;2297            i += 2;2298        } else {2299            if (i + 1 > buf.len) break;2300            buf[i] = ch;2301            i += 1;2302        }2303    }2304    return buf[0..i];2305}23062307fn logAction(ctx: Ctx, action: []const u8, gen: u32) void {2308    var ts_buf: [32]u8 = undefined;2309    const ts = nowIso(ctx.io, &ts_buf);2310    // machine.name is config-parsed and may legally contain `"` or `\`2311    // (NINA-020) — embedding it unescaped produced an invalid JSON line that2312    // renderJsonLogLine could only fall back to showing raw.2313    var name_buf: [128]u8 = undefined;2314    const machine_name = jsonEscape(&name_buf, ctx.machine.name);2315    var buf: [256]u8 = undefined;2316    const entry = std.fmt.bufPrint(&buf, "{{\"ts\":\"{s}\",\"machine\":\"{s}\",\"command\":\"{s}\",\"outcome\":\"success\",\"gen_before\":null,\"gen_after\":{d},\"duration_ms\":0}}\n", .{2317        ts, machine_name, action, gen,2318    }) catch return;2319    exec.appendNinaLog(ctx.io, ctx.environ, entry);2320}23212322test "jsonEscape lets a machine name containing quotes and backslashes round-trip through JSON" {2323    var esc_buf: [128]u8 = undefined;2324    const escaped = jsonEscape(&esc_buf, "kyoshi\" evil\\host");23252326    var line_buf: [256]u8 = undefined;2327    const entry = std.fmt.bufPrint(&line_buf, "{{\"ts\":\"2026-01-01T00:00:00Z\",\"machine\":\"{s}\",\"command\":\"apply\",\"outcome\":\"success\",\"gen_before\":null,\"gen_after\":5,\"duration_ms\":0}}\n", .{escaped}) catch unreachable;23282329    const parsed = try std.json.parseFromSlice(std.json.Value, std.testing.allocator, entry, .{});2330    defer parsed.deinit();2331    try std.testing.expect(parsed.value == .object);2332    try std.testing.expectEqualStrings("kyoshi\" evil\\host", parsed.value.object.get("machine").?.string);2333}23342335// Wall-clock UTC as ISO-8601. Uses Io.Clock.real (the settable Unix-epoch clock);2336// Io.Clock.awake is monotonic and unsuitable for timestamps. Falls back to epoch 0.2337fn nowIso(io: std.Io, buf: []u8) []const u8 {2338    const fallback = "1970-01-01T00:00:00Z";2339    const ns = std.Io.Clock.real.now(io).toNanoseconds();2340    if (ns <= 0) return fallback;2341    const secs: u64 = @intCast(@divFloor(ns, 1_000_000_000));2342    const es = std.time.epoch.EpochSeconds{ .secs = secs };2343    const ed = es.getEpochDay();2344    const yd = ed.calculateYearDay();2345    const md = yd.calculateMonthDay();2346    const ds = es.getDaySeconds();2347    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", .{2348        yd.year,              md.month.numeric(),      @as(u32, md.day_index) + 1,2349        ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(),2350    }) catch return fallback;2351}