Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

vug manages declarative Linux user environments from signed Nix store closures. The client can install an exact set of packages without evaluating Nix expressions or building packages locally.

From declaration to generation

A Nix store closure is a set of store objects together with every object they reference, directly or indirectly. If a program needs an interpreter and shared libraries, those objects belong in its closure too. A declaration describes the packages, files and services a profile should use. A generation preserves a particular version of that profile, including the files and store references needed to use it again.

You write the declaration in vug.star. Management CI, a trusted continuous integration runner, resolves the Nix package outputs and signs a vug.lock recording the exact closure. On the client, a local trust policy determines which signatures and caches are acceptable. The result is a workflow in which the same signed inputs identify the same package objects, while a plan still accounts for the current state of the host. vug README.

A first look

On a configured test host with a declaration, a matching signed lock and a local trust policy, the sequence is:

vug home plan > plan.json
# Inspect the plan before applying it.
vug home apply --plan plan.json --wait
# Look up the profile after the operation finishes.
vug home status --profile demo

The first command observes the host and writes a plan to standard output. The second changes the profile after rechecking the plan. The third reports the active generation and any pending work. Read Planning, Applying, Rollback, and Recovery before running the second command.

Scope and reading order

AreaCommands or inputsChapters
Trust and host setuptrust.toml, vug store doctor, vug version compare-versionsArchitecture and Trust Model, Installation, Trust Policy, and Host Checks
Authoring and CIvug.star, vug record lockWriting vug.star Declarations, Locking Closures in Management CI
Activation and maintenancevug home plan, apply, status, rollback, recover, vug store gcPlanning, Applying, Rollback, and Recovery
Running programsvug home dev, vug home runRunning Commands and Command-Scoped FHS
System inspectionvug system observe-osObserving NixOS Candidates
Registry and reviewvug record check-tree, vug record decide-mergeThe Package Registry: vug-packages, Merge Checks and the Automated Gate
IntegrationA complete profile workflowEnd-to-End Walkthrough and Glossary

Read the trust and setup chapters before preparing a declaration. The locking chapter takes that declaration through CI, and the lifecycle chapter uses the resulting lock on the client. The runtime, observation and registry chapters then explain the other command families.

Versions and sources

RepositoryPinned version or commitRole
rust-vugv0.2.29 at 136aad6Implements the CLI, environment lifecycle, record checks and OS observation.
vug-packages2f82699Holds public package records, mostly references to existing Nixpkgs outputs, with a smaller set of overlay records for exceptions.
ts-vug-gatecfd1966Coordinates package pull-request inspection through a GitHub App, a Worker and a managed workflow.

Prerequisites and conventions

You should be comfortable with a Unix shell, file permissions and reading JSON. For activation, use a disposable x86_64-linux host or VM with a systemd user manager. For locking, use a separate Linux CI environment with Nix, Git when using overlays, and access to the permitted caches and the lock signing key.

Examples use demo for a profile, example-host for the client hostname and example-user for its account. Replace paths and values such as UUID with values from your test environment. Blocks with output show the result of a specific CLI invocation. Examples that require a configured environment show the command to run.

Architecture and Trust Model

vug separates package resolution, artifact delivery and host activation. The client checks a signed package selection against local policy before it changes a profile.

Four roles

  1. Author. Write vug.star in Starlark, a Python-like configuration language. The declaration returns structured data, including a target identity, a Nixpkgs pin and desired resources.
  2. Management CI. Run vug record lock to evaluate the selected Nixpkgs attributes into output paths, inspect the reference graph and publish a signed lock. The signing key stays with the trusted management runner.
  3. Binary cache. A substituter is a cache that supplies prebuilt Nix objects. A NAR (Nix Archive) is a serialization of a store object, including files, directories or symbolic links. A narinfo is a metadata record that identifies the archive and describes its hash, size, references and available signatures. An Ed25519 signature is made with a private signing key and checked with its public counterpart. Nix caches serve NARs with signed narinfo metadata.
  4. Client. Evaluate the bounded Starlark declaration, check the local host identity and validate the lock against trust.toml. During apply, acquire the exact objects from the store or by substitution and pin them for the generation. User environments, Caches and roots.

The management signature authenticates the selected closure. The cache signatures authenticate its store objects.

Why the client can skip Nix evaluation

Resolving an attribute such as ["hello"] against a Nixpkgs revision computes a concrete store path for each requested output. CI records those paths plus their transitive references, so a client already knows the entire graph and the expected hashes. On Linux with the vug-owned backend, it can materialize the closure without an installed Nix daemon. With the nix-daemon backend, the client asks the existing daemon to substitute fixed store paths with builds disabled. Both still evaluate the small Starlark declaration to verify that it matches the lock. Lock validation, Client store acquisition.

LocationWhat it records
vug.lockDeclaration and lock digests, lock key name and signature, evaluation inputs, resolved package outputs, fixed runtime tools, resolved FHS mappings when present, and the closure’s paths, NAR hashes and sizes, references, cache hints and signatures.
${XDG_CONFIG_HOME:-~/.config}/vug/trust.tomlLocally accepted lock signing keys, allowed HTTPS caches and their keys, per-profile cache permissions, protected units, reserved paths and optional store limits and credential file paths.
${XDG_STATE_HOME:-~/.local/state}/vugActive and retained generations, operation records and journals, and information needed to preserve the store roots and recover an interrupted operation.

A cache hint in the lock is subject to the client’s policy. Similarly, a valid cache signature authenticates a store object while the lock signature binds that object to this declaration and its other inputs. A change to the target identity changes the declaration digest. Editing a lock’s attributes or closure changes the digest covered by its signature. Lock and policy definitions, Operation journal.

Lean 4 verified core

Lean 4 is a programming language and theorem prover. vug’s verified decision core consists of selected pure functions and theorems about them. The build uses leanfran to generate Rust implementations from the Lean definitions. The embedded definitions and proofs live in the LeanRustGen Lean library under lean/LeanRustGen.

  • Version ordering. Lean proves properties of the comparison, including transitivity of the less-than relation and reversal when arguments are swapped.
  • Registry naming. Lean defines the allowed characters and path constructors and proves properties such as absence of slashes in valid names and uniqueness of version paths for valid inputs.
  • Merge decisions. The decision table gives failure priority over incomplete checks. With neither present, a record-only change without an approval requirement can auto-merge. Other changes require approval.

These proofs concern the modeled functions. Cache delivery, signature verification and systemd operation handling have their own Rust implementations. Build entry point, Lean modules, Version model, Naming model, Merge model.

Installation, Trust Policy, and Host Checks

Install vug, select a store backend and give the client a local trust policy. Then use vug store doctor to inspect the prerequisites for your profile.

Install the CLI

On a host with the Nix CLI and flakes enabled, build the pinned revision or run it directly:

nix build github:conao3/rust-vug/136aad68d179307d0f7d49f42506a38f337b80d5
./result/bin/vug --version
nix run github:conao3/rust-vug/136aad68d179307d0f7d49f42506a38f337b80d5 -- --version

On a host without Nix, obtain the static Linux x86-64 release archive vug-0.2.29-x86_64-linux-musl.tar.gz. musl is the C library used for this statically linked build. Extract vug and vug-bwrap into the same directory. The latter is the bundled bubblewrap executable, which vug uses to create isolated execution environments. Pinned release build, v0.2.29 release.

install -d -m 0700 "$HOME/.local/lib/vug"
tar -xzf vug-0.2.29-x86_64-linux-musl.tar.gz -C "$HOME/.local/lib/vug"
export PATH="$HOME/.local/lib/vug:$PATH"
vug --version

The apply worker checks the canonical executable path. It must be a regular file with group and other write permissions disabled. A Nix store executable qualifies through its store path. For the standalone release, the executable and its ancestor directories must belong to root or the executing user. Ancestor directories with group or other write permissions are refused unless they carry the sticky bit, which restricts deletion and renaming of other users’ entries. Choose a directory whose contents other users cannot replace. Worker executable check.

Select the store backend

Backend in profile.store_backendStorage and trust
nix-daemonUses the shared local Nix daemon for substitution, subject to its existing trust restrictions. vug disables local builds and registers generation roots with the daemon.
vug-ownedInstalls verified objects under ${XDG_DATA_HOME:-~/.local/share}/vug/nix-store. vug exposes these objects at their logical /nix/store paths when it runs a profile command. This backend can use private caches.

A garbage collection root keeps a store object and its references reachable, so they survive cleanup. The private store is bound to its state directory on first use. If you select a different XDG_STATE_HOME, choose a separate XDG_DATA_HOME too. vug refuses to prune a private store if it cannot verify the state-directory binding. Store policy, Store binding.

Write the client trust policy

Create ${XDG_CONFIG_HOME:-~/.config}/vug/trust.toml as a regular file owned by the account running vug. Mode 0600 works. Replace the demo value under lock_keys with the public part of the CI lock-signing key, expressed as base64 without its key name. The official cache key below is public.

schema_version = 1
protected_units = ["tmux-server.service"]
reserved_paths = [".config/externally-managed"]

# Uncomment only if your profile uses encrypted systemd credentials.
# sops_age_key_file = "/home/example-user/.config/vug/age-keys.txt"

[lock_keys]
demo = "<replace with the public key from CI>"

[substituters."https://cache.nixos.org"]
profiles = ["demo"]

# Nix signs metadata at this origin with the key below.
[substituters."https://cache.nixos.org".keys]
"cache.nixos.org-1" = "6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY="
FieldMeaning
schema_versionRequired integer, currently 1.
lock_keysRequired, nonempty table of named Ed25519 public keys authorized to sign locks.
protected_units, reserved_pathsOptional lists. The former protects additional systemd unit names. The latter blocks management of overlapping home-relative paths.
sops_age_key_fileOptional absolute path to a private, user-owned age identity file. age is a file-encryption tool and format. SOPS is a tool for encrypting and decrypting structured files such as YAML and can use age identities.
substitutersRequired table keyed by normalized HTTPS cache URLs, without a trailing slash. Each entry requires nonempty profiles and keys. The official Nix cache requires exactly the official key and must be public.
substituters.<origin>.private, authorization_fileOptional. private defaults to false. Private origins are usable only with vug-owned. A private origin can read an Authorization header value from a private, user-owned file.
limitsOptional table. Override positive bounds with paths, narinfo_bytes, file_bytes, nar_bytes, total_file_bytes or total_nar_bytes. The first two are capped at 65,536 paths and 1 MiB respectively.

The signed cache client rejects redirects. For a locked object, alternate permitted origins must have the same public or private designation as its preferred origin. Trust parser and origin selection, Signed cache client.

Check the host

A systemd user manager is the service manager for a particular user. Linger=yes is the logind setting that keeps that manager running after the user’s final session ends. Apply and recovery require both. Check the currently logged-in account on the test host:

loginctl show-user --property=Linger --value -- "$(id -un)"
systemctl --user show --property=UnitPath --value
vug store doctor --file vug.star

If the first check reports no, enable lingering on the test host with loginctl enable-linger "$(id -un)" under the account or through its administrator, according to the host’s policy. store doctor checks the host and UID, combined declaration/lock/trust validity, the store, generation roots, lingering and the FHS namespace probe. Each check has its own passed, failed or unknown result. A completed report exits 0 even when a check fails. With no declaration in an isolated directory, signature_policy was failed and store and gc_roots were unknown. On a daemon profile, the store check expects the caller to be untrusted according to the daemon. Doctor implementation, Host checks.

Output and exit status

--output json|text|table is global. JSON is the default and is the format to save for apply plans. --debug prints parsed inputs to standard error. Use --no-debug after it to disable that output.

$ vug --version
vug 0.2.29
$ vug version compare-versions --left 1.9 --right 1.10
{
  "Ordering": "Less"
}
$ vug --output text version compare-versions --left 1.9 --right 1.10
Less
$ vug --output table version compare-versions --left 1.9 --right 1.10
Ordering
Less

The comparator treats numeric components as numbers, so 9 sorts before 10. Reversing the inputs gives Greater, and passing 1.10 on both sides gives Equal. The comparison itself succeeds in all three cases.

ExitMeaning
0Success, help or top-level version output. A diagnostic report can contain failed checks.
252Invalid CLI syntax, such as a missing required flag.
254Definite refusal, such as invalid input, an ownership conflict, changed preconditions or a confirmed cache miss.
255An operational or unresolved failure, such as an I/O error, a systemd job failure or an inconclusive cache query.

The table describes the CLI and environment commands discussed here. Commands that launch a program can propagate its exit status. CLI parser and output, Exit constants, Environment failures.

Writing vug.star Declarations

A vug.star declaration describes a single target profile as structured data. It selects package outputs and can also describe files, user services and named commands.

Evaluation and target identity

vug invokes configure(ctx) and validates its returned dictionary against schema version 1. The Starlark evaluator runs in a separate process with CPU, memory and evaluation limits. Starlark code has no primitives for arbitrary I/O, networking, clocks, environment variables or subprocesses. A relative load() can read a .star module next to the importing file or in a subdirectory of the declaration root. Absolute paths, parent traversal and symlinked modules are refused.

The ctx struct provides host, user and system. On the client, these come from the lowercased hostname, the account associated with the process’s user ID, and the binary’s architecture and operating system. When locking in CI, --host and --user override the first two fields. The returned profile must agree with those values and specify x86_64-linux. You can use ctx to select configuration data or declare a fixed host and user explicitly. Evaluator process, Starlark loader, Target validation.

Schema version 1

The top-level schema_version, profile and nixpkgs keys are required. The collections below can be omitted when empty. Unknown fields are rejected.

KeyShape and constraints
schema_versionSet to integer 1.
profileid, kind, host, user, system, store_backend. Choose home or project for kind, and nix-daemon or vug-owned for storage. Projects cannot manage dotfiles, units or secrets.
nixpkgsrev is a full lowercase 40-hex revision. allow_unfree is a Boolean and permitted_insecure is a list of package-version names.
overlaysList of id, visibility, registry_rev and digest objects. An overlay changes the package definitions imported from Nixpkgs. Visibility is public or private. Private overlays require vug-owned.
packagesMap from package IDs to attr (a list of Nixpkgs attribute path segments) and outputs (a nonempty list of output names). For a registry overlay add all of overlay, record and version. Optional plugins = [{"output": "lib", "path": "lib/plugin.so"}] names libraries explicitly loaded by the package. Each plugin must be in a declared output.
dotfilesMap from clean home-relative destinations to {"owner": "vug", "source": "..."} entries with declaration-relative source paths. Destinations cannot overlap or end in .backup.
unitsMap from vug-*.service names to owner = "vug", package, output, executable, restart_policy and Boolean protected. Optional args and reload_args are argument lists. reload_executable is required for policy reload. Optional credentials lists secret IDs. Policies are reload, restart, next-login and manual. Internal prefixes such as vug-apply- are reserved.
secretsMap from IDs to sops_file and key. The file is encrypted YAML relative to the declaration, and key lists the steps to a scalar value in the document.
commandsMap from command IDs to either package, output and executable, or local_executable and its lowercase SHA-256 sha256. Optional args precede arguments supplied by the caller. fhs_profile selects a named filesystem layout and bind lists allowed host resources to expose within it.
fhs_profilesMap of profiles with a runtime_x86_64 list. Every mapping identifies package, output, and a clean relative from and to. Targets must be under usr/ without overlaps. The profile must map usr/lib64/ld-linux-x86-64.so.2.
osOptional object with a store-path candidate and optional postprocess recipe ID. See Observing NixOS Candidates for the separate observation command.

An output is one named result of a Nix package definition, for example out or lib. Executable paths in units and commands are relative to the selected output or, for local_executable, to the declaration directory. Arguments are data passed to a program. vug rejects common shells and env as executable names in these declarations. FHS, the Filesystem Hierarchy Standard, here describes a command-specific Linux layout such as /usr/lib64. The bind list is permitted only with an FHS profile. For allowed resource names and runtime checks, see Running Commands and Command-Scoped FHS. Declaration types and validation.

A declaration with one helper module

Create three files in one directory. The example selects the default output of GNU Hello, installs a small configuration file and names a command for later use.

packages.star

PACKAGES = {
    "hello": {"attr": ["hello"], "outputs": ["out"]},
}

vug.star

load("packages.star", "PACKAGES")

def configure(ctx):
    return {
        "profile": {
            "id": "demo",
            "kind": "home",
            "host": ctx.host,
            "user": ctx.user,
            "system": ctx.system,
            "store_backend": "nix-daemon",
        },
        "schema_version": 1,
        "nixpkgs": {
            "rev": "2786a2a72088ecf32aea5b3ec52099e6a7cff78f",
            "allow_unfree": False,
            "permitted_insecure": [],
        },
        "packages": PACKAGES,
        "dotfiles": {
            ".config/demo.conf": {"owner": "vug", "source": "demo.conf"},
        },
        "commands": {
            "greet": {
                "package": "hello",
                "output": "out",
                "executable": "bin/hello",
            },
        },
    }

demo.conf

greeting=hello

Use a Nixpkgs revision with cache coverage for the outputs and runtime you intend to lock. In CI, set --host example-host --user example-user for that target. On your own test host, use its actual identity. Once applied, run vug home run --command greet -- --version.

What the declaration digest binds

vug hashes the normalized declaration using SHA-256 over RFC 8785 canonical JSON, a deterministic JSON encoding with defined object key ordering and serialization rules. Moving the tree to another directory leaves the digest unchanged if the returned data stays the same. A different host, user, system or backend changes the returned profile and thus the digest. The saved plan separately records input paths and hashes for the modules, lock and referenced files, so changing demo.conf after planning still invalidates the plan. Canonical digest, Input tracking.

Locking Closures in Management CI

Management CI resolves a declaration into exact store paths, checks cache coverage and native library compatibility, then publishes the signed vug.lock.

Run the lock command

Use a Linux Nix runner. Set VUG_RUNTIME_PATH to the exact store object containing bin/vug before running this example. That object, the selected package outputs and all their references must have signed narinfo in the permitted caches. Prearrange cache coverage for your vug runtime as well as your packages.

vug record lock \
  --file vug.star \
  --lock vug.lock \
  --signing-key "$VUG_SIGNING_KEY_FILE" \
  --runtime "vug=$VUG_RUNTIME_PATH:bin/vug" \
  --trust ci-trust.toml \
  --host example-host --user example-user
FlagWhat CI supplies
--file, --lockInput declaration and output lock. Defaults are vug.star and a sibling vug.lock.
--signing-keyRequired path to a Nix Ed25519 secret key file in NAME:BASE64 form. The decoded 64 bytes hold a 32-byte signing seed followed by its matching public key. The regular file must belong to the running user and have no group or other permissions. The named public key must appear in [lock_keys].
--runtimeRepeatable ID=STORE_PATH:EXECUTABLE, with the executable path relative to the store object. Include vug and, for a profile with secrets, sops.
--trustCI’s trust configuration, defaulting to the same XDG config path used on the client.
--host, --userTarget values for configure(ctx). They default to the runner’s own host and user.
--registryRepeatable ID=DIR mapping an overlay ID to its checkout. Supply it for every overlay used by a package.

Treat the lock as a generated artifact. vug resolves the attributes with nix eval using the pinned revision and package policy and disables import from derivation, a Nix feature that can require building a value during evaluation. It walks signed narinfo beginning with the selected package outputs and fixed runtime paths. The closure must include all reachable objects and contain no extraneous entries. Lock command, Closure validation.

Verify registry overlays

For each referenced overlay, CI checks that Git HEAD matches registry_rev and that porcelain status is empty, including untracked files. It uses git ls-files to enumerate tracked files, hashes each file with SHA-256, and takes the SHA-256 of the RFC 8785 canonical JSON map from relative filename to hash. That second hash must match the declared digest.

The version record at packages/<shard>/<record>/versions/<version>.star must describe an overlay with matching architecture, Nixpkgs revision, attribute path and outputs. A private record requires a private declaration overlay. The nix-package recipe overrides the previous derivation’s source and appends hashed patches. The unpack-elf recipe unpacks the upstream artifact into out and uses Nixpkgs’ ELF patching hook. Both are evaluated as Nixpkgs overlays. A nested package set with overrideScope is updated through its package scope so siblings can see the changed input. vug uses an attribute merge for plain sets. Overlay evaluation and checkout verification, Record guide.

Substitute and inspect the ABI

After resolving metadata, CI needs the actual store objects for the ABI (application binary interface) check. vug asks nix-store --realise to obtain missing paths with local jobs disabled, no builders, and fallback disabled. At this pinned version, that step works on the CI runner’s /nix/store and passes only daemon-eligible substituter URLs. Objects advertised solely by a private cache need to be present in that store already for the ABI check.

The generated lock is reloaded and validated before the store and ABI checks. It becomes visible at the requested path after those checks succeed.

ELF (Executable and Linkable Format) is the Linux binary format used for native programs and shared libraries. vug models dynamic linking for ELF64 objects:

  1. Discover ELF files recursively under each output’s bin/ and libexec/, visiting a resolved directory once even if several symlinks reach it. Shell scripts are skipped. Files with ELF magic that fail the parser are rejected.
  2. Read PT_INTERP, the program-header segment naming the dynamic loader. The segment must stay within the file, occur at most once and contain a nonempty, NUL-terminated UTF-8 path. The loader must resolve inside the Nix store and parse as ELF when visited.
  3. Resolve each DT_NEEDED entry, which names a shared-library dependency. DT_RUNPATH is the object’s own set of search directories. Its presence, even as an empty value, suppresses DT_RPATH for that object. With no DT_RUNPATH, the model searches the object’s DT_RPATH and inherited RPATH directories. It expands $ORIGIN relative to the resolved object. If the search fails, the model can use a matching loader-chain name or interpreter name already known to it, or search the interpreter’s directory.
  4. Track each SONAME, the name a shared ELF library advertises to the loader, against the file it resolves to. Every SONAME in one modeled process must resolve to one canonical store path, including dependencies crossing output boundaries. Each discovered executable is checked with every declared plugin of that package loaded into the same process. When no ELF executable is found, the plugins are checked together by themselves.
  5. Check the locked FHS library mappings under usr/lib* for multiple files with the same SONAME. The pinned implementation collects these mappings across the declaration’s FHS profiles for this check.

The ABI resolver checks paths in the realised CI store. This is a static inspection of ELF metadata and explicit plugin declarations. ELF parser and resolver, ABI check entry point.

Sign and publish

The generator hashes a canonical JSON form of the lock while omitting lock_digest and lock_signature. It signs the UTF-8 bytes vug.lock/v1\n<lock_digest>, where \n is a literal newline in the message. It serializes the lock as TOML, parses it again, and verifies it with the declaration and trust policy. For the same inputs, including the same cache metadata and key, the result is byte-identical. After substitution and ABI inspection, vug writes a temporary file beside the destination, syncs it, atomically renames it over the lock and syncs the parent directory. Generation and atomic write.

Interpret locking failures

When the JSON error has detail.classification, use it to locate the stage that failed.

ClassificationMeaningCode and exit
evaluation_refusedThe selected package or outputs could not be evaluated under the pin and policy, for example because the package is unfree and disallowed.UNRESOLVED, 254
not_builtThe requested package output has no narinfo in any permitted cache.UNRESOLVED, 254
redistribution_deniedAn output is missing and Nixpkgs license metadata marks the package as non-redistributable.UNRESOLVED, 254
cache_missingA required closure path is absent from every permitted cache, or the later CI substitution step failed.CACHE_MISSING, 254
unavailable_unknownNo cache supplied the metadata and a transport failure prevents a definitive miss.UNRESOLVED, 255

Signature errors, invalid declarations and ABI failures can instead report INVALID_INPUT. Check standard error for their diagnostic text. Classification and resolution, JSON errors.

Planning, Applying, Rollback, and Recovery

vug separates a read-only host plan from activation. It records an apply operation durably, keeps earlier generations available and guards restoration after an interruption.

Save and review a plan

From the declaration directory on a configured test host:

vug home plan > plan.json
jq '{state, kind, plan_id, fixed: (.fixed | {from_generation, to_generation, files, units})}' plan.json

Use the default JSON output for the saved plan. If the plan command fails, the file can contain a JSON error or be empty, so check the command’s exit status before using it. The plan binds the target profile, declaration, lock, policy, source inputs, current and proposed generations, file snapshots and affected systemd unit state. Those observed values are preconditions, facts that must still hold when the worker acts. Planning reads these inputs and local state without activating the profile or acquiring the closure. Use --file and --lock to point to other input files. Plan types and rechecks, Plan command.

Apply with an independent worker

vug home apply --plan plan.json --wait
# Look up the profile after the operation finishes.
vug home status --profile demo

home apply starts a transient systemd unit, a service defined at launch rather than installed permanently. The worker runs under the systemd user manager as vug-apply-<UUID>.service. With Linger=yes, an SSH disconnect can end the client command while the worker keeps running. With --wait, the client waits for the outcome and returns the worker’s result code. Without it, exit 0 can mean the operation was accepted and is still running.

The worker takes an exclusive operation lock for the state directory, rebuilds and checks the plan, and acquires and pins the closure for a new generation. Before switching it verifies roots, checks credentials and rechecks preconditions. It updates the current-generation link and managed links, reloads systemd definitions when needed and runs the planned unit jobs. The saved plan, status and append-only events.jsonl journal are under ${XDG_STATE_HOME:-~/.local/state}/vug/operations/<UUID>/. Journal records let a later worker determine which changes were attempted. Worker launch, Operation implementation.

The journal distinguishes an early abort from a failed switch that needs restoration.

Coexist with local files and services

vug installs managed dotfiles as links to generation files. It can create an absent destination or replace a link it can prove belongs to the current profile. An unmanaged destination, a missing or changed link that vug expected to own, and a .backup sibling all prevent replacement. Trust policy can reserve additional home-relative paths. vug detects Home Manager, another Nix-based user environment manager, by looking for destinations placed by its profile generation or a generation named in home-manager-<user>.service or relevant drop-ins. A file or symlink above the destination in a Home Manager generation counts as ownership of the subtree.

Managed user units are also subject to ownership checks. An existing unit from another owner, an unexpected drop-in or an unexpected alias can block the plan. A drop-in is a supplementary systemd configuration file that modifies the unit. File and Home Manager checks, Unit ownership checks.

Protect running services

The protected set includes tmux-server.service, names in trust.toml, and units marked protected = True by the current or proposed declaration. For an actual unit job, vug walks dependency and propagation links including PartOf, BindsTo, Requires, Wants, Conflicts, trigger links, reverse relations and stop or reload propagation. It checks aliases and inactive units as well, tracks visits to terminate cycles, and includes the observed chain in the preconditions. Targets and slices are checked for protection. Membership alone is insufficient to continue the walk through them. The pinned implementation follows the links that can carry the job reaching that group, for example dependencies or conflicts reached by a start job. vug checks the relevant graph again before dispatch.

To explicitly permit a change to a directly managed protected unit, name that unit when planning, for example vug home plan --allow-protected vug-demo.service > plan.json. The override is captured in the plan. It does not authorize reaching a different protected unit through dependencies. Protection and graph walk.

Defer changes and deliver credentials

With restart_policy = "next-login", vug keeps the presently installed unit definition, if any, until a new qualifying session for the profile UID. A generated user service listens to logind, the systemd login manager, and ignores sessions already present when the deferral was queued. It creates and rechecks a fresh plan from the saved inputs. If the inputs changed, create and apply a fresh ordinary plan. Linger keeps the service available, but only a qualifying login triggers activation. The login watcher cannot override protection. Login watcher, Login plan.

For credentials, list secret IDs in a unit’s credentials. Each ID selects a string, number or Boolean from an encrypted YAML file. Point sops_age_key_file in trust.toml to a private, user-owned age identity file, and lock a pinned runtime.sops entry in vug.lock. vug retains encrypted inputs with the generation and tests decryption before switching. A generated oneshot service, which runs a task to completion, prepares the selected values in a private runtime directory. systemd LoadCredential makes those values available as credential files to the target unit. Credential preparation and delivery.

Inspect, roll back and recover

vug home status --profile demo
vug home status --operation UUID

Profile status shows the active generation, pending operations, the latest operation and deferred units. Operation status is for a particular attempt and reports its phase, result and recovery information. An early failure can leave an operation aborted. After switching starts, vug attempts guarded restoration. A successful restoration gives rolled_back, while an interruption or uncertain restoration can leave needs_recovery.

To deliberately return to a retained generation such as generation 1, generate and review a rollback plan and then apply it:

vug home rollback --generation 1 > rollback.json
vug home apply --plan rollback.json --wait

For a stopped operation that reports needs_recovery, inspect its status, journal and the affected systemd units first. An uncertain job may have changed a service even when the worker could not record the outcome. Use the operation’s ID to retry guarded restoration from its journal:

vug home recover --operation UUID --wait

Recovery checks whether observed file and systemd state still permit safe restoration. It can leave the operation in needs_recovery if it cannot establish the result of a unit job. Status and restoration.

Prune old generations

vug store gc --profile demo --keep 3

This reports proposed removals. Add --apply to remove the eligible generations and unreferenced private store objects. --keep defaults to 2 and counts the newest generations with manifests. Additional roots survive for active generations, deferred unit definitions, relevant unfinished operations and generations leased by running commands. A lease is a lock that holds a generation live while a program uses it. Garbage collection, Operation roots.

Running Commands and Command-Scoped FHS

Run an ad hoc command with the active generation on PATH, or launch a declared command with the Linux filesystem layout and host resources it needs.

Choose a command entry point

vug home dev -- hello --version
vug home run --command greet -- --version

home dev puts the active generation’s bin before the inherited PATH. Omit the program to launch $SHELL (or /bin/sh). home run looks up a command ID in the applied declaration, runs its specified executable, and appends the arguments after -- to the declaration’s fixed args. Both hold a generation lease, a shared lock that keeps garbage collection (GC) from pruning the generation while the child runs. See Planning, Applying, Rollback, and Recovery. Runtime implementation

Both entry points evaluate the supplied declaration to find the profile and compare its digest with the saved declaration. Before launch, vug reloads trust.toml and validates the saved lock’s declaration_digest, lock_digest and lock_signature. It also rehashes every locked path for vug-owned and checks the result against its nar_hash. A NAR is Nix’s serialized representation of a store object. For a declared local_executable, vug reads the file beneath the declaration directory, checks its SHA-256 and verifies it is an ELF (Executable and Linkable Format) program. It runs a temporary executable copy of the checked bytes. Runtime implementation Lock validation

What a command-scoped filesystem contains

FHS stands for Filesystem Hierarchy Standard, the familiar Linux layout with paths such as /usr/bin and /lib64. A declared command selects that layout with fhs_profile. Bubblewrap, a Linux sandbox launcher shipped as vug-bwrap with the static release, assembles the filesystem for that command. A new user namespace gives the child a separate view of user and group IDs. A new PID namespace gives it a separate process-ID space. The sandbox has its own /proc, minimal /dev, and private /tmp and /dev/shm (shared-memory files). These options leave the host network namespace available. Home runtime documentation Bubblewrap arguments

The lock supplies the filesystem mappings. The command’s bind list determines which additional host resources it can reach.

  • Runtime mappings. Each runtime_x86_64 entry maps part of a locked output read-only beneath /usr. Its source must stay inside its original locked output when vug follows symlinks. /lib64, /lib, /bin and /sbin link to the corresponding locations under /usr. The profile must map the loader at usr/lib64/ld-linux-x86-64.so.2.
  • Read-only mounts. Vug exposes the generation, and either the full /nix/store for nix-daemon or the locked closure only for vug-owned. It exposes selected /etc entries if present, covering users and groups, host and DNS lookup, time zone, machine ID, certificates and fonts.
  • Home and environment. The real home and host root stay outside the sandbox. Vug creates an empty private directory at the home path and starts there by default. It clears the environment, forwards TERM, COLORTERM, LANG, LC_ALL, LC_CTYPE, TZ, USER and LOGNAME if set, and supplies HOME, PATH and any bind-specific variables. PATH searches the generation’s bin, then /usr/bin, then /bin.

Commands without an FHS profile use the ordinary runtime. With nix-daemon they run directly, while vug-owned maps its private objects to their logical store paths and keeps the host Nix daemon socket directory visible. For 32-bit FHS software such as Steam, use steam-run. Launcher FHS validation and mounts Declaration validation

Add host resources explicitly

bind entryResource and environment
project-roMounts the declaration directory read-only and starts the command there.
project-rwMounts the same directory writable and starts there. Both project modes refuse / and directories that contain the whole home.
x11Mounts /tmp/.X11-unix/X<n> for a local DISPLAY. If XAUTHORITY is set, mounts the private user-owned file and forwards its path.
waylandMounts the socket under XDG_RUNTIME_DIR, using wayland-0 when WAYLAND_DISPLAY is unset. Supplies the absolute socket path as WAYLAND_DISPLAY and forwards XDG_RUNTIME_DIR.
dbusMounts the session bus socket from the path= field of its first unix: address, or defaults to $XDG_RUNTIME_DIR/bus. Sets DBUS_SESSION_BUS_ADDRESS to unix:path=<socket>.
gpuExposes /dev/dri/renderD* and mounts /run/opengl-driver read-only if it exists.
tmuxMounts the socket named by the first field of TMUX and forwards that variable.
ssh-agentMounts the socket named by SSH_AUTH_SOCK and forwards its path.
dockerMounts the socket from a unix:// DOCKER_HOST or /run/docker.sock and sets DOCKER_HOST to the resulting socket URI.
nix-daemonMounts /nix/var/nix/daemon-socket/socket and sets NIX_REMOTE=daemon.
host-tmpCreates or reuses the user’s private vug-<uid> directory under an absolute TMPDIR or /tmp, mounts it writable and sets VUG_HOST_TMP.

Wayland, D-Bus, tmux and SSH agent sockets must be absolute, owned by the invoking UID and sockets in their own right, rather than symlinks at the socket path. X11, Docker and the Nix daemon use a socket-type check after path resolution. The X authority file and host temporary directory must also be private to the UID. A missing socket or a resource with an unexpected type or owner fails before launch with PRECONDITIONS_CHANGED (exit 254). A mounted socket grants the ability to talk to the service according to its permissions, even when the mount itself is read-only. Bind and ownership checks Failure codes

Observing NixOS Candidates

Compare a built NixOS generation with the running system and distinguish static changes from effects that only activation can reveal.

A NixOS toplevel is the store object for a complete system generation. Pass the exact already-built /nix/store/…-nixos-system-* path. If a build left a ./result symlink, resolve it first and review the resulting path. The default observation reads the running generation from /run/current-system, queries the local Nix daemon, and inspects store files and reachable systemd managers. It evaluates no Nix expressions, builds nothing and performs no switch. The candidate is validated as a direct store path with both system and user unit directories in the store. Observation implementation

vug system observe-os --candidate "$candidate" > observation.json

The relative symlink spelling is rejected before any observation. Captured with vug 0.2.29:

$ vug system observe-os --candidate ./result
invalid Nix store path "./result"
$ echo $?
254

Read the static diff

Field under static_diffInterpretation
from_toplevel, candidate_toplevelThe exact running and proposed store paths. Vug checks whether the running generation changed during observation.
packagesbasis: "local_store_closure", with added and removed store paths. The candidate toplevel is excluded from additions and the running toplevel from removals.
unitsAdded, removed or modified definitions under etc/systemd/system and etc/systemd/user. Entries compare definitions, masks, aliases, per-unit drop-ins and dependency links, including .wants, .requires and .upholds links. A drop-in is a supplementary configuration file that systemd merges with a unit.
shared_drop_insChanges to shared configuration such as service-wide, template or dash-prefix drop-ins, listed by selector. Effective precedence is resolved at runtime.
runtime_observationsSuccessful system or invoking-UID user manager queries. Each observation has scope, uid, observed_at_unix_seconds and loaded_units, restricted to changed units that appeared in the manager’s snapshot.

A changed NixOS user tmux-server.service reports protected: true and guard: "blocked". Other unit changes show guard: "observe_only". All unit changes report restart_prediction: "unknown" and can_override_restart_policy: false. An empty manager list means that no manager was observed. Static diff and unit traversal

Request privileged observation

Dry activation invokes the candidate’s bin/switch-to-configuration dry-activate to report prospective system actions. The child acquires the system switch lock, performs pre-switch checks and accesses privileged state in /run/nixos. Only an administrator should authorize the exact candidate after reviewing the privileged code it can run.

sudo vug system observe-os --candidate "$candidate" --dry-activate > observation.json

The administrator allowlist is /etc/vug-observe-os.allow, a root-owned, non-symlink regular file that group and others cannot write. It accepts one exact store path per line, with blank lines and lines beginning with # permitted. Vug also checks the candidate’s directory, its bin directory and the resolved activation executable before launching it. The pinned Nixpkgs dry activation returns from its system branch before enumerating user unit actions. System observation documentation Authorization and child process

Without the flag, dry_activate.status is not_requested. A child that exits successfully yields completed. A failed child yields failed and vug still prints JSON before returning 255. The report includes exit_code, system_stdout and system_stderr, with signal for a spawned child and error if spawning fails. An authorization or candidate validation error can stop the command before it writes a report.

Describe post-switch work separately

Pass --postprocess nixos-configuration:make-switch to look up the operations registered for that ID. Vug hashes the provisioned /etc/vug/observe-os/Makefile with SHA-256. A matching file yields makefile_postprocess.status: "registered" and an operations list. Vug reads the Makefile for the version check and does not execute it. An unrecognized ID, a missing or unreadable file, or different bytes yields unknown with a reason. Omitting the flag yields not_requested. Postprocess implementation

Interpret the report

This sanitized projection shows three of the four top-level sections. The paths and empty arrays are illustrative.

{
  "static_diff": {
    "from_toplevel": "/nix/store/00000000000000000000000000000000-nixos-system-example-host-old",
    "candidate_toplevel": "/nix/store/11111111111111111111111111111111-nixos-system-example-host-new",
    "packages": {"basis": "local_store_closure", "added": [], "removed": []},
    "units": [],
    "shared_drop_ins": [],
    "runtime_observations": []
  },
  "dry_activate": {"status": "not_requested"},
  "makefile_postprocess": {"status": "not_requested"}
}

The fourth section, unobservable_effects, gives each item an effect, reason and suggested verification. Use it as a checklist:

  • Review activation code and compare application state before and after activation in an isolated VM.
  • Compare swapon --show for swapfile effects.
  • Check whether Docker and Compose workloads stay up.
  • Inspect systemctl --user list-units in each relevant user’s session.
  • Inspect effective units and systemd generator output for runtime units, instance expansion and shared drop-in precedence.

Reports can include local paths and child output. Review those fields before sharing. Report and checklist definitions

The Package Registry: vug-packages

Read and validate the Starlark records that connect package versions to cached Nix outputs or reviewed overlay recipes.

Find a package and its versions

A registry is a package ledger. It uses sharding, or grouping entries into directories by a fixed rule, to keep the package tree easy to traverse. The first two characters of the name form its shard. A one-character name uses that character followed by an underscore, so x lives under packages/x_/x/.

lib/*.star
packages/<shard>/<name>/package.star
packages/<shard>/<name>/versions/<version>.star
packages/<shard>/<name>/patches/*.patch

A package file exports PACKAGE, a version file exports RECORD, and the version value must match the filename stem. Starlark is a deterministic, Python-like language used here to produce data. Records have no general filesystem, environment, network or subprocess access. load() accepts shared modules such as //lib/records.star and relative .star modules within the same package. Symlinks and cross-package imports are rejected. Record format Registry validator

Use the constructors

The shared helpers in lib/records.star build the dictionaries the evaluator expects. This package and version use the pinned ImageMagick record’s values. Constructors

# packages/im/imagemagick/package.star
load("//lib/records.star", "package")

PACKAGE = package(
    name = "imagemagick",
    license = "Apache-2.0",
    sources = ["https://cache.nixos.org/"],
)
# packages/im/imagemagick/versions/7.1.2-35.star
load("//lib/records.star", "nix_output")

RECORD = nix_output(
    version = "7.1.2-35",
    nixpkgs_rev = "2786a2a72088ecf32aea5b3ec52099e6a7cff78f",
    nix_attribute = ["imagemagick"],
)

package() describes the package and its upstream URL prefixes, with an optional homepage. nix_output() points to an existing Nix output. It defaults to outputs = ["out"] and nix_system = "x86_64-linux". The attribute is a list of path components. A nix-output record cannot declare a source, patches or dependencies. Management resolves the outputs at the pinned revision and checks the closure against trusted caches. ImageMagick metadata ImageMagick version

An overlay changes a package in the Nixpkgs package set. Use overlay_record() for a version that needs a fixed source and one of the registry’s recipes. This illustrative demo record assumes its package lists https://example.org/demo/ under sources. Replace the example URL and hash with a real source and its SHA-256 before submitting it.

# packages/de/demo/versions/1.0.star
load("//lib/records.star", "overlay_record")

RECORD = overlay_record(
    version = "1.0",
    source = {
        "url": "https://example.org/demo/demo-1.0.tar.gz",
        "sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
    },
    visibility = "public",
    reason = "upstream-binary",
    recipe = "unpack-elf",
    overlay = "demo",
    nixpkgs_rev = "2786a2a72088ecf32aea5b3ec52099e6a7cff78f",
    nix_attribute = ["demo"],
)

Public overlays require visibility = "public" and one of four reasons: fast-lane for an early update, missing for a package absent from the usual selection, patch for a needed fix, or upstream-binary for a binary release. The recipe still has to work at the stated attribute. nix-package overrides a derivation’s version and source and appends declared patches to the existing ones. unpack-elf installs an upstream archive into out and uses Nix’s ELF patching hook to fix binary paths. Declare each patch by file and lowercase hexadecimal sha256. An overlay may also list package IDs in dependencies.build or dependencies.run. Registry rules Gate recipes

Keep private exceptions in a separate access-controlled ledger. Their URLs, revisions, artifacts and closures belong there. Serve their outputs from an authenticated cache such as Attic or private Cachix, and permit that HTTPS substituter and its signing key only for the intended profile in trust.toml. Private origins require vug-owned. Cache authentication controls access to the bytes, while the signing key verifies the cache metadata. Private exceptions Cache trust

Validate and prepare a pull request

From the registry root, run vug record check-tree --root .. The following output is from a clean export of the pinned registry evaluated with vug 0.2.29.

$ vug record check-tree --root .
{
  "Errors": [],
  "Packages": 99,
  "Versions": 99
}

Use vug record check-tree --root . --evaluated to include the Records object keyed by record path. Each value is a normalized object, so defaults such as empty dependency arrays may appear even though the source omitted them. --evaluated requires JSON output. A validation error returns 254 and leaves out Records. This check validates schema, local references and patch bytes. To verify official cache coverage, run the registry’s separate script with a base and a head that describe the checked-out candidate:

VUG=vug python3 .github/scripts/nix-outputs.py record check-closure \
  --base origin/master --head HEAD

It checks changed nix-output version records (or all such records when shared helpers change), resolves the pinned outputs and validates the official cache.nixos.org-1 signatures across their closures. Keep each package contribution to one package directory, choose a Nixpkgs revision whose outputs the cache serves, and state the reason for an overlay in the PR. Changes to shared helpers require owner approval. The merge gate also verifies provenance and runs isolated checks. Contribution rules Closure script

Merge Checks and the Automated Gate

Follow a registry pull request from its evaluated Git diff through provenance, isolated builds and the check that authorizes a merge.

Eight checks on the same candidate

A candidate identity binds a base commit, head commit, candidate Git tree and policy digest. The provenance policy is a trusted JSON document specifying which source URLs and patch origins can count as evidence. The managed workflow evaluates the base and candidate trees with its own pinned vug and uses its own policy. Merge check contract Managed inspection

CheckEvidence
1. Format and evaluationBoth trees must yield valid normalized Starlark records. Changes to a shared module also select packages that import it, directly or transitively.
2. Diff scopedecide-merge classifies paths, Git modes and evaluated record changes. It rejects empty diffs, duplicate paths and modes other than 100644 and 100755.
3. Source originsEach source must match a declared prefix and either the base package’s trusted prefixes or the fixed Nixpkgs mapping for a new package, with maintainer-approved additions. Matching compares parsed host, effective port and path prefix. A candidate-only declaration requires approval, and an undeclared source fails.
4. Source hashesFetch approved sources over HTTPS, from public IP addresses, and compare SHA-256. Redirects must stay within trusted or explicitly allowed redirect prefixes. Each source may be up to 512 MiB. The verifier follows up to five redirects and gives each HTTP request 30 seconds to finish, including reading the response body. A blocked redirect or hash mismatch fails. An unavailable download leaves the check incomplete.
5. Patch provenanceCompare the candidate patch bytes with a file from pinned Nixpkgs or an approved upstream raw_root plus commit and path. The upstream repository must cover a trusted source prefix. Downloads use a fixed destination, public HTTPS and an 8 MiB limit. Missing approval for an origin requires review, different bytes from a pinned file fail, and unavailable evidence leaves the check incomplete.
6. Realisation and testsMaterialize the Nix outputs and verify their NAR hashes. Check each ELF program’s application binary interface (ABI) by following its interpreter and library dependencies within the closure and requiring one file per SONAME, the loader’s shared-library name, per process. Enumerate executable entries under bin/ and libexec/ and run each with --version in a Nix sandbox. A timeout, signal or missing loader or library fails the smoke test. Zero entry points yields a reported skip.
7. Build-time reverse dependenciesSelect packages that depend on affected packages through dependencies.build, using both trees so deleted edges still count. Build their records against changed candidate overlays. Nested scopes use overrideScope where available so siblings see the changed package. For each applicable overlay record, prove that its exact derivation appears among the dependant’s requisites and matches the derivation built by the overlay’s own check.
8. Independent repeatA separate runner realises the impacted records again and uses nix build --rebuild for each impacted derivation, including ordinary nix-output records. Both jobs must agree on output paths and NAR hashes, and the repeat must confirm the local rebuild.

Checks 4 and 5 run after the preceding provenance check passes for that package. The build plan includes impacted packages plus build-time reverse dependencies, up to 12 packages. The managed workflow takes candidate build data as JSON, pins the Nixpkgs revision and archive hash in a trusted policy, and disables import-from-derivation. It ordinarily substitutes plain nix-output outputs from the signed official cache first and builds overlay-dependent records in the Nix sandbox. A revision missing from the trusted policy or an overlay without a fixed HTTPS source can leave isolated checks incomplete. For Check 6, PT_INTERP identifies the loader and DT_NEEDED names its required libraries. Resolution searches DT_RUNPATH or DT_RPATH (which can be inherited), then the loader directory. Even an empty DT_RUNPATH suppresses DT_RPATH. Provenance verifier Build and result processing Overlay evaluation

Request and interpret a report

vug record verify-provenance --root /path/to/repository \
  --input file://candidate.json --policy file://policy.json \
  --source-cache-dir verified-sources
vug record decide-merge --input file://request.json

Both requests set schema_version: 1 and supply an identity record containing base_sha, head_sha, tree_oid, and policy_digest. Each Git identifier shares one object format (40 or 64 lowercase hexadecimal digits), while policy_digest is the 64-character lowercase SHA-256 of the provenance policy bytes. The caller authenticates the candidate and the trusted policy. The verifier inspects Git objects under --root and can save verified downloads by their SHA-256.

Field in the provenance policyContents
schema_version1
nixpkgs_commitFull 40-character lowercase commit for the policy’s Nixpkgs recipes and patches.
new_package_sourcesMap of package names to URL-prefix arrays derived from pinned recipes.
approved_sources, redirect_sourcesMaps of package names to extra approved source and redirect URL prefixes.
patch_originsMap from patch path to a pin. For kind: "nixpkgs", supply path. For kind: "upstream", supply repository, raw_root, commit and path. The maintainer associates the HTTPS raw endpoint with the upstream repository.

Supply empty maps when there are no entries. The verifier reports SchemaVersion, Results and Findings. Its result rows can feed the decision alongside the other checks. A completed verification report returns exit 0 even if a finding blocks a merge. Invalid input, policy or Git object data returns 254. Provenance schema and result types Command status handling

Add these fields to a decide-merge request:

  • core_packages is the list of package names designated by the trusted policy.
  • changes contains one {path, before, after} per changed path. A present side carries a Git mode and, for regular records, the normalized evaluated value from check-tree --evaluated. Use null for a missing side and split renames into separate deletion and addition entries.
  • required_checks contains objects with check and target. Include Checks 1 and 3–8 for each touched package, plus Check 1 for target . when there is a path outside packages/ or no recognized package. Include extra targets selected by policy or provenance. Check 2 is computed from changes.
  • results contains objects with check, target, identity, status and optional output_id. Status is passed, failed or incomplete. Checks 3 and 5 can also return requires_approval.

record_change covers ordinary changes to recognized package paths. approval_change covers package-only changes that need review, for example a deleted version, a changed existing source, an added or changed overlay or patch, a core package, a nonstandard package path or an executable file. A provenance exception can also move a package-only candidate into this class. repository_change takes precedence for changes outside packages/, including shared helpers. Inspect Scope separately to see the diff check’s result even when a provenance exception determines the class. Decision model and output types

DecisionWhat the evidence supports, in precedence order
rejectScope or a check failed, or the supplied evidence was inconsistent, such as a duplicate or unexpected target, invalid check status or mismatched identity.
incompleteA required target is absent or its result is missing or unfinished.
requires_approvalRequired checks are complete and the scope or provenance needs review.
auto_mergeThe diff is a record change with all required checks passed.

The JSON report echoes the identity in top-level fields BaseSha, HeadSha, TreeOid, PolicyDigest, and includes SchemaVersion, ChangeClass, Scope, Decision, AffectedPackages, Reasons and IncompleteChecks. Exit 0 means the command computed the report. Read Decision for the verdict. Malformed requests return 254.

In the walkthrough, a synthetic one-package addition supplies a passed Check 1 and deliberately leaves Checks 3–8 without results. Vug 0.2.29 produced this projection:

$ vug record decide-merge --input file://request.json | jq '{ChangeClass, Scope, Decision, missing: [.IncompleteChecks[].Check]}'
{
  "ChangeClass": "record_change",
  "Scope": "passed",
  "Decision": "incomplete",
  "missing": [
    3,
    4,
    5,
    6,
    7,
    8
  ]
}

From decision to merge

The inspection App publishes evidence. A separate merge App acts only after the Worker verifies the current candidate.

  1. Intake and dispatch. A GitHub App sends webhooks to a Cloudflare Worker. A Durable Object is a stateful Cloudflare component with persistent storage. The gate uses one SQLite-backed object to reserve queue slots and persist executions. Defaults allow one running and one waiting PR per author and one running PR globally. A changed head or base cancels the obsolete run before its slot is reused.
  2. Management identity. The Worker assigns an execution UUID and dispatches against MANAGEMENT_REF, a mutable ref. It expects the resulting run at the deployed MANAGEMENT_SHA. A redeploy can trigger inspection again even if the policy digest stayed the same. An unconfirmed dispatch expires after 15 minutes, releases capacity and can be requeued with a new UUID. Late callbacks for the expired UUID are refused.
  3. Authenticated callback. OIDC (OpenID Connect) supplies a short-lived GitHub Actions identity token to the callback job. The Worker checks issuer, audience, repository ID, workflow and commit, dispatch event, hosted runner, run ID and first attempt, then validates the result against the active execution and reads GitHub again before publishing a successful vug/merge-policy check on the inspected head. An auto_merge decision earns success directly. For an enabled merge target, an eligible review can also give a requires_approval candidate a successful check.
  4. Verify and merge. refs/pull/<n>/merge is GitHub’s synthetic test merge ref for PR number n. The Worker verifies that its parents are the inspected base and head and that its tree matches. It publishes vug/verified-merge-tree from the inspection App on the head SHA and calls the squash-merge API using that SHA as the expected head. Strict branch protection requires the head to stay up to date with the base before merging. Pair it with the required verified-tree check from the inspection App so a base advance blocks a stale success. The separate app/vug-merge installation can merge only the repository and branch authorized by MERGE_INSTALLATION. For requires_approval, it needs an APPROVED review of the current head from a non-author administrator, or a non-author in APPROVER_USER_IDS with write, maintain or admin permission.
  5. Halt and recover. Before the API call the queue persists the attempt. It verifies that the squash commit has the inspected base as its sole parent and the inspected tree. After an ambiguous response it reads GitHub to identify the resulting commit, using the merged issue event if the PR has no merge commit SHA. A mismatch, an unidentifiable merge commit for a merged PR, or five failed reads sets merge_halted, a durable flag that immediately blocks further merge calls. Check revocation happens asynchronously for runs the queue still tracks. After investigating, clear the merge_halted row from the Durable Object’s state table to resume.

Before a merge call, the Worker rechecks success of both App checks, the current candidate identity and the test merge tree. Gate architecture and deployment Queue and merge state Callback workflow GitHub merge verification

Smoke and acceptance trials

From the management repository, supply a known merged package commit and its parent. This manual smoke run prints a decision in Actions and skips the callback.

gh workflow run merge-policy.yml \
  -f candidate='{"repo":"OWNER/REPO","base_sha":"PARENT_SHA","head_sha":"COMMIT_SHA"}'

Use an isolated sandbox repository to exercise webhook delivery and merge protections. Submit a clean version addition, then a candidate that also changes its own workflow, and verify that only the managed job can earn the inspection check. Change a PR head or move the base during a run and verify replacement of the old execution. Test queue limits with multiple PRs from one author and another author, including webhook redelivery. With merge enabled on the sandbox, compare the resulting parent and tree with the inspected identity, and test that a base advance blocks merging from an old head check. Smoke and sandbox instructions

End-to-End Walkthrough and Glossary

Build a tiny ImageMagick profile, inspect the evidence for its package record, and trace two signed generations through activation and rollback.

Build and inspect the demo

Use vug 0.2.29, a shell and jq for the registry portion. It runs in an ordinary temporary directory. For the live lifecycle portion, use a disposable Linux VM with an x86-64 Nix daemon, a running systemd user manager, Linger=yes, and an immutable vug executable as described in Installation, Trust Policy, and Host Checks. The VM is where the example writes a home dotfile and changes the active generation.

1. Write the declaration and registry

Start in a new directory and give the profile an unambiguous target. Set the VM’s hostname and user to the example values or substitute its actual lowercase hostname and account name in the declaration.

lab="$(mktemp -d)"
mkdir -p "$lab/registry/packages/im/imagemagick/versions" "$lab/v1" "$lab/v2"
cd "$lab"

cat > v1/vug.star <<'STAR'
def configure(ctx):
    return {
        "schema_version": 1,
        "profile": {
            "id": "demo",
            "kind": "home",
            "host": "example-host",
            "user": "example-user",
            "system": "x86_64-linux",
            "store_backend": "nix-daemon",
        },
        "nixpkgs": {
            "rev": "2786a2a72088ecf32aea5b3ec52099e6a7cff78f",
            "allow_unfree": False,
            "permitted_insecure": [],
        },
        "packages": {
            "imagemagick": {"attr": ["imagemagick"], "outputs": ["out"]},
        },
        "dotfiles": {
            ".config/vug-book-demo.conf": {"owner": "vug", "source": "demo.conf"},
        },
        "commands": {
            "image-info": {
                "package": "imagemagick",
                "output": "out",
                "executable": "bin/magick",
                "args": ["--version"],
            },
        },
    }
STAR
printf 'profile=first\n' > v1/demo.conf

cat > registry/packages/im/imagemagick/package.star <<'STAR'
PACKAGE = {
    "schema_version": 1,
    "name": "imagemagick",
    "license": "Apache-2.0",
    "upstream": {"sources": ["https://cache.nixos.org/"]},
}
STAR

cat > registry/packages/im/imagemagick/versions/7.1.2-35.star <<'STAR'
RECORD = {
    "schema_version": 1,
    "version": "7.1.2-35",
    "build": {
        "kind": "nix-output",
        "nix_system": "x86_64-linux",
        "nixpkgs_rev": "2786a2a72088ecf32aea5b3ec52099e6a7cff78f",
        "nix_attribute": ["imagemagick"],
        "outputs": ["out"],
    },
}
STAR

vug record check-tree --root registry
vug record check-tree --root registry --evaluated > records.json

The mini-registry has one package and one version, with Errors: []. Its package and version correspond to the declaration’s Nixpkgs attribute, but the declaration already has the information to resolve this ordinary Nix output. A registry checkout becomes a direct lock input when the declaration selects an overlay. Writing declarations ImageMagick version record

2. Compute a merge decision

Model both records as additions. The repeated hex strings are fixture IDs, and the only supplied evidence is the local format check. In a real workflow the caller takes the identity and diff from Git, hashes the actual policy, and authenticates each check result.

jq '{
  base_sha: ("0" * 40),
  head_sha: ("1" * 40),
  tree_oid: ("2" * 40),
  policy_digest: ("3" * 64)
} as $id | {
  schema_version: 1,
  identity: $id,
  core_packages: [],
  changes: [.Records | to_entries[] | {
    path: .key, before: null, after: {mode: "100644", evaluated: .value}
  }],
  required_checks: [1, 3, 4, 5, 6, 7, 8] | map({check: ., target: "imagemagick"}),
  results: [{check: 1, target: "imagemagick", identity: $id, status: "passed"}]
}' records.json > request.json

vug record decide-merge --input file://request.json > decision.json
jq '{ChangeClass, Scope, Decision, missing: [.IncompleteChecks[].Check]}' decision.json

Expect record_change, a passed scope and an incomplete verdict, with Checks 3–8 missing. decide-merge computes from the supplied results. Merge request contract

3. Set up trust and create signed locks

Use the management role to create the lock-signing key. In this one-VM lab the same person can perform both roles. Save the trust file below with mode 0600 at $XDG_CONFIG_HOME/vug/trust.toml (default ~/.config/vug/trust.toml). Replace the placeholder with the part after demo-lock: from lock.pub. Keep lock.sec private on the management side.

(umask 077
 nix-store --generate-binary-cache-key demo-lock "$lab/lock.sec" "$lab/lock.pub")
schema_version = 1

[lock_keys]
demo-lock = "<base64 public half from lock.pub>"

[substituters."https://cache.nixos.org"]
profiles = ["demo"]

[substituters."https://cache.nixos.org".keys]
"cache.nixos.org-1" = "6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY="

Set VUG_RUNTIME to the store output of vug 0.2.29 that contains bin/vug. Management needs signed cache metadata for that output and every reference, including any new runtime paths it introduces. If the official cache does not have the runtime, use a provisioned HTTPS lab cache with signed contents. Add its URL, key and profiles = ["demo"] to the trust file, and configure that public-to-the-VM origin and key in the daemon. A locally built runtime alone does not supply the cache metadata that the lock command checks. Use a currently cached Nixpkgs revision if the example’s package closure is no longer served, and update both declaration and registry accordingly. Lock inputs and cache requirements Cache trust schema

trust="${XDG_CONFIG_HOME:-$HOME/.config}/vug/trust.toml"
cd "$lab"

vug record lock --file v1/vug.star --trust "$trust" \
  --signing-key "$lab/lock.sec" --runtime "vug=${VUG_RUNTIME:?set VUG_RUNTIME}:bin/vug"

The lock is written next to v1/vug.star. The initial trust file, the signed lock and the declaration’s inputs are what the client needs. Keep the signing key out of the client bundle. Lock implementation

4. Plan, apply, run and roll back

In the VM, start with no demo generation and no existing demo dotfile. Review each plan before its apply command. Run apply as the target user.

cd "$lab"
vug store doctor --file v1/vug.star
vug home plan --file v1/vug.star > plan-v1.json
jq . plan-v1.json
vug home apply --plan plan-v1.json --wait
first="$(vug home status --profile demo | jq -er '.active_generation')"
vug home dev --file v1/vug.star -- magick --version
vug home run --file v1/vug.star --command image-info
cat "$HOME/.config/vug-book-demo.conf"

For generation two, retain the first inputs and create a second declaration with changed fixed command arguments and dotfile bytes. Sign its lock on the management side before planning the new generation.

sed 's/"--version"/"-list", "format"/' v1/vug.star > v2/vug.star
printf 'profile=second\n' > v2/demo.conf

vug record lock --file v2/vug.star --trust "$trust" \
  --signing-key "$lab/lock.sec" --runtime "vug=$VUG_RUNTIME:bin/vug"

vug home plan --file v2/vug.star > plan-v2.json
jq . plan-v2.json
vug home apply --plan plan-v2.json --wait
vug home run --file v2/vug.star --command image-info
cat "$HOME/.config/vug-book-demo.conf"

The first invocation prints version information. The second generation lists available formats. The dotfile changes from profile=first to profile=second. With the first generation still retained, plan the rollback from the current profile and apply it separately.

vug home rollback --file v2/vug.star --generation "$first" > rollback.json
jq . rollback.json
vug home apply --plan rollback.json --wait
vug home status --profile demo
vug home run --file v1/vug.star --command image-info
cat "$HOME/.config/vug-book-demo.conf"

The declared command returns to version reporting and the file returns to profile=first. Compare the observable content and command behavior after each apply. If a precondition changes, make a fresh plan from the intended inputs. If the operation stops in an uncertain state, inspect its operation status and follow the recovery procedure. For system-level changes in the VM, use NixOS observation on an already built toplevel. Home rollback applies to the home profile. Home lifecycle Home command implementation

Glossary

TermDefinition
ABIApplication binary interface, the binary-level contract among executables, loaders and libraries.
ActivationThe operations that make a prepared generation active. Home activation and NixOS system activation are separate.
ApplyExecute a saved home plan after rechecking its assumptions under the operation lock.
Attic / CachixServices for hosting Nix binary caches. A private cache requires authentication as well as trusted signatures.
Binary cacheA server that supplies prebuilt Nix store objects and their metadata.
Bind mountA mount that makes a host file, directory, device or socket visible at a path in another filesystem view.
BubblewrapLinux namespace launcher used by vug for isolation and mount setup.
Candidate identityThe base commit, head commit, tree ID and policy digest that bind check results to one candidate.
ClosureA set of store objects together with every transitively referenced object.
DeclarationThe environment data returned by configure(ctx) in vug.star.
DerivationNix’s recipe for building an output, identified by its .drv store path.
Drop-inA supplemental systemd configuration file merged with a unit definition.
Dry activationThe candidate’s switch-to-configuration dry-activate action, guarded by root authorization and used to observe prospective system actions.
Durable ObjectCloudflare’s stateful execution and storage component. The gate uses one SQLite-backed object for its queue.
ELFExecutable and Linkable Format, the Linux format for native executables and shared libraries.
FHSFilesystem Hierarchy Standard. In vug, a command can request a locked x86-64 layout with familiar paths under /usr.
Garbage collection (GC)Removal of unreferenced store objects and unneeded generations. Roots and leases keep the relevant data live.
GC rootA reference that keeps a store object and its closure reachable for garbage collection.
GenerationA saved activation snapshot of a profile with its declaration, lock and managed state.
Generation leaseA shared lock held while a command uses a generation, protecting it from GC.
Git tree IDThe Git object ID of a file hierarchy, including its entries’ modes and object IDs.
LingerA logind setting that keeps a user’s systemd manager available beyond an interactive login.
LockThe signed vug.lock binding a normalized declaration, package outputs, fixed tools and closure metadata.
Management CIThe trusted workflow that resolves and signs locks or runs gate checks using managed inputs.
Merge haltThe durable merge_halted flag that blocks further merge calls when a merge outcome cannot be reconciled.
NARNix Archive, the canonical serialized form of a Nix store object.
NarinfoCache metadata for a store path, including its NAR hash, references and signatures.
NixOS toplevelThe store path representing one built NixOS system generation.
NixpkgsThe package collection and Nix expressions that vug resolves at a pinned commit.
OIDCOpenID Connect. GitHub Actions uses it to issue a short-lived token that identifies the callback job.
OutputOne named result of a derivation, such as out or dev.
OverlayA change to the Nixpkgs package set used to substitute a reviewed package recipe.
PlanA saved read-only report of intended changes and observed preconditions.
ProfileThe declared environment identity for a target host, user, system and store backend.
Protected unitA systemd unit subject to vug’s protective guard, including tmux-server.service.
Provenance policyThe trusted rules and pinned origins used to verify source and patch evidence.
RealisationMaking the output of a Nix derivation available locally by substitution or building it.
RecoveryRetrying guarded restoration after an interrupted or uncertain home operation.
RegistryA ledger of Starlark package and version records in a defined directory layout.
Reverse dependencyA package that depends on the package under review. The gate follows build-time edges for Check 7.
RollbackPlanning and applying a return to a retained home generation.
ShardA directory grouping determined by the first two package-name characters, or one character plus _.
Smoke testA limited execution check. The gate invokes enumerated executables with --version.
SONAMEA shared object’s loader-visible name, for example libexample.so.1.
StarlarkA deterministic Python-like language used to describe environments and registry data.
Store backendThe mechanism that houses the closure. nix-daemon uses the shared Nix store and vug-owned uses a private store.
Strict branch protectionGitHub’s up-to-date requirement for a PR head when checking whether the protected branch can accept its merge.
SubstituterA configured binary cache origin used to fetch store objects instead of building them.
Systemd managerThe service manager for the system or a particular user. Vug can query a reachable manager’s loaded units.
Test merge refrefs/pull/<n>/merge, GitHub’s synthetic merge of a pull request used to compare its parents and resulting tree.
Trust policytrust.toml, which sets allowed lock-signing keys, substituters, cache keys and local protections.
User / PID namespaceIndependent Linux views of user and group IDs or process IDs, respectively.
Verified merge treeThe tree whose parents and contents the gate has checked before publishing vug/verified-merge-tree on the head.