Compare commits

17 Commits

Author SHA1 Message Date
30e5b1e677 docs: add project task notes 2026-10-18 01:16:20 -04:00
45a840002f refactor(skills): remove redundant skills 2026-10-17 22:04:31 -04:00
a9db1f8b7c feat(skills): add agent writing guide 2026-10-17 22:04:31 -04:00
dcc4efcc75 fix(rofi): migrate Home Manager options 2026-10-15 18:16:47 -04:00
a23a317335 build(nix): update flake inputs 2026-10-15 18:16:47 -04:00
6e545c0a15 build(pi): integrate vendored Pi 1.3.0 2026-10-15 18:05:57 -04:00
6081e3e325 chore(vendor): import pi 1.3.0
Imported as a linear vendor commit so forge rebases do not replay the upstream root tree.

git-subtree-dir: third_party/pi

git-subtree-split: 71023aec1546d6d677a65669c5665c0927ce0dd0
2026-10-15 17:58:48 -04:00
719370c8f7 refactor(bazel): inline the primary user 2026-10-15 14:23:18 -04:00
2b4e66a75c fix(palworld): configure the RCON port 2026-10-15 14:18:27 -04:00
c44769ff70 refactor(steamcmd): constrain service names 2026-10-15 14:13:07 -04:00
1397576538 refactor(reverse-proxy): simplify virtual host generation 2026-10-15 13:57:45 -04:00
5fbe1850e0 docs(tasks): organize task areas 2026-10-14 18:18:18 -04:00
57bb21af1a feat(vault): add task workflow 2026-10-14 01:24:22 -04:00
ffc40e547b feat(skills): add Conventional Commits skill 2026-10-13 22:49:44 -04:00
55f61f71d8 refactor(natu): remove custom Nix linter 2026-10-13 21:59:41 -04:00
08563c6769 refactor(nixos): remove unused direnv module 2026-10-13 21:50:37 -04:00
8462b3a5a8 refactor(copyparty): separate deployment and service policy
Move Copyparty rendering into shared dotfiles utilities, keep guest wiring focused on host/container plumbing, and let the service module derive effective volume policy.
2026-10-13 20:33:25 -04:00
2909 changed files with 243664 additions and 488863 deletions

View File

@@ -17,15 +17,6 @@ If the target includes multiple matching file types, use all matching skills.
If the target is a diff, choose skills from the changed files.
Do not use a style skill when no reviewed file matches it.
For every reviewed `*.nix` file, run:
```bash
bazel run //src/natu:natu -- <reviewed-nix-paths>
```
Pass every reviewed Nix path to Natu.
Report every Natu diagnostic as an actionable finding.
Report only actionable findings.
Order findings by severity.
Do not report preferences unless a loaded rule states them.
@@ -45,7 +36,6 @@ Keep the code excerpt to one to three lines when possible.
Use a longer excerpt only when the violation needs surrounding context.
Use `...` to omit unrelated lines from a multi-line excerpt.
Use a style-skill rule citation in the form `skill::rule-file:line`.
Cite Natu diagnostics as `natu::<rule-id>`.
Make the fix direct.
Do not include alternatives when one fix best follows the cited rule.

View File

@@ -0,0 +1 @@
../../src/skills/agent-writing-guide

View File

@@ -0,0 +1 @@
../../src/skills/conventional-commits

View File

@@ -1 +0,0 @@
../../src/skills/craft-skill

View File

@@ -1 +0,0 @@
../../src/skills/grill

View File

@@ -1 +0,0 @@
../../src/skills/to-document

View File

@@ -3,7 +3,6 @@
## Commit convention
- Use Conventional Commits for all commit messages.
Before writing a commit message, read `docs/conventional-commits.md`.
- Keep commit messages about the Git history, not the forge workflow.
Include external references only when they are stable context for the change.
- When writing commit messages, NEVER auto-add your agent name as co-author.
@@ -105,13 +104,10 @@
Do not use `nix fmt` as a validation command until a formatter is added.
- The `fix` app passes its current directory to Deadnix.
Run `nix run .#fix` from the repository root so path exclusions match.
- During the Nix refactor, address each issue that comes up by adding either a Natu rule or a new Nix style rule.
- Git pathspec searches started in a subdirectory default to that subtree.
Use `git -C <repository-root>` or top-anchored pathspecs for repository-wide history searches.
- A `**/*.nix` Git pathspec does not include Nix files directly in its starting directory.
Include both `*.nix` and `**/*.nix`, or use a recursive `*.nix` pathspec, when linting every Nix file.
- Nix `let` bindings are recursive; their source order does not determine binding availability.
Treat Natu `let_order` as a readability rule, not an evaluation dependency.
- Ariadne extraction must preserve the game-root season prefix for archived source.
Different game installs can contain compiled scripts with the same internal path.
- Clew owns Ren'Py extraction, preparation, and compiled-script AST export. Ariadne owns analysis over Clew-produced data.
@@ -122,7 +118,10 @@
- OMP does not discover project skills from `.pi/skills`.
Put skills shared by Pi and OMP under `.agents/skills`, or configure OMP's `skills.customDirectories`.
- Pi is vendored under `third_party/pi` as a linear vendor import.
`pkgs.alexion.pi-coding-agent` packages that source and does not use Nixpkgs Pi.
Do not use `git subtree add` or `git subtree pull` for Pi PR branches.
Gitea rebases the synthetic upstream root commit without the `third_party/pi` prefix.
Preserve `git-subtree-dir` and `git-subtree-split` trailers on Pi vendor commits.
- The default Pi model for NixOS user configuration is set in `configs/nixos/modules/shell/pi/default.nix`, not in vendored Pi source.
- The `monorepo` and `status` libraries do not have `README.md` files.
- Check root and `src/skills/.pi/skills/` for enabled symlinks before removing a monorepo skill.

154
Cargo.lock generated
View File

@@ -2,15 +2,6 @@
# It is not intended for manual editing.
version = 4
[[package]]
name = "aho-corasick"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
dependencies = [
"memchr",
]
[[package]]
name = "anstream"
version = "1.0.0"
@@ -71,12 +62,6 @@ dependencies = [
"serde_json",
]
[[package]]
name = "autocfg"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "clap"
version = "4.6.7"
@@ -108,7 +93,7 @@ dependencies = [
"heck",
"proc-macro2",
"quote",
"syn 3.0.6",
"syn",
]
[[package]]
@@ -123,41 +108,6 @@ version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
[[package]]
name = "countme"
version = "3.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7704b5fdd17b18ae31c4c1da5a2e0305a2bf17b5249300a9ee9ed7b72114c636"
[[package]]
name = "googletest"
version = "0.14.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6b5e2f2b556b7b90297a5a35c8267dd43a537923d2b329beefdba2b4ec19d94"
dependencies = [
"googletest_macro",
"num-traits",
"regex",
"rustversion",
]
[[package]]
name = "googletest_macro"
version = "0.14.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2ae6abc96141edd26bf5aeec0f119c129c44de3ced09e5073711a02cb74725d0"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "hashbrown"
version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
[[package]]
name = "heck"
version = "0.5.0"
@@ -190,27 +140,6 @@ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
name = "monorepo"
version = "0.1.0"
[[package]]
name = "natu"
version = "0.1.0"
dependencies = [
"clap",
"googletest",
"monorepo",
"rnix",
"rowan",
"status",
]
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]]
name = "once_cell_polyfill"
version = "1.70.2"
@@ -235,68 +164,6 @@ dependencies = [
"proc-macro2",
]
[[package]]
name = "regex"
version = "1.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
[[package]]
name = "rnix"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c163bd17372eecdf10d351c34584b7de7c1a33be4e92a32f3fb3f5a7fe3f579b"
dependencies = [
"rowan",
]
[[package]]
name = "rowan"
version = "0.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "417a3a9f582e349834051b8a10c8d71ca88da4211e4093528e36b9845f6b5f21"
dependencies = [
"countme",
"hashbrown",
"rustc-hash",
"text-size",
]
[[package]]
name = "rustc-hash"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2"
[[package]]
name = "rustversion"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
[[package]]
name = "serde"
version = "1.0.229"
@@ -324,7 +191,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.6",
"syn",
]
[[package]]
@@ -350,17 +217,6 @@ version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "syn"
version = "2.0.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "syn"
version = "3.0.6"
@@ -372,12 +228,6 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "text-size"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f18aa187839b2bdb1ad2fa35ead8c4c2976b64e4363c386d45ac0f7ee85c9233"
[[package]]
name = "unicode-ident"
version = "1.0.26"

View File

@@ -4,16 +4,12 @@ members = [
"src/machoke",
"src/monorepo",
"src/status",
"src/natu",
]
resolver = "3"
[workspace.dependencies]
clap = "4"
googletest = "0.14"
monorepo = { path = "src/monorepo" }
rnix = "=0.14.0"
rowan = "0.16"
serde = "1.0"
serde_json = "1.0"
status = { path = "src/status" }

View File

@@ -65,3 +65,6 @@
and Zeus), not in the generic host module.
- Module-relative paths resolve from the module file. Update them when moving a module into a subdirectory.
- On Pikachu, `uptime` does not support `-s`. Use `who -b` to report the boot time.
- Evaluating a NixOS guest's inner `config.services.nginx` can force incomplete ACME values.
Evaluate the parent host's `config.system.build.toplevel` to validate an ACME-enabled guest.
- `pkgs.systemd` does not set `meta.mainProgram`. Use `lib.getExe' pkgs.systemd "systemctl"` instead of `lib.getExe pkgs.systemd`.

View File

@@ -4,7 +4,7 @@
...
}:
let
cfg = config.guests.copyparty; # NOLINT(let_order)
cfg = config.guests.copyparty;
in
{
options.guests.copyparty = {

View File

@@ -4,7 +4,7 @@
...
}:
let
cfg = config.guests.homepage; # NOLINT(let_order)
cfg = config.guests.homepage;
environmentFile = "/run/secrets/homepage.env";
in
{

View File

@@ -4,7 +4,7 @@
...
}:
let
cfg = config.guests.palworld; # NOLINT(let_order)
cfg = config.guests.palworld;
steamDir = "/data/steamcmd";
installDir = "/data/server";
stateDir = "/data/state";

View File

@@ -4,7 +4,7 @@
...
}:
let
cfg = config.guests.valheim; # NOLINT(let_order)
cfg = config.guests.valheim;
steamDir = "/data/steamcmd";
installDir = "/data/server";
stateDir = "/data/state";

View File

@@ -8,7 +8,7 @@
}:
# Configures Firefox as the desktop browser.
let
cfg = config.modules.desktop.apps.firefox; # NOLINT(let_order)
cfg = config.modules.desktop.apps.firefox;
in
{
options.modules.desktop.apps.firefox = {

View File

@@ -28,12 +28,11 @@ in
# Stylix supplies the Nord theme.
programs.rofi = {
enable = true;
font = lib.mkForce "JetBrains Mono 12";
# Application launch is the only mode, kept minimal so the prompt opens
# as fast as rofi can read the desktop entries.
# Icons are off: resolving one per entry is the bulk of drun's startup.
extraConfig = {
settings = {
font = lib.mkForce "JetBrains Mono 12";
modi = "drun";
show-icons = false;
};

View File

@@ -5,7 +5,7 @@
}:
# Imports existing ZFS pools that hold durable service state.
let
cfg = config.modules.host.zfs; # NOLINT(let_order)
cfg = config.modules.host.zfs;
in
{
options.modules.host.zfs = {

View File

@@ -7,19 +7,17 @@
# Configures inbound and outbound SSH access.
let
cfg = config.modules.network.ssh;
user = config.user.name; # NOLINT(let_order)
user = config.user.name;
# NOLINT(let_order)
workstationNames = [
"neogaia"
"zeus"
];
serverNames = [ "pikachu" ];
isWorkstation = lib.elem config.networking.hostName workstationNames; # NOLINT(let_order)
isServer = lib.elem config.networking.hostName serverNames; # NOLINT(let_order)
isWorkstation = lib.elem config.networking.hostName workstationNames;
isServer = lib.elem config.networking.hostName serverNames;
# NOLINT(let_order)
clientKeyFor = host: builtins.readFile (../../hosts + "/${host}/ssh_user_ed25519_key.pub");
hostKeysFor =
host:
@@ -28,7 +26,6 @@ let
(../../hosts + "/${host}/ssh_host_rsa_key.pub")
];
# NOLINT(let_order)
managedTargets = lib.genAttrs (workstationNames ++ serverNames) (name: {
hostName = registry.address.${name}.self;
clientKey = clientKeyFor name;
@@ -48,7 +45,6 @@ let
};
};
# NOLINT(let_order)
mkTarget = name: target: {
hostName = target.hostName or name;
user = target.user or user;
@@ -57,15 +53,14 @@ let
clientKey = target.clientKey or null;
hostKeys = target.hostKeys or [ ];
};
targets = lib.mapAttrs mkTarget (managedTargets // extraTargets); # NOLINT(let_order)
targets = lib.mapAttrs mkTarget (managedTargets // extraTargets);
clientKeysFor = names: lib.filter (key: key != null) (map (name: targets.${name}.clientKey) names); # NOLINT(let_order)
# NOLINT(let_order)
clientKeysFor = names: lib.filter (key: key != null) (map (name: targets.${name}.clientKey) names);
defaultAuthorizedKeys = lib.flatten (
clientKeysFor workstationNames ++ lib.optional isServer (clientKeysFor serverNames)
);
outboundTargetNames = # NOLINT(let_order)
outboundTargetNames =
let
groupTargets =
if isServer then

View File

@@ -6,7 +6,7 @@
}:
# Configures bridges for tagged VLANs on a physical interface that uses DHCP.
let
cfg = config.modules.network.vlans; # NOLINT(let_order)
cfg = config.modules.network.vlans;
in
{
options.modules.network.vlans = {

View File

@@ -6,7 +6,7 @@
...
}:
let
cfg = config.modules.network.vpn-client; # NOLINT(let_order)
cfg = config.modules.network.vpn-client;
vpnIcon = util.glyph [
"db83"

View File

@@ -6,7 +6,7 @@
...
}:
let
cfg = config.modules.services.copyparty; # NOLINT(let_order)
cfg = config.modules.services.copyparty;
accountName = config.user.name;

View File

@@ -92,33 +92,33 @@
startScript = pkgs.writeShellScript "palworld-start" ''
set -eu
${pkgs.coreutils}/bin/install -d \
${lib.getExe' pkgs.coreutils "install"} -d \
-m 0770 \
${lib.escapeShellArg service.stateDir} \
${lib.escapeShellArg (builtins.dirOf savedDir)}
if [ -L ${lib.escapeShellArg savedDir} ]; then
current_target="$(${pkgs.coreutils}/bin/readlink ${lib.escapeShellArg savedDir})"
current_target="$(${lib.getExe' pkgs.coreutils "readlink"} ${lib.escapeShellArg savedDir})"
if [ "$current_target" != ${lib.escapeShellArg service.stateDir} ]; then
${pkgs.coreutils}/bin/rm ${lib.escapeShellArg savedDir}
${lib.getExe' pkgs.coreutils "rm"} ${lib.escapeShellArg savedDir}
fi
fi
if [ -d ${lib.escapeShellArg savedDir} ] && [ ! -L ${lib.escapeShellArg savedDir} ]; then
if ${pkgs.findutils}/bin/find ${lib.escapeShellArg service.stateDir} -mindepth 1 -maxdepth 1 | ${pkgs.gnugrep}/bin/grep -q .; then
${pkgs.coreutils}/bin/rm -rf ${lib.escapeShellArg savedDir}
if ${lib.getExe' pkgs.findutils "find"} ${lib.escapeShellArg service.stateDir} -mindepth 1 -maxdepth 1 | ${lib.getExe' pkgs.gnugrep "grep"} -q .; then
${lib.getExe' pkgs.coreutils "rm"} -rf ${lib.escapeShellArg savedDir}
else
${pkgs.coreutils}/bin/cp -a ${lib.escapeShellArg savedDir}/. ${lib.escapeShellArg service.stateDir}/
${pkgs.coreutils}/bin/rm -rf ${lib.escapeShellArg savedDir}
${lib.getExe' pkgs.coreutils "cp"} -a ${lib.escapeShellArg savedDir}/. ${lib.escapeShellArg service.stateDir}/
${lib.getExe' pkgs.coreutils "rm"} -rf ${lib.escapeShellArg savedDir}
fi
fi
if [ ! -e ${lib.escapeShellArg savedDir} ]; then
${pkgs.coreutils}/bin/ln -s ${lib.escapeShellArg service.stateDir} ${lib.escapeShellArg savedDir}
${lib.getExe' pkgs.coreutils "ln"} -s ${lib.escapeShellArg service.stateDir} ${lib.escapeShellArg savedDir}
fi
password="$(${pkgs.coreutils}/bin/tr -d '\n' < ${lib.escapeShellArg service.passwordFile})"
admin_password="$(${pkgs.coreutils}/bin/tr -d '\n' < ${lib.escapeShellArg service.adminPasswordFile})"
password="$(${lib.getExe' pkgs.coreutils "tr"} -d '\n' < ${lib.escapeShellArg service.passwordFile})"
admin_password="$(${lib.getExe' pkgs.coreutils "tr"} -d '\n' < ${lib.escapeShellArg service.adminPasswordFile})"
exec ./PalServer.sh \
"$@" \
@@ -145,9 +145,12 @@
]
++ lib.optional service.publicLobby "-publiclobby"
++ lib.optionals (service.publicIP != null) [ "-publicip=${service.publicIP}" ]
++ lib.optional service.rcon.enable "-rcon";
++ lib.optionals service.rcon.enable [
"-rcon"
"-RCONPort=${toString service.rcon.port}"
];
udpPorts = [ service.port ];
tcpPorts = [ service.port ];
tcpPorts = lib.optional service.rcon.enable service.rcon.port;
};
}
);

View File

@@ -51,7 +51,7 @@
startScript = pkgs.writeShellScript "valheim-start" ''
set -eu
password="$(${pkgs.coreutils}/bin/tr -d '\n' < ${lib.escapeShellArg service.passwordFile})"
password="$(${lib.getExe' pkgs.coreutils "tr"} -d '\n' < ${lib.escapeShellArg service.passwordFile})"
exec ./valheim_server.x86_64 "$@" -password "$password"
'';
in

View File

@@ -5,7 +5,7 @@
...
}:
let
cfg = config.modules.services.homepage; # NOLINT(let_order)
cfg = config.modules.services.homepage;
derivedAllowedHosts = lib.unique (
lib.optional (selfRoute != null) selfRoute.domain

View File

@@ -4,7 +4,7 @@
...
}:
let
cfg = config.modules.services.navidrome; # NOLINT(let_order)
cfg = config.modules.services.navidrome;
in
{
options.modules.services.navidrome = {

View File

@@ -40,43 +40,14 @@ let
proxy_pass ${stream.address}:${toString stream.port};
}
'') generatedUdpStreams;
generatedVirtualHosts =
if duplicateDomainMessages != [ ] then
throw (builtins.head duplicateDomainMessages)
else
lib.listToAttrs generatedVirtualHostList;
generatedVirtualHosts = lib.listToAttrs generatedVirtualHostList;
duplicateDomainMessages = lib.concatLists (
lib.mapAttrsToList (
domain: virtualHosts:
if lib.length virtualHosts > 1 then
[
"duplicate route domain ${domain} in ${
lib.concatMapStringsSep " and " (
virtualHost: mkRegistryPath virtualHost.registryName virtualHost.host virtualHost.entry
) virtualHosts
}"
]
else
[ ]
) virtualHostsByDomain
);
virtualHostsByDomain = lib.foldl' (
acc: virtualHost:
acc
// {
${virtualHost.name} = (acc.${virtualHost.name} or [ ]) ++ [ virtualHost ];
}
) { } generatedVirtualHostList;
generatedVirtualHostList = generatedHttpsVirtualHostList ++ generatedHttpVirtualHostList;
generatedHttpsVirtualHostList = lib.concatLists (
# Route registry validation already requires unique domains.
generatedVirtualHostList = lib.concatLists (
lib.mapAttrsToList (
host: routes:
lib.mapAttrsToList (entry: _route: mkVirtualHost host entry "https") (
lib.filterAttrs (_entry: route: route.protocol == "https") routes
lib.mapAttrsToList (entry: route: mkVirtualHost host entry route.protocol) (
lib.filterAttrs (_entry: route: route.protocol != "udp") routes
)
) registry.route
);
@@ -93,8 +64,6 @@ let
inherit (route) port;
in
{
inherit host entry;
registryName = "route";
name = route.domain;
value = {
forceSSL = !isHttp;
@@ -108,15 +77,6 @@ let
mkBackend = address: port: "http://${address}:${toString port}";
generatedHttpVirtualHostList = lib.concatLists (
lib.mapAttrsToList (
host: routes:
lib.mapAttrsToList (entry: _route: mkVirtualHost host entry "http") (
lib.filterAttrs (_entry: route: route.protocol == "http") routes
)
) registry.route
);
mkRegistryPath =
registryName: host: entry:
"registry.${registryName}.${host}.${entry}";

View File

@@ -15,9 +15,9 @@
};
serviceName = lib.mkOption {
type = lib.types.str;
type = lib.types.strMatching "[a-z0-9][a-z0-9-]*";
example = "valheim";
description = "Name of the systemd service that runs the game server.";
description = "Lowercase systemd service basename for the game server.";
};
appId = lib.mkOption {
@@ -87,7 +87,7 @@
prepareScript = pkgs.writeShellScript "steamcmd-${service.serviceName}-prepare" ''
set -eu
${pkgs.coreutils}/bin/install -d \
${lib.getExe' pkgs.coreutils "install"} -d \
-o ${user} \
-g ${group} \
-m 0770 \
@@ -155,7 +155,7 @@
wantedBy = lib.mkIf service.autoStart [ "multi-user.target" ];
serviceConfig = {
Type = "oneshot";
ExecStart = "${pkgs.systemd}/bin/systemctl --no-block start ${service.serviceName}.service";
ExecStart = "${lib.getExe' pkgs.systemd "systemctl"} --no-block start ${service.serviceName}.service";
};
};

View File

@@ -5,14 +5,11 @@
...
}:
# Bazel for the primary user's shell environment.
let
user = config.user.name;
in
{
options.modules.shell.bazel.enable =
lib.mkEnableOption "Bazel for the primary user's shell environment";
config = lib.mkIf config.modules.shell.bazel.enable {
home-manager.users.${user}.home.packages = [ pkgs.bazel ];
home-manager.users.${config.user.name}.home.packages = [ pkgs.bazel ];
};
}

View File

@@ -1,25 +0,0 @@
{
config,
lib,
...
}:
# direnv for the primary user, configured through home-manager.
let
user = config.user.name;
in
{
options.modules.shell.direnv.enable =
lib.mkEnableOption "direnv for the primary user, with nix-direnv shell caching";
config = lib.mkIf config.modules.shell.direnv.enable {
home-manager.users.${user}.programs.direnv = {
enable = true;
silent = true;
# nix-direnv caches the evaluated shell so re-entering a directory is instant
# instead of re-running `nix develop`, and adds the `use flake` stdlib helper.
nix-direnv.enable = true;
stdlib = builtins.readFile ./repo-flake.sh;
};
};
}

View File

@@ -1,33 +0,0 @@
if declare -f use_flake >/dev/null; then
__dotfiles_use_flake_definition="$(declare -f use_flake)"
eval "${__dotfiles_use_flake_definition/use_flake/__dotfiles_nix_direnv_use_flake}"
unset __dotfiles_use_flake_definition
use_flake() {
local flake_expr="${1:-.}"
if [[ "$flake_expr" == //* ]]; then
local git_root
if ! git_root="$(git rev-parse --show-toplevel 2>/dev/null)"; then
log_error 'use flake // requires a Git repository'
return 1
fi
local flake_suffix="${flake_expr#//}"
if [[ -n "$flake_suffix" && "$flake_suffix" != \#* && "$flake_suffix" != /* ]]; then
flake_expr="path:${git_root}/${flake_suffix}"
else
flake_expr="path:${git_root}${flake_suffix}"
fi
shift
__dotfiles_nix_direnv_use_flake "$flake_expr" "$@"
return
fi
__dotfiles_nix_direnv_use_flake "$@"
}
else
log_error 'nix-direnv must define use_flake before the // wrapper loads'
return 1
fi

View File

@@ -6,7 +6,7 @@
}:
# fish for the primary user, configured through home-manager.
let
cfg = config.modules.shell.fish; # NOLINT(let_order)
cfg = config.modules.shell.fish;
commandsOf = shortcuts: lib.mapAttrs (_name: shortcut: shortcut.command) shortcuts;
shortcuts = lib.attrByPath [ config.networking.hostName ] { } config.registry.shell-shortcut;
user = config.user.name;

View File

@@ -5,7 +5,7 @@
"livePreview": false,
"readableLineLength": false,
"strictLineBreaks": true,
"propertiesInDocument": "hidden",
"propertiesInDocument": "visible",
"showLineNumber": true,
"autoPairMarkdown": false,
"useTab": false,

View File

@@ -5,5 +5,6 @@
"obsidian-style-settings",
"custom-font-loader",
"obsidian-icon-folder",
"table-editor-obsidian"
"table-editor-obsidian",
"obsidian-linter"
]

View File

@@ -28,6 +28,20 @@
"rgb": 5366249
}
},
{
"query": "path:\"03 wrk/tasks\"[\"status\":open]",
"color": {
"a": 1,
"rgb": 14725458
}
},
{
"query": "path:\"03 wrk/tasks\" [\"status\":closed]",
"color": {
"a": 1,
"rgb": 11657298
}
},
{
"query": "path:\"03 wrk\" ",
"color": {
@@ -60,6 +74,6 @@
"repelStrength": 20,
"linkStrength": 1,
"linkDistance": 250,
"scale": 0.3645607001522557,
"scale": 0.16202697784544698,
"close": false
}

View File

@@ -0,0 +1,326 @@
{
"ruleConfigs": {
"add-blank-line-after-yaml": {
"enabled": true
},
"dedupe-yaml-array-values": {
"enabled": true,
"dedupe-alias-key": true,
"dedupe-tag-key": true,
"dedupe-array-keys": true,
"ignore-keys": []
},
"escape-yaml-special-characters": {
"enabled": true,
"try-to-escape-single-line-arrays": true
},
"force-yaml-escape": {
"enabled": true,
"force-yaml-escape-keys": []
},
"format-tags-in-yaml": {
"enabled": true
},
"format-yaml-array": {
"enabled": true,
"alias-key": true,
"tag-key": true,
"default-array-keys": true,
"force-single-line-array-style": [],
"force-multi-line-array-style": []
},
"insert-yaml-attributes": {
"enabled": true,
"text-to-insert": []
},
"move-inline-fields-to-yaml": {
"enabled": true,
"how-to-handle-full-line-fields": "Move and remove",
"how-to-handle-bracketed-fields": "Leave in place",
"how-to-handle-existing-keys": "Skip",
"inline-keys-to-ignore": []
},
"move-tags-to-yaml": {
"enabled": true,
"how-to-handle-existing-tags": "Nothing",
"tags-to-ignore": []
},
"remove-yaml-keys": {
"enabled": true,
"yaml-keys-to-remove": []
},
"sort-yaml-array-values": {
"enabled": true,
"sort-alias-key": true,
"sort-tag-key": true,
"sort-array-keys": true,
"ignore-keys": [],
"sort-order": "Ascending Alphabetical"
},
"yaml-key-sort": {
"enabled": true,
"yaml-key-priority-sort-order": [
"aliases",
"date-created",
"date-modified"
],
"priority-keys-at-start-of-yaml": true,
"yaml-sort-order-for-other-keys": "None"
},
"yaml-timestamp": {
"enabled": true,
"date-created": true,
"date-created-key": "date-created",
"date-created-source-of-truth": "file system",
"date-modified": true,
"date-modified-key": "date-modified",
"date-modified-source-of-truth": "file system",
"format": "YYYY-MM-DD HH:mm",
"convert-to-utc": false,
"update-on-file-contents-updated": "after 5 seconds"
},
"yaml-title": {
"enabled": false,
"title-key": "title",
"mode": "first-h1-or-filename-if-h1-missing"
},
"yaml-title-alias": {
"enabled": true,
"preserve-existing-alias-section-style": true,
"keep-alias-that-matches-the-filename": false,
"use-yaml-key-to-keep-track-of-old-filename-or-heading": false,
"alias-helper-key": "linter-yaml-title-alias",
"remove-alias-if-empty": true
},
"capitalize-headings": {
"enabled": true,
"style": "Title Case",
"ignore-case-words": [],
"lowercase-words": [],
"starting-word-ignore-characters": "'\"(‘“-",
"ending-word-ignore-characters": ".?!,:;'\")”’0123456789-",
"ignore-words": []
},
"file-name-heading": {
"enabled": true
},
"header-increment": {
"enabled": true,
"start-at-h2": false
},
"headings-start-line": {
"enabled": true
},
"remove-trailing-punctuation-in-heading": {
"enabled": true,
"punctuation-to-remove": ".,;:!。,;:!"
},
"footnote-after-punctuation": {
"enabled": true
},
"move-footnotes-to-the-bottom": {
"enabled": true,
"include-blank-line-between-footnotes": false
},
"re-index-footnotes": {
"enabled": true
},
"auto-correct-common-misspellings": {
"enabled": true,
"ignore-words": [],
"skip-words-with-multiple-capitals": true,
"extra-auto-correct-files": []
},
"blockquote-style": {
"enabled": true,
"style": "space"
},
"convert-bullet-list-markers": {
"enabled": true
},
"default-language-for-code-fences": {
"enabled": true,
"default-language": ""
},
"emphasis-style": {
"enabled": true,
"style": "consistent"
},
"no-bare-urls": {
"enabled": true,
"no-bare-uris": true
},
"ordered-list-style": {
"enabled": true,
"number-style": "ascending",
"list-end-style": ".",
"preserve-start": false
},
"proper-ellipsis": {
"enabled": true
},
"quote-style": {
"enabled": true,
"single-quote-enabled": true,
"single-quote-style": "''",
"double-quote-enabled": true,
"double-quote-style": "\"\""
},
"remove-consecutive-list-markers": {
"enabled": true
},
"remove-empty-list-markers": {
"enabled": true
},
"remove-hyphenated-line-breaks": {
"enabled": true
},
"remove-multiple-spaces": {
"enabled": true
},
"strong-style": {
"enabled": true,
"style": "consistent"
},
"two-spaces-between-lines-with-content": {
"enabled": false,
"line-break-indicator": " "
},
"unordered-list-style": {
"enabled": true,
"list-style": "consistent"
},
"align-table-columns": {
"enabled": true
},
"compact-yaml": {
"enabled": true,
"inner-new-lines": false
},
"consecutive-blank-lines": {
"enabled": true
},
"convert-spaces-to-tabs": {
"enabled": true,
"tabsize": 4
},
"empty-line-around-blockquotes": {
"enabled": true
},
"empty-line-around-code-fences": {
"enabled": true
},
"empty-line-around-horizontal-rules": {
"enabled": true
},
"empty-line-around-math-blocks": {
"enabled": true
},
"empty-line-around-tables": {
"enabled": true
},
"heading-blank-lines": {
"enabled": true,
"bottom": true,
"empty-line-after-yaml": true
},
"line-break-at-document-end": {
"enabled": true
},
"move-math-block-indicators-to-their-own-line": {
"enabled": true
},
"paragraph-blank-lines": {
"enabled": true
},
"remove-empty-lines-between-list-markers-and-checklists": {
"enabled": true
},
"remove-link-spacing": {
"enabled": true
},
"remove-space-around-characters": {
"enabled": true,
"include-fullwidth-forms": true,
"include-cjk-symbols-and-punctuation": true,
"include-dashes": true,
"other-symbols": ""
},
"remove-space-before-or-after-characters": {
"enabled": true,
"characters-to-remove-space-before": ",!?;:).’”]",
"characters-to-remove-space-after": "¿¡‘“(["
},
"space-after-list-markers": {
"enabled": true
},
"space-between-chinese-japanese-or-korean-and-english-or-numbers": {
"enabled": true,
"english-symbols-punctuation-before": "-+;:'\"°%$)]",
"english-symbols-punctuation-after": "-+'\"([¥$"
},
"trailing-spaces": {
"enabled": true,
"two-space-line-break": false
},
"add-blockquote-indentation-on-paste": {
"enabled": true
},
"prevent-double-checklist-indicator-on-paste": {
"enabled": true
},
"prevent-double-list-item-indicator-on-paste": {
"enabled": true
},
"proper-ellipsis-on-paste": {
"enabled": true
},
"remove-hyphens-on-paste": {
"enabled": true
},
"remove-leading-or-trailing-whitespace-on-paste": {
"enabled": true
},
"remove-leftover-footnotes-from-quote-on-paste": {
"enabled": true
},
"remove-multiple-blank-lines-on-paste": {
"enabled": true
}
},
"lintOnSave": true,
"recordLintOnSaveLogs": false,
"displayChanged": true,
"suppressMessageWhenNoChange": true,
"enableDiffPreviewView": true,
"suppressLintAllFilesConfirmationModal": false,
"suppressLintAllFilesInFolderConfirmationModal": false,
"lintOnFileChange": false,
"displayLintOnFileChangeNotice": false,
"settingsConvertedToConfigKeyValues": true,
"textAreaSettingsConvertedToListItemSettings": true,
"defaultArrayStyleMovedToCommonStyles": true,
"additionalFileExtensions": [],
"foldersToIgnore": [
"99 meta/templates"
],
"filesToIgnore": [
{
"label": "todo",
"match": "TODO.md",
"flags": "i"
}
],
"linterLocale": "system-default",
"logLevel": "ERROR",
"lintCommands": [],
"customRegexes": [],
"commonStyles": {
"aliasArrayStyle": "multi-line",
"tagArrayStyle": "single-line",
"defaultArrayStyle": "multi-line",
"minimumNumberOfDollarSignsToBeAMathBlock": 2,
"escapeCharacter": "\"",
"removeUnnecessaryEscapeCharsForMultiLineArrays": true
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,11 @@
{
"id": "obsidian-linter",
"name": "Linter",
"version": "1.34.1",
"minAppVersion": "1.13.0",
"description": "Formats and styles your notes. It can be used to format YAML tags, aliases, arrays, and metadata; footnotes; headings; spacing; math blocks; regular markdown contents like list, italics, and bold styles; and more with the use of custom rule options as well.",
"author": "Victor Tao",
"authorUrl": "https://github.com/platers",
"helpUrl": "https://platers.github.io/obsidian-linter/",
"isDesktopOnly": false
}

View File

@@ -0,0 +1 @@
.linter-no-border{border:none}.linter-border-bottom{border-bottom:1px solid var(--background-modifier-border);border-top:0;margin-bottom:.75em}.custom-row-description{margin-top:0}.modal-warn,.search-zero-state{font-weight:700}.modal-heading,.search-zero-state{text-align:center}.confirm-modal-checkbox-container{align-items:center;display:flex;gap:6px;margin-top:8px}.disabled-list-entry{color:var(--text-faint)}.linter-diff-preview-view{display:flex;flex-direction:column;height:100%;min-width:0;overflow:hidden}.linter-diff-preview-empty{color:var(--text-muted);padding:16px}.linter-diff-preview-header{align-items:flex-start;border-bottom:1px solid var(--background-modifier-border);display:flex;flex:0 0 auto;gap:12px;justify-content:space-between;padding:12px 14px}.linter-diff-preview-title-group{min-width:0}.linter-diff-preview-header h3{font-size:var(--font-ui-medium);line-height:1.3;margin:0 0 6px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.linter-diff-preview-actions{display:flex;flex:0 0 auto;gap:8px}.linter-diff-preview-body{flex:1 1 auto;min-height:0;overflow:auto;padding:12px 14px 16px}.linter-diff-preview-view .linter-diff-summary{color:var(--text-normal);display:inline-block;font-size:var(--font-ui-small);margin:0 0 10px;padding:5px 8px}.linter-diff-preview-view .linter-diff,.linter-diff-preview-view .linter-diff-summary{background:var(--background-secondary);border:1px solid var(--background-modifier-border);border-radius:6px}.linter-diff-preview-view .linter-diff{font-family:var(--font-monospace);font-size:var(--font-smaller);line-height:1.45;margin:0;overflow:hidden;padding:6px 0}.linter-diff-preview-view .linter-diff-line{display:grid;grid-template-columns:26px minmax(0,1fr);min-height:20px;padding:1px 10px 1px 0}.linter-diff-preview-view .linter-diff-marker{color:var(--text-muted);padding-right:8px;text-align:right;user-select:none}.linter-diff-preview-view .linter-diff-text{min-width:0;overflow-wrap:anywhere;white-space:pre-wrap}.linter-diff-preview-view .linter-diff-skip{border-bottom:1px solid var(--background-modifier-border);border-top:1px solid var(--background-modifier-border);color:var(--text-faint);font-family:var(--font-interface);font-size:var(--font-ui-smaller);padding:4px 12px;text-align:center}.linter-diff-preview-view .linter-diff-added{background:rgba(var(--color-green-rgb),.12);color:var(--text-normal)}.linter-diff-preview-view .linter-diff-removed{background:rgba(var(--color-red-rgb),.12);color:var(--text-normal)}.linter-diff-preview-view .linter-diff-context{color:var(--text-muted)}

View File

@@ -4,21 +4,21 @@
"type": "split",
"children": [
{
"id": "6d9088d392cb8604",
"id": "81c4860f495113bf",
"type": "tabs",
"children": [
{
"id": "22a4c1f201a1b00e",
"id": "daab69fc3faab88f",
"type": "leaf",
"state": {
"type": "markdown",
"state": {
"file": "00 INBOX/ai/valheim-items.md",
"mode": "preview",
"file": "00 INBOX/credits.md",
"mode": "source",
"source": true
},
"icon": "lucide-file",
"title": "valheim-items"
"title": "credits"
}
}
]
@@ -91,7 +91,7 @@
"state": {
"type": "localgraph",
"state": {
"file": "00 INBOX/ai/valheim-items.md",
"file": "00 INBOX/credits.md",
"options": {
"collapse-filter": true,
"search": "",
@@ -115,7 +115,7 @@
"linkStrength": 1,
"linkDistance": 250,
"scale": 0.6666666666666666,
"close": true
"close": false
}
},
"icon": "lucide-git-fork",
@@ -184,20 +184,6 @@
"title": "tag"
}
},
{
"id": "8918bf52a32e4a8e",
"type": "leaf",
"state": {
"type": "all-properties",
"state": {
"sortOrder": "frequency",
"showSearch": false,
"searchQuery": ""
},
"icon": "lucide-ghost",
"title": "all-properties"
}
},
{
"id": "c10908b3bd97f5fa",
"type": "leaf",
@@ -231,43 +217,43 @@
"table-editor-obsidian:Advanced Tables Toolbar": false
}
},
"active": "22a4c1f201a1b00e",
"active": "daab69fc3faab88f",
"lastOpenFiles": [
"00 INBOX/ai/hyprland-lua-migration-plan.md",
"00 INBOX/ai/deadnix-architecture.md",
"00 INBOX/ai/valheim-items.md",
"TODO.md",
"AGENTS.md",
"00 INBOX/valheim progression.md",
"03 wrk/tasks/0010-fix-main-monitor-detection.md",
"00 INBOX/credits.md",
"03 wrk/tasks/0009-bazel-project-scaffolding.md",
"03 wrk/tasks/0005-rust-cli-scaffolding.md",
"03 wrk/tasks/0008-vim-obsidian-markdown-renderer.md",
"03 wrk/tasks/0002-nixos-refactor.md",
"TODO.md",
"technical-writing.md",
"rust-module-prototype.md",
"00 INBOX/ai/statix-architecture.md",
"00 INBOX/ai/nix-statix-deadnix-rules.md",
"dictionary.md",
"03 wrk/tasks/0007-obsidian-source-notes.md",
"03 wrk/tasks/0004-dictionary-cli.md",
"03 wrk/tasks/0006-wallpaper-randomizer.md",
"03 wrk/tasks/0003-whisper-dictation.md",
"03 wrk/monorepo.md",
"03 wrk/tasks/0001-todo-cli.md",
"03 wrk/productivity.md",
"99 meta/templates/task.md",
"03 wrk/dotfiles.md",
"03 wrk/machoke.md",
"03 wrk/falinks.md",
"03 wrk/ariadne.md",
"03 wrk/tasks/0005-modules-services-navidrome.md",
"03 wrk/tasks/0003-registry-homepage.md",
"03 wrk/tasks/0039-hosts-zeus-hardware-configuration.md",
"03 wrk/tasks/0030-dotfiles-hosts.md",
"03 wrk/tasks",
"00 INBOX/let order name resolution.md~",
"00 INBOX/nix name resolution.md",
"00 INBOX/let order name resolution.md",
"00 INBOX/nix name resolution.md~",
"TODO.md~",
"00 INBOX/ai/xatu-rule-implementation-order.md",
"00 INBOX/ai/xatu-architecture-design.md",
"00 INBOX/ai/nix-style-linter-plan.md",
"00 INBOX/ai/nix-style-guide-agent-customization.md",
"00 INBOX/ai/game-guest-readiness-plan.md",
"00 INBOX/ai/xatu-node-rule-static-dispatch-plan.md",
"00 INBOX/ai/nix-style-linter-pr-1-vendor-rnix.md",
"00 INBOX/ai/nix-style-linter-pr-3-let-order.md",
"00 INBOX/ai/nix-style-linter-pr-2-scaffold-cli.md",
"00 INBOX/ai/homepage-pikachu-setup-plan.md",
"00 INBOX/ai/source-driven-remote-deploy-plan.md",
"00 INBOX/ai/monorepo-work-report.md",
"00 INBOX/ai/clew-ast-exploration.md",
"00 INBOX/ai/steamcmd servers.md",
"00 INBOX/ai/clew-ast-exploration.md~",
"03 wrk/machoke.md~",
"03 wrk/falinks.md~",
"99 meta/attachments/bases/unlinked mentions.base",
"00 INBOX/ai",
"03 wrk/ai",
"99 meta/Untitled"
"03 wrk/ai"
]
}

View File

@@ -1,304 +0,0 @@
# Deadnix Architecture
## Purpose
This note explains how `deadnix` finds unused Nix code.
It focuses on architecture, not whether each check belongs in our linter.
Use this note when deciding whether our linter needs scope analysis.
## What Deadnix Is
`deadnix` is a dead-code scanner for Nix.
It finds bindings that introduce names which no live code uses.
It is not a general style linter.
It does not have many independent rules.
It implements one analysis family: unused declarations.
Like `statix`, it parses source text with `rnix`.
It does not evaluate Nix.
It does not import files.
It reasons over local syntax and local scope only.
## Minimal Dead-Code Vocabulary
- A binding introduces a name.
- A scope defines where introduced names are visible.
- A use is an identifier occurrence that refers to a binding.
- Shadowing happens when an inner scope reuses an outer name.
- Dead code is a binding that no live code uses.
- A fixed point is the final result after repeated analysis no longer changes.
Dead-code analysis needs more state than a simple syntax lint.
It must know which names a scope introduces and where those names can be used.
## Component Map
`deadnix` has fewer layers than `statix`.
The command-line entry point, file walk, parsing, analysis, reporting, and editing live in one small tool.
The important concepts are separate modules:
- settings control analysis options;
- scopes describe where names are introduced;
- bindings describe individual declared names;
- usage search answers whether a name appears in a live body;
- dead-code results connect a binding to its scope;
- reports render findings;
- edits remove or rename unused declarations.
## Main Pipeline
```mermaid
flowchart TD
A[Parse CLI options] --> B[Collect input files]
B --> C[Read each file]
C --> D[Parse with rnix]
D --> E[Skip file on parse errors]
D --> F[Run dead-code analysis]
F --> G[Print reports unless quiet]
G --> H[Apply edits when --edit is set]
H --> I[Exit 1 when --fail and findings exist]
```
The CLI accepts files or directories.
Directory mode walks `.nix` files.
Hidden files require an explicit option.
Excludes filter paths before analysis.
The tool skips dead-code diagnostics when a file has parse errors.
It reports parse errors to the user and continues with other files.
## Analysis Settings
The analysis has four important switches.
`no_lambda_arg` disables checks for single lambda arguments.
This can avoid noise when an API requires an argument name.
`no_lambda_pattern_names` disables checks for names in attribute-set function patterns.
This matters for `callPackage`-style code, where argument names can be external API.
`no_underscore` ignores bindings that start with `_`.
This treats `_name` as an intentional unused placeholder.
`warn_used_underscore` reports underscore-prefixed bindings that code actually uses.
This enforces the convention that `_name` means unused.
These settings are architecture-relevant because dead-code policy depends on API context.
A repository linter needs a way to express that context.
## Scope Model
`deadnix` recognizes four scope types.
### Lambda pattern scope
A lambda pattern is a function argument written as an attribute set pattern.
It can introduce field names and an optional alias for the whole argument set.
Example shape:
```nix
args @ { pkgs, lib, ... }: body
```
This scope can introduce `args`, `pkgs`, and `lib`.
### Lambda argument scope
A single lambda argument introduces one name.
Example shape:
```nix
pkgs: body
```
This scope introduces `pkgs`.
### Let scope
A `let` expression introduces bindings and inherited names.
Those names are available in binding expressions and in the body.
Example shape:
```nix
let
inherit (pkgs) hello;
value = hello;
in
value
```
This scope introduces `hello` and `value`.
### Recursive attribute-set scope
A `rec` attribute set introduces names that sibling attributes can reference.
`deadnix` models this scope, but treats its bindings as non-removable.
That conservative choice avoids deleting public-looking attributes from recursive sets.
## Binding Model
A binding stores three facts.
It stores the identifier name.
It stores the syntax node that declared the name.
It stores whether the binding is mortal.
A mortal binding can become a dead-code finding.
A non-mortal binding participates in name lookup but will not be removed.
Single lambda arguments that already start with `_` are non-mortal.
Recursive attribute-set bindings are also non-mortal.
A binding also checks for the `deadnix: skip` pragma.
The pragma applies to a nearby following declaration.
The scanner searches backward from the declaration and stops after a blank-line boundary.
## Usage Search
Usage search asks whether a given name appears inside a syntax subtree.
The search is scope-aware.
When it enters a child scope that binds the same name, it stops following that branch.
That prevents an inner binding from counting as a use of an outer binding.
Attribute paths get special handling.
Ordinary attribute keys do not count as uses.
Dynamic or string attribute names can contain expressions, so the search looks inside those parts.
`inherit` also gets special handling.
A scope can inherit names from an outer scope.
The analysis checks whether the inherited expression uses the searched name.
## Fixed-Point Analysis
`deadnix` repeats the scan until the result set stops changing.
This matters because dead code can depend on other dead code.
A binding can appear used during the first pass because another binding references it.
If the referring binding is dead, the referenced binding is also dead.
The loop tracks dead declaration nodes.
During later scans, uses inside already-dead bodies do not keep other bindings alive.
This fixed-point loop is the central architectural difference from simple local syntax lints.
It makes dead-code results transitive.
## Reporting Model
A result stores the scope and binding for one finding.
The display text combines both parts.
Examples include unused lambda pattern, unused lambda argument, and unused let binding.
Human output uses `ariadne`.
The reporter groups ranges by line and labels the exact binding names.
It uses different colors for different scope kinds.
JSON output exists behind a feature flag.
It emits file, message, line, column, and end column.
`NO_COLOR` disables colored human output.
## Edit Model
`deadnix --edit` converts findings into text edits.
Each edit has a start offset, end offset, and replacement string.
The edit behavior depends on scope kind.
For unused lambda pattern names, it removes the name and nearby comma or whitespace.
For unused pattern aliases, it removes the alias syntax.
For unused lambda arguments, it renames the argument with an underscore prefix.
For unused `let` assignments, it deletes the assignment.
For unused inherited names, it deletes only the inherited name.
After those edits, it parses the edited source again.
Then it removes empty `let in` constructs and empty `inherit` statements.
This cleanup pass prevents the first edit batch from leaving invalid or useless scaffolding.
## Error Handling
If a path cannot be stated or read, the CLI reports the file error and continues.
If a file has parse errors, the CLI reports those errors and skips dead-code analysis for that file.
The `--fail` flag changes exit status when findings exist.
Without `--fail`, findings do not make the command fail.
This design separates report generation from CI policy.
## Architectural Strengths
The scope model is explicit.
Each scope type declares which bindings it introduces and where those bindings are visible.
The fixed-point loop catches transitive dead code.
A binding used only by dead code also becomes dead.
The usage search handles shadowing.
That prevents common false positives in nested functions and nested `let` expressions.
The edit model is tied to analysis results.
It knows whether a binding came from a lambda, pattern, `let`, or `inherit`.
The tool has few moving parts.
That makes the analysis easy to follow compared to a general multi-rule linter.
## Architectural Limits
`deadnix` does not evaluate Nix.
It cannot know which names external callers depend on.
This matters for module arguments, package function arguments, and public attribute sets.
It has global switches rather than project-specific rule contexts.
For example, all lambda pattern names can be checked or skipped.
The tool does not know that one directory contains `callPackage` functions.
The analysis is local to one file.
It cannot see that another file imports a function and relies on its argument names.
The fixer performs text edits with byte ranges.
It must handle punctuation and whitespace carefully.
Pattern edits are harder than simple assignment deletion.
The tool has one analysis family.
It is not a framework for many unrelated rules.
## Lessons for Our Linter
Dead-code checks need a scope pass.
A per-node rule interface is not enough when a diagnostic depends on name visibility.
Represent scopes explicitly.
Each scope type should provide introduced bindings and visible bodies.
Track shadowing before reporting unused names.
A text search for an identifier is not sufficient.
Use fixed-point analysis for transitive dead code.
One pass misses names used only by dead declarations.
Separate policy from mechanics.
The mechanics can find unused names.
Repository policy decides whether module arguments, package arguments, or underscore names count.
Treat autofix as scope-specific.
Removing a pattern name is not the same operation as deleting a `let` assignment.
Run cleanup after edits.
Dead-code fixes can create empty `let` expressions and empty `inherit` statements.
## Open Design Questions for Our Linter
- Should dead-code analysis be part of `nix-style-linter`, or a separate command?
- Should policy vary by path, file kind, or suppression comment?
- Should recursive attribute-set members ever become removable findings?
- Should underscore names mean ignored, or should used underscore names be errors?
- Should the linter report unused names without offering autofix first?
- Should cleanup rules run as ordinary rules or as a post-fix pass?

View File

@@ -1,102 +0,0 @@
# Hyprland Lua Migration Plan
## Problem Statement
The Hyprland compositor config uses Home Manager's hyprlang output.
Hyprland deprecates hyprlang for the main compositor config.
The repository needs to generate a Lua config without changing desktop behavior.
## Solution
Keep the config owned by Nix and Home Manager.
Switch the Hyprland Home Manager config output to Lua.
Convert only the settings whose shape changes under Lua.
This is not a desktop redesign.
The change preserves the current monitors, binds, window rules, environment variables, and UWSM startup.
## User Stories
1. As the operator, I want Hyprland to load `hyprland.lua`, so that startup no longer warns about hyprlang deprecation.
2. As the operator, I want existing keyboard binds to keep working, so that the desktop behavior stays unchanged.
3. As the operator, I want host monitor layout to stay unchanged, so that the physical display setup does not move.
4. As the operator, I want session environment variables to stay in the compositor config, so that Wayland and cursor behavior stays unchanged.
5. As the operator, I want auxiliary module binds to keep working, so that launcher, lock, screenshot, clipboard, notifications, and recording flows stay usable.
## Implementation Decisions
1. Use Home Manager's Lua config generator.
Set the Hyprland config type to Lua and keep package ownership unchanged.
2. Keep ordinary compositor options declarative in Nix.
Move input, general, decoration, xwayland, animation, and layout settings into the Lua config structure.
3. Remove hyprlang-only variables from generated config.
Keep modifier and terminal values as Nix locals or helper inputs.
4. Add minimal local helpers for Lua calls.
Use helpers only for repeated bind, dispatcher, command, environment, and rule shapes.
5. Convert all bind strings to Lua bind call data.
Preserve key combinations, dispatchers, commands, repeat behavior, and locked-session behavior.
6. Convert contributed binds in their owning modules.
Keep each bind near the module that owns the tool it launches.
7. Convert monitor strings to Lua monitor records.
Preserve output names, modes, positions, scale values, and rotation.
8. Convert the screenshot window rule to the Lua rule shape.
Preserve the Satty class matcher and floating behavior.
9. Convert environment strings to Lua environment calls.
Preserve the Wayland flag and cursor variables.
10. Delete or update comments that describe hyprlang syntax.
Keep comments that explain behavior or non-obvious invariants.
## Testing Decisions
1. Run the repository Nix formatting and style checks for modified Nix files.
2. Evaluate or build the affected host configuration.
This proves Home Manager accepts the Lua settings structure.
3. Confirm the generated config file uses Lua.
The expected output is `hyprland.lua`, not `hyprland.conf`.
4. Verify Hyprland accepts the generated Lua config.
Use Hyprland config verification when the installed build supports it.
Otherwise reload the compositor and inspect errors.
5. Smoke test the changed desktop surface.
Test one bind from each source area after reload.
6. Check the explicit monitor layout on the host that declares it.
Confirm resolution, position, scale, and rotation stayed unchanged.
## Out of Scope
- Do not split the config into Lua modules.
- Do not hand-write a full Lua config.
- Do not add new Hyprland behavior.
- Do not change UWSM startup.
- Do not redesign binds, monitor layout, or visual settings.
- Do not change hyprlock, hypridle, waybar, mako, or rofi settings beyond their Hyprland binds.
## Further Notes
Home Manager documents `configType = "lua"` for Hyprland.
It maps settings to `hl.*` calls.
It supports `_args` for multi-argument calls.
It supports raw Lua expressions with `lib.generators.mkLuaInline`.
The riskiest parts are binds, monitor declarations, and window rules.
Those parts changed shape more than scalar config sections.
Assumption: the pinned Home Manager input contains the documented Lua Hyprland generator.
Validate this during the configuration build.

14
docs/00 INBOX/credits.md Normal file
View File

@@ -0,0 +1,14 @@
---
aliases:
- Credits
date-created: 2026-10-17 18:08
date-modified: 2026-10-17 23:33
---
# Credits
| Path | Original | Notes | |
|-------------------------------------|-----------------------------------------------------------------------------------------|-------|---|
| `//src/skills/agent-writing-skills` | <https://github.com/mattpocock/skills/tree/main/skills/productivity/writing-for-agents> | | |
| `//src/skills/retrospect` | <https://github.com/mattpocock/skills/tree/main/skills/engineering/retro> | | |
| | | | |

8
docs/03 wrk/dotfiles.md Normal file
View File

@@ -0,0 +1,8 @@
---
aliases:
- Dotfiles
date-created: 2026-10-14 16:27
date-modified: 2026-10-14 16:28
---
# Dotfiles

8
docs/03 wrk/monorepo.md Normal file
View File

@@ -0,0 +1,8 @@
---
aliases:
- Monorepo
date-created: 2026-10-14 22:51
date-modified: 2026-10-14 22:54
---
# Monorepo

View File

@@ -0,0 +1,8 @@
---
aliases:
- Productivity
date-created: 2026-10-14 16:32
date-modified: 2026-10-14 16:33
---
# Productivity

View File

@@ -0,0 +1,16 @@
---
aliases:
- "0001"
- TODO CLI
date-created: 2026-10-14 00:49
date-modified: 2026-10-14 22:52
status: open
area: "[[productivity]]"
blocked-by:
- "[[0005-rust-cli-scaffolding]]"
subtasks: []
---
# TODO CLI
Write a TODO CLI that enforces the task workflow in this vault deterministically. This allows agents to participate in task management with minimal cost instead of relying on markdown generation and parsing arbitrary metadata while maintaining human readability.

View File

@@ -0,0 +1,103 @@
---
aliases:
- "0002"
- NixOS Refactor
date-created: 2026-10-14 16:07
date-modified: 2026-10-14 18:17
status: open
area: "[[dotfiles]]"
blocked-by: []
subtasks: []
---
# NixOS Refactor
Complete the remaining Nix refactor work.
## Files
- [x] `flake.nix`
- [x] `src/flake/default.nix`
- [x] `src/flake/formatter.nix`
- [x] `src/flake/apps.nix`
- [x] `src/dotfiles/default.nix`
- [x] `src/dotfiles/util.nix`
- [x] `src/dotfiles/registry.nix`
- [x] `src/dotfiles/registry/schema.nix`
- [x] `src/dotfiles/registry/validation.nix`
- [x] `configs/nixos/registry/address.nix`
- [>] `configs/nixos/registry/homepage.nix`
- [x] `configs/nixos/registry/route.nix`
- [x] `configs/nixos/registry/shell-shortcut.nix`
- [x] `configs/nixos/registry/stable-uid.nix`
- [x] `configs/nixos/modules/default.nix`
- [x] `configs/nixos/modules/host.nix`
- [x] `configs/nixos/modules/guest.nix`
- [x] `configs/nixos/modules/monorepo.nix`
- [x] `configs/nixos/modules/zfs.nix`
- [x] `configs/nixos/modules/network/ssh.nix`
- [x] `configs/nixos/modules/network/vlans.nix`
- [x] `configs/nixos/modules/network/vpn-client.nix`
- [x] `configs/nixos/modules/desktop/default.nix`
- [x] `configs/nixos/modules/desktop/apps/alacritty.nix`
- [x] `configs/nixos/modules/desktop/apps/firefox.nix`
- [x] `configs/nixos/modules/desktop/apps/ghostty.nix`
- [x] `configs/nixos/modules/desktop/apps/obsidian.nix`
- [x] `configs/nixos/modules/desktop/apps/r2modman.nix`
- [x] `configs/nixos/modules/desktop/apps/signal.nix`
- [x] `configs/nixos/modules/desktop/apps/steam.nix`
- [x] `configs/nixos/modules/desktop/apps/vencord.nix`
- [x] `configs/nixos/modules/desktop/session/hyprland/default.nix`
- [x] `configs/nixos/modules/desktop/session/hyprland/hypridle.nix`
- [x] `configs/nixos/modules/desktop/session/hyprland/hyprlock.nix`
- [x] `configs/nixos/modules/desktop/session/login.nix`
- [x] `configs/nixos/modules/desktop/session/mako.nix`
- [x] `configs/nixos/modules/desktop/session/portals.nix`
- [x] `configs/nixos/modules/desktop/session/rofi.nix`
- [x] `configs/nixos/modules/desktop/session/waybar.nix`
- [x] `configs/nixos/modules/desktop/utilities/audio.nix`
- [x] `configs/nixos/modules/desktop/utilities/clipboard.nix`
- [x] `configs/nixos/modules/desktop/utilities/osd.nix`
- [x] `configs/nixos/modules/desktop/utilities/recording.nix`
- [x] `configs/nixos/modules/desktop/utilities/screenshot.nix`
- [x] `configs/nixos/modules/desktop/utilities/theming.nix`
- [x] `configs/nixos/modules/desktop/utilities/userdirs.nix`
- [x] `configs/nixos/modules/services/actualbudget.nix`
- [x] `configs/nixos/modules/services/copyparty.nix`
- [x] `configs/nixos/modules/services/homepage.nix`
- [x] `configs/nixos/modules/services/navidrome.nix`
- [x] `configs/nixos/modules/services/reverse-proxy.nix`
- [x] `configs/nixos/modules/services/steamcmd.nix`
- [x] `configs/nixos/modules/services/games/palworld.nix`
- [x] `configs/nixos/modules/services/games/valheim.nix`
- [x] `configs/nixos/modules/shell/bazel.nix`
- [x] `configs/nixos/modules/shell/direnv/default.nix`
- [ ] `configs/nixos/modules/shell/fish/default.nix`
- [ ] `configs/nixos/modules/shell/gitea-axi.nix`
- [ ] `configs/nixos/modules/shell/git.nix`
- [ ] `configs/nixos/modules/shell/herdr.nix`
- [ ] `configs/nixos/modules/shell/nvim/default.nix`
- [ ] `configs/nixos/modules/shell/omp.nix`
- [ ] `configs/nixos/modules/shell/pi/default.nix`
- [ ] `configs/nixos/modules/shell/python.nix`
- [ ] `configs/nixos/modules/shell/rust.nix`
- [ ] `configs/nixos/modules/shell/tmux/default.nix`
- [ ] `configs/nixos/modules/shell/yazi.nix`
- [ ] `src/dotfiles/guests.nix`
- [x] `configs/nixos/guests/actualbudget.nix`
- [ ] `configs/nixos/guests/copyparty.nix`
- [ ] `configs/nixos/guests/homepage.nix`
- [ ] `configs/nixos/guests/navidrome.nix`
- [ ] `configs/nixos/guests/palworld.nix`
- [ ] `configs/nixos/guests/reverse-proxy.nix`
- [ ] `configs/nixos/guests/valheim.nix`
- [ ] `src/dotfiles/hosts.nix`
- [ ] `configs/nixos/hosts/neogaia/default.nix`
- [ ] `configs/nixos/hosts/neogaia/disk.nix`
- [ ] `configs/nixos/hosts/neogaia/hardware-configuration.nix`
- [ ] `configs/nixos/hosts/pikachu/default.nix`
- [ ] `configs/nixos/hosts/pikachu/disk.nix`
- [ ] `configs/nixos/hosts/pikachu/hardware-configuration.nix`
- [ ] `configs/nixos/hosts/zeus/default.nix`
- [ ] `configs/nixos/hosts/zeus/disk.nix`
- [ ] `configs/nixos/hosts/zeus/hardware-configuration.nix`

View File

@@ -0,0 +1,37 @@
---
aliases:
- "0003"
- Whisper dictation
date-created: 2026-10-14 16:31
date-modified: 2026-10-14 16:33
status: open
area: "[[productivity]]"
blocked-by:
- "[[0002-nixos-refactor]]"
subtasks: []
---
# Whisper dictation
Provide reliable local dictation on Zeus.
## Prototype findings
- `hyprwhspr-rs` provides PipeWire capture, local `whisper.cpp` transcription, clipboard copying, and Hyprland integration.
- The prototype used `small.en` from `~/dwn/ggml-small.en.bin`.
- The initial CPU prototype transcribed accurately but added about 2.3 seconds after a 2.9-second recording.
- Vulkan acceleration uses `whisper-cpp-vulkan` and `gpu_layers = 999`.
- `SUPER + ALT + D` starts recording on press and stops recording on release.
- Hyprland Lua represents release bindings with `hl.bind(..., { release = true })`.
- `hyprwhspr-rs` uses Hyprland's removed `sendshortcut` dispatcher for automatic paste.
- Its virtual-keyboard fallback can drop modifiers and insert only `v`.
- Treat the prototype configuration as disposable because it no longer works reliably.
## Completion
- [ ] Choose a maintained local speech-to-text backend.
- [ ] Record microphone audio through PipeWire.
- [ ] Transcribe locally with GPU acceleration when available.
- [ ] Insert transcribed text reliably into the focused application.
- [ ] Copy transcribed text to the clipboard.
- [ ] Test dictation with representative technical speech.

View File

@@ -0,0 +1,18 @@
---
aliases:
- "0004"
- Dictionary CLI
date-created: 2026-10-14 22:47
date-modified: 2026-10-14 22:57
status: open
area: "[[productivity]]"
blocked-by:
- "[[0005-rust-cli-scaffolding]]"
subtasks: []
---
# Dictionary CLI
A CLI tool that basically works as a strict allowlist for words used in prose such as markdown files or strings passed to the tool.
The basic idea can be found in [[dictionary]], but as it would be a deterministic tool, a strict allowlist might be more beneficial.

View File

@@ -0,0 +1,21 @@
---
aliases:
- "0005"
- Rust CLI Scaffolding
date-created: 2026-10-14 22:50
date-modified: 2026-10-15 23:48
# Allowed: open, closed
status: open
area: "[[monorepo]]"
blocked-by:
- "[[0009-bazel-project-scaffolding]]"
subtasks: []
---
# Rust CLI Scaffolding
One of the biggest patterns I noticed when working on Rust projects in the monorepo was that they were mostly CLI tools. I found myself doing the same boilerplate over and over again.
I think much like Google, having a function that handles sensible defaults would be a good idea.
But also, maybe a Rust project set up to avoid the common pitfalls?

View File

@@ -0,0 +1,23 @@
---
aliases:
- "0006"
- Wallpaper Randomizer
date-created: 2026-10-14 23:00
date-modified: 2026-10-14 23:05
status: open
area: "[[dotfiles]]"
blocked-by:
- "[[0005-rust-cli-scaffolding]]"
subtasks: []
---
# Wallpaper Randomizer
This is kind of two ideas in one:
1. Randomizing the desktop wallpaper from a select list.
2. A web service endpoint that provides a random image from a configured directory/set.
The first idea might not need any special code, so it wouldn't be a CLI.
I think that any tools I write should have both a non-interactive mode and a TUI or web server mode.

View File

@@ -0,0 +1,20 @@
---
aliases:
- "0007"
- Obsidian Source Notes
date-created: 2026-10-14 23:11
date-modified: 2026-10-14 23:14
status: open
area: "[[productivity]]"
blocked-by: []
subtasks: []
---
# Obsidian Source Notes
This is more of a note to collect ideas for `ingest-*` skills.
## Skill Ideas
- `ingest-youtube-transcript`
- `ingest-youtube-video`

View File

@@ -0,0 +1,15 @@
---
aliases:
- "0008"
- Vim Obsidian Markdown Renderer
date-created: 2026-10-14 23:18
date-modified: 2026-10-14 23:20
status: open
area: "[[dotfiles]]"
blocked-by: []
subtasks: []
---
# Vim Obsidian Markdown Renderer
The current plugin I use for Markdown rendering in Vim has some issues, but most importantly it doesn't have full feature parity with Obsidian. I think from the top of my head, wikilinks can't be followed for example.

View File

@@ -0,0 +1,17 @@
---
aliases:
- "0009"
- Bazel Project Scaffolding
date-created: 2026-10-15 23:46
date-modified: 2026-10-16 00:32
status: open
area: "[[monorepo]]"
blocked-by: []
subtasks: []
---
# Bazel Project Scaffolding
A small utility library that sets up projects when needed.
The first goal would be to scaffold a basic Rust project with a library, tests and binary to avoid manual toil.

View File

@@ -0,0 +1,18 @@
---
aliases:
- "0010"
- Fix Main Monitor Detection
date-created: 2026-10-17 09:24
date-modified: 2026-10-17 09:25
# Allowed: open, closed
status: open
area: "[[dotfiles]]"
blocked-by: []
subtasks: []
---
# Fix Main Monitor Detection
Most of the time, games detect the HDMI monitor as the main monitor and show the wrong resolution options and/or have display issues.
The HDMI monitor is a vertical monitor with 1080x1920 resolution so that leads to a lot of problems I can't fix from within the game because it gets cut off.

View File

@@ -1,5 +1,5 @@
---
date-created: {{date}} {{time}}
date-created: "{{date}} {{time}}"
---
# {{title}}

View File

@@ -0,0 +1,12 @@
---
date-created: "{{date}} {{time}}"
# Allowed: open, closed
status: open
area:
blocked-by:
-
subtasks:
-
---
# {{title}}

View File

@@ -1,35 +1,33 @@
# active projects
# Active Projects
- dotfiles
- nix-style / refactor
## Inactive For Now
- ariadne
- machoke
- falinks
- dotfiles
- natu
- nix-style / refactor
# project ideas
# Project Ideas
- obsidian-source-notes (`ingest-*` skills)
- onepacerr (requires raichu migration)
- obsidian-game-backlog
- whisper dictation
- breadcrumbs
- gingko
- pokemon-classifier-ml
- home assistant agent integration
- wallpaper randomizer
- ebook tool (might be an overlap with `ingest-ebook`)
- amazon / actualbudget exporter
- vim-obsidian-markdown
- dictionary cli tool
- kitchen.md
- Rust project creator
- random number generator utility
- reading material helper
- valheim progression DSL + graph
- Pi:
- vim bindings
# migration
# Migration
- [[conventional-commits]] -> skill?
- [[dictionary]] -> cli tool
- [[technical-writing]] -> skill?
- gitea-axi
- skills
@@ -50,7 +48,7 @@
- subagents
- test-driven-development
## pikachu + pichu proxmox -> nixos
## Pikachu + Pichu Proxmox -> Nixos
- lidarr (requires raichu)
- immich
@@ -60,7 +58,8 @@
- adguard
- manage DNS rewrites for local service names such as `home`
## raichu proxmox -> nixos
## Raichu Proxmox -> Nixos
- dwn torrent (vpn)
- dwn usenet (vpn)
- dwn-torrent-novpn
@@ -77,39 +76,34 @@
- seerr
- plex
- pterodactyl
- palworld old
- project zomboid
- minecraft
- cobblemon
- palworld old
- project zomboid
- minecraft
- cobblemon
# Learning
# learning
- YouTube
- EeroAlvar
- https://www.youtube.com/watch?v=DzhLFiblPUk
- https://www.youtube.com/watch?v=hQGAwD9vkLo
- https://www.youtube.com/watch?v=hhtExS5UQBI
- https://www.youtube.com/watch?v=Y1xO9OsCBC4
- https://www.youtube.com/watch?v=DWWrLlM3gwQ
- https://www.youtube.com/watch?v=yHL-gmkzC-4
- https://www.youtube.com/watch?v=KRVYUkM16hE
- https://www.youtube.com/watch?v=RxdvzenLcl4
- https://www.youtube.com/watch?v=mdbpIpPSPwQ
- https://www.youtube.com/watch?v=GHsq0klC_4g
- https://www.youtube.com/watch?v=ciC6ffUqI8k
- https://www.youtube.com/watch?v=gYxZt9Qe0fk
- https://www.youtube.com/watch?v=0tqty8ltKDA
- https://www.youtube.com/watch?v=kzcI5F4tGiU
- https://www.youtube.com/watch?v=iKwPaB5TUdI
- https://www.youtube.com/watch?v=A-CtdQFRX64
- natu literature
- https://rust-analyzer.github.io/book/contributing/syntax.html?utm_source=chatgpt.com
- https://github.com/dotnet/roslyn/blob/main/docs/compilers/Design/Red-Green%20Trees.md?utm_source=chatgpt.com
- https://github.com/rust-analyzer/rowan/blob/master/examples/s_expressions.rs?utm_source=chatgpt.com
- https://dl.acm.org/doi/10.1145/964001.964011
- https://web.cecs.pdx.edu/~apt/esop15.pdf?utm_source=chatgpt.com
- https://www.researchgate.net/publication/2377179_Efficient_and_flexible_incremental_parsing?utm_source=chatgpt.com
- EeroAlvar
- <https://www.youtube.com/watch?v=DzhLFiblPUk>
- <https://www.youtube.com/watch?v=hQGAwD9vkLo>
- <https://www.youtube.com/watch?v=hhtExS5UQBI>
- <https://www.youtube.com/watch?v=Y1xO9OsCBC4>
- <https://www.youtube.com/watch?v=DWWrLlM3gwQ>
- <https://www.youtube.com/watch?v=yHL-gmkzC-4>
- <https://www.youtube.com/watch?v=KRVYUkM16hE>
- <https://www.youtube.com/watch?v=RxdvzenLcl4>
- <https://www.youtube.com/watch?v=mdbpIpPSPwQ>
- <https://www.youtube.com/watch?v=GHsq0klC_4g>
- <https://www.youtube.com/watch?v=ciC6ffUqI8k>
- <https://www.youtube.com/watch?v=gYxZt9Qe0fk>
- <https://www.youtube.com/watch?v=0tqty8ltKDA>
- <https://www.youtube.com/watch?v=kzcI5F4tGiU>
- <https://www.youtube.com/watch?v=iKwPaB5TUdI>
- <https://www.youtube.com/watch?v=A-CtdQFRX64>
- <https://www.youtube.com/watch?v=MHPRnM38Dyc>
# tech debt
# Tech Debt
- better remote deployment
- expose remote deployment as a flake app, replacing the Fish-only `deploy-to` workflow
@@ -118,92 +112,7 @@
Prefer clear per-file dependency edges, but `rust_library` maps each target to a crate.
Decide whether wrapper rules or another pattern can improve graph clarity without forcing artificial crate boundaries.
## nix refactor
## Nix Refactor
Review Nix files in entrypoint order:
- [x] `flake.nix`
- [x] `src/flake/default.nix`
- [x] `src/flake/formatter.nix`
- [x] `src/flake/apps.nix`
- [x] `src/dotfiles/default.nix`
- [x] `src/dotfiles/util.nix`
- [x] `src/dotfiles/registry.nix`
- [x] `src/dotfiles/registry/schema.nix`
- [x] `src/dotfiles/registry/validation.nix`
- [x] `configs/nixos/registry/address.nix`
- [>] `configs/nixos/registry/homepage.nix`
- [x] `configs/nixos/registry/route.nix`
- [x] `configs/nixos/registry/shell-shortcut.nix`
- [x] `configs/nixos/registry/stable-uid.nix`
- [x] `configs/nixos/modules/default.nix`
- [x] `configs/nixos/modules/host.nix`
- [x] `configs/nixos/modules/guest.nix`
- [x] `configs/nixos/modules/monorepo.nix`
- [x] `configs/nixos/modules/zfs.nix`
- [x] `configs/nixos/modules/network/ssh.nix`
- [x] `configs/nixos/modules/network/vlans.nix`
- [x] `configs/nixos/modules/network/vpn-client.nix`
- [x] `configs/nixos/modules/desktop/default.nix`
- [x] `configs/nixos/modules/desktop/apps/alacritty.nix`
- [x] `configs/nixos/modules/desktop/apps/firefox.nix`
- [x] `configs/nixos/modules/desktop/apps/ghostty.nix`
- [x] `configs/nixos/modules/desktop/apps/obsidian.nix`
- [x] `configs/nixos/modules/desktop/apps/r2modman.nix`
- [x] `configs/nixos/modules/desktop/apps/signal.nix`
- [x] `configs/nixos/modules/desktop/apps/steam.nix`
- [x] `configs/nixos/modules/desktop/apps/vencord.nix`
- [ ] `configs/nixos/modules/desktop/session/hyprland/default.nix`
- [ ] `configs/nixos/modules/desktop/session/hyprland/hypridle.nix`
- [ ] `configs/nixos/modules/desktop/session/hyprland/hyprlock.nix`
- [ ] `configs/nixos/modules/desktop/session/login.nix`
- [ ] `configs/nixos/modules/desktop/session/mako.nix`
- [ ] `configs/nixos/modules/desktop/session/portals.nix`
- [ ] `configs/nixos/modules/desktop/session/rofi.nix`
- [ ] `configs/nixos/modules/desktop/session/waybar.nix`
- [ ] `configs/nixos/modules/desktop/utilities/audio.nix`
- [ ] `configs/nixos/modules/desktop/utilities/clipboard.nix`
- [ ] `configs/nixos/modules/desktop/utilities/osd.nix`
- [ ] `configs/nixos/modules/desktop/utilities/recording.nix`
- [ ] `configs/nixos/modules/desktop/utilities/screenshot.nix`
- [ ] `configs/nixos/modules/desktop/utilities/theming.nix`
- [ ] `configs/nixos/modules/desktop/utilities/userdirs.nix`
- [ ] `configs/nixos/modules/services/actualbudget.nix`
- [ ] `configs/nixos/modules/services/copyparty.nix`
- [ ] `configs/nixos/modules/services/homepage.nix`
- [ ] `configs/nixos/modules/services/navidrome.nix`
- [ ] `configs/nixos/modules/services/reverse-proxy.nix`
- [ ] `configs/nixos/modules/services/steamcmd.nix`
- [ ] `configs/nixos/modules/services/games/palworld.nix`
- [ ] `configs/nixos/modules/services/games/valheim.nix`
- [ ] `configs/nixos/modules/shell/bazel.nix`
- [ ] `configs/nixos/modules/shell/direnv/default.nix`
- [ ] `configs/nixos/modules/shell/fish/default.nix`
- [ ] `configs/nixos/modules/shell/gitea-axi.nix`
- [ ] `configs/nixos/modules/shell/git.nix`
- [ ] `configs/nixos/modules/shell/herdr.nix`
- [ ] `configs/nixos/modules/shell/nvim/default.nix`
- [ ] `configs/nixos/modules/shell/omp.nix`
- [ ] `configs/nixos/modules/shell/pi/default.nix`
- [ ] `configs/nixos/modules/shell/python.nix`
- [ ] `configs/nixos/modules/shell/rust.nix`
- [ ] `configs/nixos/modules/shell/tmux/default.nix`
- [ ] `configs/nixos/modules/shell/yazi.nix`
- [ ] `src/dotfiles/guests.nix`
- [ ] `configs/nixos/guests/actualbudget.nix`
- [ ] `configs/nixos/guests/copyparty.nix`
- [ ] `configs/nixos/guests/homepage.nix`
- [ ] `configs/nixos/guests/navidrome.nix`
- [ ] `configs/nixos/guests/palworld.nix`
- [ ] `configs/nixos/guests/reverse-proxy.nix`
- [ ] `configs/nixos/guests/valheim.nix`
- [ ] `src/dotfiles/hosts.nix`
- [ ] `configs/nixos/hosts/neogaia/default.nix`
- [ ] `configs/nixos/hosts/neogaia/disk.nix`
- [ ] `configs/nixos/hosts/neogaia/hardware-configuration.nix`
- [ ] `configs/nixos/hosts/pikachu/default.nix`
- [ ] `configs/nixos/hosts/pikachu/disk.nix`
- [ ] `configs/nixos/hosts/pikachu/hardware-configuration.nix`
- [ ] `configs/nixos/hosts/zeus/default.nix`
- [ ] `configs/nixos/hosts/zeus/disk.nix`
- [ ] `configs/nixos/hosts/zeus/hardware-configuration.nix`

View File

@@ -1,141 +0,0 @@
# Conventional Commits 1.0.0
## Summary
The Conventional Commits specification is a lightweight convention on top of commit messages.
It provides an easy set of rules for creating an explicit commit history;
which makes it easier to write automated tools on top of.
This convention dovetails with [SemVer](http://semver.org),
by describing the features, fixes, and breaking changes made in commit messages.
The commit message should be structured as follows:
---
```
<type>[optional scope]: <description>
[optional body]
[optional footer(s)]
```
---
The commit contains the following structural elements, to communicate intent to the
consumers of your library:
1. **fix:** a commit of the _type_ `fix` patches a bug in your codebase (this correlates with [`PATCH`](http://semver.org/#summary) in Semantic Versioning).
2. **feat:** a commit of the _type_ `feat` introduces a new feature to the codebase (this correlates with [`MINOR`](http://semver.org/#summary) in Semantic Versioning).
3. **BREAKING CHANGE:** a commit that has a footer `BREAKING CHANGE:`, or appends a `!` after the type/scope, introduces a breaking API change (correlating with [`MAJOR`](http://semver.org/#summary) in Semantic Versioning).
A BREAKING CHANGE can be part of commits of any _type_.
4. _types_ other than `fix:` and `feat:` are allowed, for example [@commitlint/config-conventional](https://github.com/conventional-changelog/commitlint/tree/master/%40commitlint/config-conventional) (based on the [Angular convention](https://github.com/angular/angular/blob/22b96b9/CONTRIBUTING.md#type)) recommends `build:`, `chore:`,
`ci:`, `docs:`, `style:`, `refactor:`, `perf:`, `test:`, and others.
5. _footers_ other than `BREAKING CHANGE: <description>` may be provided and follow a convention similar to
[git trailer format](https://git-scm.com/docs/git-interpret-trailers).
Additional types are not mandated by the Conventional Commits specification, and have no implicit effect in Semantic Versioning (unless they include a BREAKING CHANGE).
A scope may be provided to a commit’s type, to provide additional contextual information and is contained within parenthesis, e.g., `feat(parser): add ability to parse arrays`.
## Examples
### Commit message with description and breaking change footer
```
feat: allow provided config object to extend other configs
BREAKING CHANGE: `extends` key in config file is now used for extending other config files
```
### Commit message with `!` to draw attention to breaking change
```
feat!: send an email to the customer when a product is shipped
```
### Commit message with scope and `!` to draw attention to breaking change
```
feat(api)!: send an email to the customer when a product is shipped
```
### Commit message with both `!` and BREAKING CHANGE footer
```
chore!: drop support for Node 6
BREAKING CHANGE: use JavaScript features not available in Node 6.
```
### Commit message with no body
```
docs: correct spelling of CHANGELOG
```
### Commit message with scope
```
feat(lang): add Polish language
```
### Commit message with multi-paragraph body and multiple footers
```
fix: prevent racing of requests
Introduce a request id and a reference to latest request. Dismiss
incoming responses other than from latest request.
Remove timeouts which were used to mitigate the racing issue but are
obsolete now.
Reviewed-by: Z
Refs: #123
```
## Specification
The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [RFC 2119](https://www.ietf.org/rfc/rfc2119.txt).
1. Commits MUST be prefixed with a type, which consists of a noun, `feat`, `fix`, etc.,
followed by the OPTIONAL scope, OPTIONAL `!`, and REQUIRED terminal colon and space.
2. The type `feat` MUST be used when a commit adds a new feature to your application or library.
3. The type `fix` MUST be used when a commit represents a bug fix for your application.
4. A scope MAY be provided after a type.
A scope MUST consist of a noun describing a section of the codebase surrounded by parenthesis, e.g., `fix(parser):`
5. A description MUST immediately follow the colon and space after the type/scope prefix.
The description is a short summary of the code changes, e.g., _fix: array parsing issue when multiple spaces were contained in string_.
6. A longer commit body MAY be provided after the short description, providing additional contextual information about the code changes.
The body MUST begin one blank line after the description.
7. A commit body is free-form and MAY consist of any number of newline separated paragraphs.
8. One or more footers MAY be provided one blank line after the body.
Each footer MUST consist of a word token, followed by either a `:<space>` or `<space>#` separator, followed by a string value (this is inspired by the [git trailer convention](https://git-scm.com/docs/git-interpret-trailers)).
9. A footer’s token MUST use `-` in place of whitespace characters, e.g., `Acked-by` (this helps differentiate the footer section from a multi-paragraph body).
An exception is made for `BREAKING CHANGE`, which MAY also be used as a token.
10. A footer’s value MAY contain spaces and newlines, and parsing MUST terminate when the next valid footer token/separator pair is observed.
11. Breaking changes MUST be indicated in the type/scope prefix of a commit, or as an entry in the footer.
12. If included as a footer, a breaking change MUST consist of the uppercase text BREAKING CHANGE, followed by a colon, space, and description, e.g., _BREAKING CHANGE: environment variables now take precedence over config files_.
13. If included in the type/scope prefix, breaking changes MUST be indicated by a `!` immediately before the `:`.
If `!` is used, `BREAKING CHANGE:` MAY be omitted from the footer section, and the commit description SHALL be used to describe the breaking change.
14. Types other than `feat` and `fix` MAY be used in your commit messages, e.g., _docs: updated ref docs._
15. The units of information that make up Conventional Commits MUST NOT be treated as case sensitive by implementors, with the exception of BREAKING CHANGE which MUST be uppercase.
16. BREAKING-CHANGE MUST be synonymous with BREAKING CHANGE, when used as a token in a footer.
## FAQ
### How does Conventional Commits handle revert commits?
Reverting code can be complicated: are you reverting multiple commits?
if you are reverting a feature, should the next release instead be a patch?
Conventional Commits does not make an explicit effort to define revert behavior.
Instead we leave it to tooling authors to use the flexibility of _types_ and _footers_ to develop their logic for handling reverts.
One recommendation is to use the `revert` type, and a footer that references the commit SHAs that are being reverted:
```
revert: let us never again speak of the noodle incident
Refs: 676104e, a215868
```

View File

@@ -38,7 +38,7 @@ Use `REPLACE` for terms that have a preferred substitute.
| host | USE | | A machine with a NixOS configuration built by this repository's flake. |
| module | USE | | A self-contained NixOS configuration under `configs/nixos/modules/`. |
| registry | USE | | A typed configuration namespace whose entries can be collected across hosts and reused by other configuration. |
| Conventional Commits | USE | | A commit-message format defined in `docs/conventional-commits.md`. |
| Conventional Commits | USE | | A format for commit messages. |
| forge | USE | | A web service that hosts Git repositories, pull requests, issues, and code review comments. Use when the exact provider does not matter. |
| flake | USE | | A Nix project with pinned inputs and declared outputs. Use for the repository-level build unit defined by `flake.nix`. |
| NixOS module | USE | | A Nix file evaluated by `nixosSystem` for a NixOS configuration. |

107
flake.lock generated
View File

@@ -75,11 +75,11 @@
"nixpkgs": "nixpkgs"
},
"locked": {
"lastModified": 1789232619,
"narHash": "sha256-8pyRIm67V5dtVN3A4Mu0e2a7DIhUhWp6y3NSVS6WBwU=",
"lastModified": 1792048969,
"narHash": "sha256-+Scy7etDouWzvEV9d6zEDz/TxOoGzfSJau9+yp/zWM4=",
"owner": "chaotic-cx",
"repo": "nyx",
"rev": "0265d6932168aef12c47f03a565786410ba877e0",
"rev": "c283697bfcc3770232139b86c4ad19fd8a62cd6f",
"type": "github"
},
"original": {
@@ -96,11 +96,11 @@
]
},
"locked": {
"lastModified": 1781152676,
"narHash": "sha256-RxWs5ND31KzTG7wvMM+PMfUjyNpmIEr999lqNARaM5o=",
"lastModified": 1789770686,
"narHash": "sha256-uZkBR7yHdIKUFB5SZdfgh1qkGfI3XmYmI/lTiquxbck=",
"owner": "nix-community",
"repo": "disko",
"rev": "ff8702b4de27f72b4c78573dfb89ec74e36abdf1",
"rev": "725ea35e410ad83be4931d1bff7e090eacaf3563",
"type": "github"
},
"original": {
@@ -117,11 +117,11 @@
},
"locked": {
"dir": "pkgs/firefox-addons",
"lastModified": 1789185767,
"narHash": "sha256-jaWL9beN3ifjNzNEBxo0abA+TSi0n7Q8LRQvZTxEqaM=",
"lastModified": 1792036980,
"narHash": "sha256-y28wLbzsIbBDeToXHhAdoTs+lcH/d7/1Pky40N6/CoI=",
"owner": "rycee",
"repo": "nur-expressions",
"rev": "811170bb74b11f3b9489618ce77487cc58c79067",
"rev": "cbf0380669792dd8f6dbb891d3be33aae8fa4625",
"type": "gitlab"
},
"original": {
@@ -155,11 +155,11 @@
]
},
"locked": {
"lastModified": 1788450739,
"narHash": "sha256-glZLQlzIn1fXH6PazR2iUmTo7kzzyYSshrWhLS9TqCU=",
"lastModified": 1790898470,
"narHash": "sha256-zTwuwezD0w3hpga6a6P8emidzAZFyWqlNeRBlpWOOl8=",
"owner": "hercules-ci",
"repo": "flake-parts",
"rev": "31729ca8cbdb4fa927b34e5f4353e6a83f39e993",
"rev": "024633cd702b10285db5cb19b40ad48d2399ba60",
"type": "github"
},
"original": {
@@ -267,11 +267,11 @@
]
},
"locked": {
"lastModified": 1789183968,
"narHash": "sha256-pEWnYdIF1pBMZwarp/rEPzl+Lknhm5hhjSfeLxH8nAA=",
"lastModified": 1791940130,
"narHash": "sha256-hRCCi4fp5IjLz4cA8+RkUsaYAHzbd7M5FSAjKOq4E+k=",
"owner": "nix-community",
"repo": "home-manager",
"rev": "cd1c9e552f41894aeb5cc5cb353d5a1d61550357",
"rev": "92a0ed1be12f1e20093faf8af63bae2c74ad521e",
"type": "github"
},
"original": {
@@ -308,11 +308,11 @@
]
},
"locked": {
"lastModified": 1789267719,
"narHash": "sha256-FIlwGdFjtpGYyL8g/RZZvIxshT9gdwJfcMjHRWHrc4U=",
"lastModified": 1792098797,
"narHash": "sha256-u4DIIZgznEGzByxXrxWCXK19VcMtTBmi/M9gZ7Jk9bM=",
"owner": "nix-community",
"repo": "home-manager",
"rev": "10d0acd7f81e3c035b452daa39ac7d1673880729",
"rev": "640725978b99076e18e069f6e7d2959124584f8f",
"type": "github"
},
"original": {
@@ -328,11 +328,11 @@
]
},
"locked": {
"lastModified": 1789127271,
"narHash": "sha256-vL/Fpo7Zxa7wvO8V5FAToUBvP+K3XsMB1wUglTtd/J0=",
"lastModified": 1791721963,
"narHash": "sha256-BYhx89XJltnRyQeuDKHVL5eSqbbfAcOKuDts7QRsrxQ=",
"owner": "NixOS",
"repo": "nixos-hardware",
"rev": "24cfdc1f9344b90a1eee329a3906e2f39f4d0f1e",
"rev": "60a624466c08787ee8303393b7d4752d1826f14f",
"type": "github"
},
"original": {
@@ -343,27 +343,24 @@
},
"nixpkgs": {
"locked": {
"lastModified": 1789006805,
"narHash": "sha256-xB8mKMOx1IA9vTDNLmJZ6n4wCMq/cuWBBOzGCRnqxrU=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "8ce4ef6cb6f871616146b9fe26d2a5ae594e94fe",
"type": "github"
"lastModified": 1791734076,
"narHash": "sha256-0dNcyVeoD61zhucIpt5BAQ+ytd6JzF641Z+A9bgltLo=",
"rev": "7fd4004d0511991fff3a0524856a9be09e28c5f0",
"type": "tarball",
"url": "https://releases.nixos.org/nixos/unstable/nixos-26.11pre1090327.7fd4004d0511/nixexprs.tar.zst"
},
"original": {
"owner": "NixOS",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"type": "github"
"type": "tarball",
"url": "https://channels.nixos.org/nixos-unstable/nixexprs.tar.zst"
}
},
"nixpkgs-stable": {
"locked": {
"lastModified": 1789114715,
"narHash": "sha256-ugpsyk3NM2s87vXfUiIIiibbJ4Pp0JPS5p/3mfs+q+c=",
"lastModified": 1791883866,
"narHash": "sha256-yvkDdToRZ4IgPc9tSBzzCYJvTLf8n5eE3rgUkpCuD5A=",
"owner": "nixos",
"repo": "nixpkgs",
"rev": "21a67dc470149f337cecafbe965d8d252a390518",
"rev": "a033e66ab94a6bedf2c3d58d93a36319d3cbbbaf",
"type": "github"
},
"original": {
@@ -375,11 +372,11 @@
},
"nixpkgs-unstable": {
"locked": {
"lastModified": 1789073787,
"narHash": "sha256-xfX/toC2QV707s06GbP4II/TxYF0fNQj7s5/LClNDKc=",
"lastModified": 1791966044,
"narHash": "sha256-t1hT8UW97rFCWCJO7/pClvu0AhLN5V3uir2M0ic4w/Q=",
"owner": "nixos",
"repo": "nixpkgs",
"rev": "aff8a0b28396750446e5537a96461bc4facdb287",
"rev": "319e4cebef10cbb636c6ea392137b52ad105336a",
"type": "github"
},
"original": {
@@ -391,11 +388,11 @@
},
"nixpkgs_2": {
"locked": {
"lastModified": 1789149629,
"narHash": "sha256-H6GwaZzZf+4npqv0tph94w9tZddSjFjmQrVsW0z78uk=",
"lastModified": 1791956154,
"narHash": "sha256-jBYGPi4udQ9uo4KQp9m2J0546nJVQitG15gvZSaVVAs=",
"owner": "nixos",
"repo": "nixpkgs",
"rev": "eaad089433ca2bb662274377d33df3d0e51ef28b",
"rev": "55bfb4d7437bd4e09ab7cba58a43bd68eb310044",
"type": "github"
},
"original": {
@@ -414,11 +411,11 @@
"systems": "systems"
},
"locked": {
"lastModified": 1789067777,
"narHash": "sha256-gN3OnYgJwCK0HX01dQGWusnirJuVHE9WigmSqOnyuCE=",
"lastModified": 1792012326,
"narHash": "sha256-DApZIjaKdU4XzglZ56yrPYLhG/ajoyuQ4g4s8tkHqxU=",
"owner": "nix-community",
"repo": "nixvim",
"rev": "16baff93297c63b6d4c497f00ffcf0b844b06fc6",
"rev": "8485794923eb406ce3728af320392226608f724b",
"type": "github"
},
"original": {
@@ -476,11 +473,11 @@
]
},
"locked": {
"lastModified": 1788914643,
"narHash": "sha256-4GuMPW90JSxXWDPUB9M+1m7fYbe3H0apOd86/zBQ2Kw=",
"lastModified": 1792056300,
"narHash": "sha256-YU1LjDe1o2Ymg5zEiCHbmMXLkDCtxHQRiVqZ3nC5GGk=",
"owner": "Mic92",
"repo": "sops-nix",
"rev": "13616fff713a9f94055c66f15687ebdc17a335df",
"rev": "44931708c62937c2b1bf7953902989fa5bb9ee1b",
"type": "github"
},
"original": {
@@ -509,11 +506,11 @@
"tinted-zed": "tinted-zed"
},
"locked": {
"lastModified": 1787771653,
"narHash": "sha256-DkkJSBOXWV/mja5Vy8az5g1KpZlsbUwlmH0BsQhowaQ=",
"lastModified": 1791574276,
"narHash": "sha256-UMnLnZ3JlA7UTBNNNx1rNsXYoPP/cirXLCKGiQ/yDx8=",
"owner": "danth",
"repo": "stylix",
"rev": "5e3809851f486e7fc7e84b40f174c74b60ecc784",
"rev": "2856c4c6a845b9bec98828ef197abe176e4806bb",
"type": "github"
},
"original": {
@@ -525,11 +522,11 @@
"systems": {
"flake": false,
"locked": {
"lastModified": 1774449309,
"narHash": "sha256-brhZ8DmuGtzkCYHJg4HEd602amKm89Y9ytsFZ5uWD1w=",
"lastModified": 1791244623,
"narHash": "sha256-uuanbkFk8a313Zfrxdcz8Us/yQtaxNnKJtX8v0ZPpd8=",
"owner": "nix-systems",
"repo": "default",
"rev": "c29398b59d2048c4ab79345812849c9bd15e9150",
"rev": "d36eeed142f88b5a636f2e3856a53c61654cf29b",
"type": "github"
},
"original": {
@@ -626,11 +623,11 @@
]
},
"locked": {
"lastModified": 1786901030,
"narHash": "sha256-WSFCsDSE5ffgD2MqzkM2CYjeFiKhRF/dJUN8uedb6YE=",
"lastModified": 1791885023,
"narHash": "sha256-C3alQ2MEt0zVrUSho5NUDo3jmhbff72++bfwoqT9Omo=",
"owner": "numtide",
"repo": "treefmt-nix",
"rev": "27b3b12a8e6375f28ebe122f07d230ca5459bbfa",
"rev": "0d6d739a833ba9a9c93034862e4a7b061a062a1c",
"type": "github"
},
"original": {

View File

@@ -24,7 +24,6 @@ in
configs/nixos/hosts/neogaia/hardware-configuration.nix \
configs/nixos/hosts/pikachu/hardware-configuration.nix \
configs/nixos/hosts/zeus/hardware-configuration.nix \
src/natu/testdata \
third_party \
-- .
treefmt

View File

@@ -6,7 +6,6 @@ inputs.treefmt-nix.lib.evalModule inputs.nixpkgs.legacyPackages.${system} {
settings.formatter.nixfmt.excludes = [
"configs/nixos/hosts/*/hardware-configuration.nix"
"src/natu/testdata/*.nix"
"third_party/**"
];
}

View File

@@ -1,8 +1,4 @@
{
pi-coding-agent,
root,
}:
pi-coding-agent.overrideAttrs {
src = root + "/third_party/pi";
patches = [ ];
{ pkgs, root }:
pkgs.callPackage (root + "/third_party/pi/nix/package.nix") {
source = root + "/third_party/pi";
}

View File

@@ -1,59 +0,0 @@
load("@rules_rust//rust:defs.bzl", "rust_binary", "rust_library", "rust_test")
rust_library(
name = "natu_lib",
crate_name = "natu",
srcs = [
"ast.rs",
"file_store.rs",
"natu.rs",
"parser.rs",
"rules.rs",
"rules/let_order.rs",
"rules/list_to_attrs_map.rs",
"rules/manual_inherit.rs",
"rules/manual_inherit_from.rs",
"rules/redundant_let.rs",
"rules/redundant_parameter_forwarding.rs",
"rules/unquoted_uri.rs",
"scope_graph.rs",
],
deps = [
"//src/status:status",
"//third_party/crates:rnix",
"//third_party/crates/rowan-0.16.1:rowan",
],
)
rust_test(
name = "file_store_test",
srcs = ["file_store_test.rs"],
deps = [":natu_lib"],
)
rust_test(
name = "natu_test",
srcs = ["natu_test.rs"],
data = [
"testdata/clean.nix",
"testdata/invalid.nix",
"testdata/lint_findings.nix",
],
deps = [
":natu_lib",
"//src/status:status",
"//third_party/crates:googletest",
],
)
rust_binary(
name = "natu",
crate_name = "natu_cli",
srcs = ["natu_main.rs"],
deps = [
":natu_lib",
"//src/monorepo:monorepo",
"//src/status:status",
"//third_party/crates:clap",
],
)

View File

@@ -1,21 +0,0 @@
[package]
name = "natu"
version = "0.1.0"
edition = "2024"
[lib]
path = "natu.rs"
[[bin]]
name = "natu"
path = "natu_main.rs"
[dependencies]
clap = { workspace = true, features = ["derive"] }
monorepo = { workspace = true }
rnix = { workspace = true }
rowan = { workspace = true }
status = { workspace = true }
[dev-dependencies]
googletest = { workspace = true }

View File

@@ -1,92 +0,0 @@
use crate::FileId;
#[derive(Debug)]
pub struct ParsedFile {
pub file_id: FileId,
pub root: Expr,
pub nodes: Vec<Node>,
pub tokens: Vec<Token>,
pub errors: Vec<ParseError>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Node {
pub range: SourceRange,
pub data: NodeData,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SourceRange {
pub start: usize,
pub end: usize,
}
impl std::fmt::Display for SourceRange {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(formatter, "{}..{}", self.start, self.end)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NodeData {
Binding(Binding),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Binding {
pub range: SourceRange,
pub key: Ident,
pub value: Expr,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Ident {
pub name: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Expr {
Ident(Ident),
Select(Select),
Apply(Apply),
Let {
range: SourceRange,
bindings: Vec<Binding>,
body: Box<Expr>,
},
AttrSet(Vec<Binding>),
Lambda {
parameters: Vec<Ident>,
body: Box<Expr>,
},
Other(Vec<Expr>),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Select {
pub receiver: String,
pub attr: Ident,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Apply {
pub lambda: Box<Expr>,
pub argument: Box<Expr>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Token {
pub range: SourceRange,
pub data: TokenData,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TokenData {
UnquotedUri(String),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseError {
pub range: SourceRange,
pub message: String,
}

View File

@@ -1,33 +0,0 @@
use std::path::PathBuf;
#[derive(Debug, Default)]
pub struct FileStore {
files: Vec<SourceFile>,
}
impl FileStore {
pub fn add(&mut self, file: SourceFile) -> FileId {
let id = FileId(self.files.len());
self.files.push(file);
id
}
pub fn get(&self, id: FileId) -> &SourceFile {
&self.files[id.0]
}
}
impl From<Vec<SourceFile>> for FileStore {
fn from(files: Vec<SourceFile>) -> Self {
Self { files }
}
}
#[derive(Debug)]
pub struct SourceFile {
pub path: PathBuf,
pub source: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct FileId(usize);

View File

@@ -1,33 +0,0 @@
use std::path::PathBuf;
use natu::{FileStore, SourceFile};
fn source_file(path: &str, source: &str) -> SourceFile {
SourceFile {
path: PathBuf::from(path),
source: source.to_owned(),
}
}
#[test]
fn added_file_can_be_retrieved_by_id() {
let mut store = FileStore::default();
let id = store.add(source_file("first.nix", "{ inherit foo; }"));
let file = store.get(id);
assert_eq!(PathBuf::from("first.nix"), file.path);
assert_eq!("{ inherit foo; }", file.source);
}
#[test]
fn file_ids_refer_to_their_added_files() {
let mut store = FileStore::default();
let first = store.add(source_file("first.nix", "first"));
let second = store.add(source_file("second.nix", "second"));
assert_ne!(first, second);
assert_eq!("first", store.get(first).source);
assert_eq!("second", store.get(second).source);
}

View File

@@ -1,121 +0,0 @@
use std::collections::HashSet;
mod ast;
mod file_store;
mod parser;
mod rules;
mod scope_graph;
use scope_graph::ScopeGraph;
pub use file_store::{FileId, FileStore, SourceFile};
pub use rules::{Diagnostic, Finding};
#[derive(Debug)]
pub struct Report {
pub files: FileStore,
pub diagnostics: Vec<Diagnostic>,
}
impl Report {
pub fn is_clean(&self) -> bool {
self.diagnostics.is_empty()
}
}
impl std::fmt::Display for Report {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut reported_let_order_files = HashSet::new();
for diagnostic in &self.diagnostics {
if diagnostic.finding.rule_id == "let_order" {
if !reported_let_order_files.insert(diagnostic.file_id) {
continue;
}
let file = self.files.get(diagnostic.file_id);
writeln!(
formatter,
"{} [let_order] Let bindings must follow dependency order",
file.path.display()
)?;
let mut findings = self
.diagnostics
.iter()
.filter(|candidate| {
candidate.file_id == diagnostic.file_id
&& candidate.finding.rule_id == "let_order"
})
.collect::<Vec<_>>();
findings.sort_by_key(|finding| finding.finding.range.start);
for finding in findings {
let (start, _) = line_range(&file.source, finding.finding.range);
let expected_order =
finding.finding.expected_order.as_ref().expect("let order");
writeln!(
formatter,
" let at line {start}: {}",
expected_order.join(", ")
)?;
}
continue;
}
let file = self.files.get(diagnostic.file_id);
let (start, end) = line_range(&file.source, diagnostic.finding.range);
let location = if start == end {
start.to_string()
} else {
format!("{start}-{end}")
};
writeln!(formatter, "{}:{location} {diagnostic}", file.path.display())?;
}
Ok(())
}
}
fn line_range(source: &str, range: ast::SourceRange) -> (usize, usize) {
let line_at = |offset| {
source
.bytes()
.take(offset)
.filter(|byte| *byte == b'\n')
.count()
+ 1
};
let start = line_at(range.start);
let end = line_at(range.end);
(start, end)
}
/// Analyzes source files and returns the diagnostics Natu finds.
pub fn future_sight(files: Vec<SourceFile>) -> status::Result<Report> {
let mut store = FileStore::default();
let mut diagnostics = Vec::new();
for file in files {
let file_id = store.add(file);
let file = store.get(file_id);
let parsed = parser::parse_file(file_id, &file.source);
if !parsed.errors.is_empty() {
return Err(status::Status::failed_precondition(format!(
"failed to parse {}",
file.path.display()
)));
}
let graph = ScopeGraph::from_file(&parsed);
diagnostics.extend(rules::run_rules(&parsed, &graph, &file.source));
}
Ok(Report {
files: store,
diagnostics,
})
}

View File

@@ -1,105 +0,0 @@
use clap::Parser;
use natu::{Report, SourceFile};
use status::ResultExt;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
fn main() -> ExitCode {
let args = Args::parse();
match analyze(args) {
Ok(report) if report.is_clean() => {
println!("No findings.");
ExitCode::SUCCESS
}
Ok(report) => {
print!("{report}");
ExitCode::from(1)
}
Err(error) => {
eprintln!("{error}");
ExitCode::from(2)
}
}
}
#[derive(Debug, Parser)]
struct Args {
#[arg(value_name = "PATH", default_value = ".")]
paths: Vec<PathBuf>,
}
fn analyze(args: Args) -> status::Result<Report> {
let paths: Vec<PathBuf> = args
.paths
.into_iter()
.map(monorepo::workspace::resolve_workspace_path)
.collect();
let files: Vec<SourceFile> = paths
.iter()
.map(|path| collect_source_files(path))
.collect::<status::Result<Vec<_>>>()?
.into_iter()
.flatten()
.collect();
natu::future_sight(files)
}
fn collect_source_files(path: &Path) -> status::Result<Vec<SourceFile>> {
let metadata = std::fs::symlink_metadata(path)
.with_context(|| format!("failed to read metadata for {}", path.display()))?;
if metadata.file_type().is_dir() {
if is_excluded_dir(path) {
return Ok(Vec::new());
}
let mut files = Vec::new();
for entry in std::fs::read_dir(path)
.with_context(|| format!("failed to read directory {}", path.display()))?
{
let entry =
entry.with_context(|| format!("failed to read entry in {}", path.display()))?;
files.extend(collect_source_files(&entry.path())?);
}
return Ok(files);
}
if metadata.file_type().is_file() && is_nix_file(path) {
return Ok(vec![SourceFile {
path: path.to_path_buf(),
source: std::fs::read_to_string(path)
.with_context(|| format!("failed to read source file {}", path.display()))?,
}]);
}
Ok(Vec::new())
}
// TODO: Add configurable exclusions.
fn is_excluded_dir(path: &Path) -> bool {
path.file_name()
.and_then(|name| name.to_str())
.is_some_and(|name| {
matches!(
name,
".git"
| "bazel-bin"
| "bazel-dev"
| "bazel-out"
| "bazel-testlogs"
| "target"
| "testdata"
| "third_party"
) || name == "result"
|| name.starts_with("result-")
})
}
fn is_nix_file(path: &Path) -> bool {
path.extension().is_some_and(|extension| extension == "nix")
}

View File

@@ -1,303 +0,0 @@
use std::path::{Path, PathBuf};
use googletest::matchers::{contains, eq, is_true};
use googletest::{OrFail, expect_that, gtest};
use status::Code;
use natu::SourceFile;
fn fixture_source(path: &str) -> googletest::Result<SourceFile> {
Ok(SourceFile {
path: PathBuf::from(path),
source: std::fs::read_to_string(fixture_path(path)?).or_fail()?,
})
}
fn fixture_path(path: &str) -> googletest::Result<PathBuf> {
if Path::new(path).exists() {
return Ok(PathBuf::from(path));
}
let runfiles = PathBuf::from(std::env::var("TEST_SRCDIR").or_fail()?);
let workspace = std::env::var("TEST_WORKSPACE").or_fail()?;
Ok(runfiles.join(workspace).join("src/natu").join(path))
}
#[gtest]
fn natu_accepts_clean_source() -> googletest::Result<()> {
let report = natu::future_sight(vec![fixture_source("testdata/clean.nix")?]).or_fail()?;
expect_that!(report.is_clean(), is_true());
Ok(())
}
#[gtest]
fn natu_rejects_invalid_source() -> googletest::Result<()> {
let error = natu::future_sight(vec![fixture_source("testdata/invalid.nix")?])
.err()
.or_fail()?;
expect_that!(error.code(), eq(Code::FailedPrecondition));
Ok(())
}
#[gtest]
fn natu_reports_out_of_order_let_bindings() -> googletest::Result<()> {
let report = natu::future_sight(vec![fixture_source("testdata/lint_findings.nix")?]).or_fail()?;
let let_order_count = report
.diagnostics
.iter()
.filter(|diagnostic| diagnostic.finding.rule_id == "let_order")
.count();
expect_that!(let_order_count, eq(2));
expect_that!(
report.to_string(),
eq(concat!(
"testdata/lint_findings.nix:11 [manual_inherit] Use `inherit` for this assignment\n",
"testdata/lint_findings.nix:12 [manual_inherit_from] Use `inherit` for this selected attribute\n",
"testdata/lint_findings.nix:13 [unquoted_uri] URI literals should be quoted\n",
"testdata/lint_findings.nix [let_order] Let bindings must follow dependency order\n",
" let at line 1: first, second, nested\n",
" let at line 4: nestedSecond, nestedFirst\n",
))
);
Ok(())
}
#[gtest]
fn natu_preserves_suppressed_bindings() -> googletest::Result<()> {
let report = natu::future_sight(vec![SourceFile {
path: PathBuf::from("testdata/nolint.nix"),
source: "{ config, ... }: let # NOLINT(redundant_let)\n cfg = config.example; # NOLINT(let_order)\n value = cfg;\nin value\n".into(),
}])
.or_fail()?;
expect_that!(report.is_clean(), is_true());
Ok(())
}
#[gtest]
fn natu_reports_select_dependency_order() -> googletest::Result<()> {
let report = natu::future_sight(vec![SourceFile {
path: PathBuf::from("testdata/select_dependencies.nix"),
source: r#"
let
dependency = { value = 1; };
entry = dependency.value;
in
entry
"#
.into(),
}])
.or_fail()?;
let count = report
.diagnostics
.iter()
.filter(|diagnostic| diagnostic.finding.rule_id == "let_order")
.count();
expect_that!(count, eq(1));
Ok(())
}
#[gtest]
fn natu_reports_redundant_let() -> googletest::Result<()> {
let report = natu::future_sight(vec![SourceFile {
path: PathBuf::from("testdata/redundant_let.nix"),
source: r#"
let
helper = 1;
value = helper;
in
value
"#
.into(),
}])
.or_fail()?;
let count = report
.diagnostics
.iter()
.filter(|diagnostic| diagnostic.finding.rule_id == "redundant_let")
.count();
expect_that!(count, eq(1));
Ok(())
}
#[gtest]
fn natu_accepts_nonredundant_let() -> googletest::Result<()> {
let report = natu::future_sight(vec![
SourceFile {
path: PathBuf::from("testdata/recursive_let.nix"),
source: r#"
let
recursive = recursive;
in
recursive
"#
.into(),
},
SourceFile {
path: PathBuf::from("testdata/dependent_let.nix"),
source: r#"
let
value = 1;
dependent = value;
in
value
"#
.into(),
},
])
.or_fail()?;
let count = report
.diagnostics
.iter()
.filter(|diagnostic| diagnostic.finding.rule_id == "redundant_let")
.count();
expect_that!(count, eq(0));
Ok(())
}
#[gtest]
fn natu_reports_redundant_parameter_forwarding() -> googletest::Result<()> {
let report = natu::future_sight(vec![
SourceFile {
path: PathBuf::from("testdata/attribute_parameter.nix"),
source: r#"
{ hosts, ... }:
let
collect = { hosts }: hosts;
in
collect { inherit hosts; }
"#
.into(),
},
SourceFile {
path: PathBuf::from("testdata/plain_parameter.nix"),
source: r#"
value:
let
transform = value: value;
in
transform value
"#
.into(),
},
SourceFile {
path: PathBuf::from("testdata/curried_parameter.nix"),
source: r#"
{ hosts, ... }:
let
transform = prefix: hosts: suffix: hosts;
in
transform "prefix" hosts "suffix"
"#
.into(),
},
SourceFile {
path: PathBuf::from("testdata/local_parameter.nix"),
source: r#"
let
transform = value: value;
in
transform value
"#
.into(),
},
])
.or_fail()?;
let count = report
.diagnostics
.iter()
.filter(|diagnostic| diagnostic.finding.rule_id == "redundant_parameter_forwarding")
.count();
expect_that!(count, eq(3));
Ok(())
}
#[gtest]
fn natu_reports_list_to_attrs_after_map() -> googletest::Result<()> {
let report = natu::future_sight(vec![SourceFile {
path: PathBuf::from("testdata/list_to_attrs.nix"),
source: r#"
let
generated = lib.listToAttrs (
map (item: lib.nameValuePair item item) items
);
generated_pairs = lib.listToAttrs (
concatLists (
mapAttrsToList (name: _: lib.nameValuePair name name) attrs
)
);
precomputed = lib.listToAttrs pairs;
in
{
inherit generated generated_pairs precomputed;
}
"#
.into(),
}])
.or_fail()?;
let count = report
.diagnostics
.iter()
.filter(|diagnostic| diagnostic.finding.rule_id == "list_to_attrs_map")
.count();
expect_that!(count, eq(1));
Ok(())
}
#[gtest]
fn natu_reports_unquoted_uri() -> googletest::Result<()> {
let report = natu::future_sight(vec![fixture_source("testdata/lint_findings.nix")?]).or_fail()?;
let findings = report
.diagnostics
.iter()
.map(|diagnostic| {
(
report.files.get(diagnostic.file_id).path.clone(),
diagnostic.finding.rule_id,
)
})
.collect::<Vec<_>>();
expect_that!(
findings,
contains(eq(&(
PathBuf::from("testdata/lint_findings.nix"),
"unquoted_uri"
)))
);
Ok(())
}
#[gtest]
fn natu_reports_manual_inherit() -> googletest::Result<()> {
let report = natu::future_sight(vec![fixture_source("testdata/lint_findings.nix")?]).or_fail()?;
let manual_inherit_count = report
.diagnostics
.iter()
.filter(|diagnostic| diagnostic.finding.rule_id == "manual_inherit")
.count();
expect_that!(manual_inherit_count, eq(1));
Ok(())
}
#[gtest]
fn natu_reports_manual_inherit_from() -> googletest::Result<()> {
let report = natu::future_sight(vec![fixture_source("testdata/lint_findings.nix")?]).or_fail()?;
let manual_inherit_from_count = report
.diagnostics
.iter()
.filter(|diagnostic| diagnostic.finding.rule_id == "manual_inherit_from")
.count();
expect_that!(manual_inherit_from_count, eq(1));
Ok(())
}

View File

@@ -1,295 +0,0 @@
use rnix::ast::{Attr, HasEntry};
use rowan::ast::AstNode;
use crate::{FileId, ast};
pub fn parse_file(file_id: FileId, source: &str) -> ast::ParsedFile {
let parse = rnix::Root::parse(source);
let source_len = source.len();
let syntax = parse.syntax();
let root = rnix::ast::Root::cast(syntax.clone()).expect("parser root is a root node");
let root = convert_expr(root.expr().expect("parser root has an expression"));
let (nodes, tokens) = convert_syntax(syntax);
ast::ParsedFile {
file_id,
root,
nodes,
tokens,
errors: parse
.errors()
.iter()
.map(|error| convert_parse_error(error, source_len))
.collect(),
}
}
fn convert_syntax(syntax: rnix::SyntaxNode) -> (Vec<ast::Node>, Vec<ast::Token>) {
let mut nodes = Vec::new();
let mut tokens = Vec::new();
for element in syntax.descendants_with_tokens() {
match element {
rnix::NodeOrToken::Node(node) => nodes.extend(convert_node(node)),
rnix::NodeOrToken::Token(token) => tokens.extend(convert_token(token)),
}
}
(nodes, tokens)
}
fn convert_expr(expr: rnix::ast::Expr) -> ast::Expr {
match expr {
rnix::ast::Expr::Ident(ident) => ast::Expr::Ident(ident.into()),
rnix::ast::Expr::Select(select) => convert_select_expr(select),
rnix::ast::Expr::Apply(apply) => ast::Expr::Apply(ast::Apply {
lambda: Box::new(convert_expr(apply.lambda().expect("applications have a lambda"))),
argument: Box::new(convert_expr(
apply.argument().expect("applications have an argument"),
)),
}),
rnix::ast::Expr::LetIn(let_in) => ast::Expr::Let {
range: let_in.syntax().text_range().into(),
bindings: let_in
.attrpath_values()
.filter_map(convert_binding_ast)
.collect(),
body: Box::new(convert_expr(
let_in.body().expect("let expressions have bodies"),
)),
},
rnix::ast::Expr::AttrSet(attr_set) => ast::Expr::AttrSet(convert_attr_set(attr_set)),
rnix::ast::Expr::Lambda(lambda) => ast::Expr::Lambda {
parameters: lambda_parameters(&lambda),
body: Box::new(convert_expr(lambda.body().expect("lambdas have bodies"))),
},
expr => ast::Expr::Other(
expr.syntax()
.children()
.filter_map(rnix::ast::Expr::cast)
.map(convert_expr)
.collect(),
),
}
}
fn convert_select_expr(select: rnix::ast::Select) -> ast::Expr {
select.clone().try_into().map(ast::Expr::Select).unwrap_or_else(|_| {
ast::Expr::Other(
select
.syntax()
.children()
.filter_map(rnix::ast::Expr::cast)
.map(convert_expr)
.collect(),
)
})
}
fn convert_binding_ast(binding: rnix::ast::AttrpathValue) -> Option<ast::Binding> {
let mut attrs = binding.attrpath()?.attrs();
let Attr::Ident(key) = attrs.next()? else {
return None;
};
Some(ast::Binding {
range: binding.syntax().text_range().into(),
key: key.into(),
value: convert_expr(binding.value()?),
})
}
fn convert_attr_set(attr_set: rnix::ast::AttrSet) -> Vec<ast::Binding> {
attr_set
.entries()
.flat_map(|entry| match entry {
rnix::ast::Entry::AttrpathValue(binding) => {
convert_binding_ast(binding).into_iter().collect()
}
rnix::ast::Entry::Inherit(inherit) => convert_inherit(inherit),
})
.collect()
}
fn convert_inherit(inherit: rnix::ast::Inherit) -> Vec<ast::Binding> {
let value = inherit
.from()
.and_then(|from| from.expr())
.map(convert_expr);
inherit
.attrs()
.filter_map(|attr| match attr {
Attr::Ident(ident) => Some(ident),
_ => None,
})
.map(|key| ast::Binding {
range: key.syntax().text_range().into(),
value: value
.clone()
.unwrap_or_else(|| ast::Expr::Ident(key.clone().into())),
key: key.into(),
})
.collect()
}
fn lambda_parameters(lambda: &rnix::ast::Lambda) -> Vec<ast::Ident> {
match lambda.param() {
Some(rnix::ast::Param::IdentParam(parameter)) => {
parameter.ident().map(Into::into).into_iter().collect()
}
Some(rnix::ast::Param::Pattern(pattern)) => pattern
.pat_entries()
.filter_map(|entry| entry.ident())
.chain(pattern.pat_bind().and_then(|binding| binding.ident()))
.map(Into::into)
.collect(),
None => Vec::new(),
}
}
fn convert_node(node: rnix::SyntaxNode) -> Option<ast::Node> {
match node.kind() {
rnix::SyntaxKind::NODE_ATTRPATH_VALUE => convert_binding(node),
_ => None,
}
}
fn convert_binding(node: rnix::SyntaxNode) -> Option<ast::Node> {
let binding = rnix::ast::AttrpathValue::cast(node)?;
let range = binding.syntax().text_range().into();
let mut attrs = binding.attrpath()?.attrs();
let Attr::Ident(key) = attrs.next()? else {
return None;
};
if attrs.next().is_some() {
return None;
}
Some(ast::Node {
range,
data: ast::NodeData::Binding(ast::Binding {
range,
key: key.into(),
value: convert_expr(binding.value()?),
}),
})
}
impl TryFrom<rnix::ast::AttrpathValue> for ast::Binding {
type Error = ();
fn try_from(binding: rnix::ast::AttrpathValue) -> Result<Self, Self::Error> {
let mut attrs = binding.attrpath().ok_or(())?.attrs();
let key = match attrs.next().ok_or(())? {
Attr::Ident(ident) => ident.into(),
_ => return Err(()),
};
if attrs.next().is_some() {
return Err(());
}
let value = binding.value().ok_or(())?.try_into()?;
Ok(Self {
range: binding.syntax().text_range().into(),
key,
value,
})
}
}
impl TryFrom<rnix::ast::Expr> for ast::Expr {
type Error = ();
fn try_from(expr: rnix::ast::Expr) -> Result<Self, Self::Error> {
match expr {
rnix::ast::Expr::Ident(ident) => Ok(Self::Ident(ident.into())),
rnix::ast::Expr::Select(select) => Ok(Self::Select(select.try_into()?)),
_ => Err(()),
}
}
}
impl From<rnix::ast::Ident> for ast::Ident {
fn from(ident: rnix::ast::Ident) -> Self {
Self {
name: ident.to_string(),
}
}
}
impl TryFrom<rnix::ast::Select> for ast::Select {
type Error = ();
fn try_from(select: rnix::ast::Select) -> Result<Self, Self::Error> {
if select.or_token().is_some() {
return Err(());
}
let mut attrs = select.attrpath().ok_or(())?.attrs();
let attr = match attrs.next().ok_or(())? {
Attr::Ident(ident) => ident.into(),
_ => return Err(()),
};
if attrs.next().is_some() {
return Err(());
}
Ok(Self {
receiver: select.expr().ok_or(())?.syntax().to_string(),
attr,
})
}
}
fn convert_token(token: rnix::SyntaxToken) -> Option<ast::Token> {
match token.kind() {
rnix::SyntaxKind::TOKEN_URI => Some(ast::Token {
range: token.text_range().into(),
data: ast::TokenData::UnquotedUri(token.text().to_string()),
}),
_ => None,
}
}
fn convert_parse_error(error: &rnix::ParseError, source_len: usize) -> ast::ParseError {
ast::ParseError {
range: parse_error_range(error, source_len),
message: error.to_string(),
}
}
fn parse_error_range(error: &rnix::ParseError, source_len: usize) -> ast::SourceRange {
match error {
rnix::ParseError::Unexpected(range)
| rnix::ParseError::UnexpectedExtra(range)
| rnix::ParseError::UnexpectedWanted(_, range, _)
| rnix::ParseError::UnexpectedDoubleBind(range)
| rnix::ParseError::DuplicatedArgs(range, _) => (*range).into(),
rnix::ParseError::UnexpectedEOF
| rnix::ParseError::UnexpectedEOFWanted(_)
| rnix::ParseError::RecursionLimitExceeded => ast::SourceRange {
start: source_len,
end: source_len,
},
_ => ast::SourceRange {
start: source_len,
end: source_len,
},
}
}
impl From<rnix::TextRange> for ast::SourceRange {
fn from(range: rnix::TextRange) -> Self {
Self {
start: usize::from(range.start()),
end: usize::from(range.end()),
}
}
}

View File

@@ -1,187 +0,0 @@
use crate::FileId;
use crate::ast;
use crate::rules::list_to_attrs_map::ListToAttrsMap;
use crate::rules::manual_inherit::ManualInherit;
use crate::rules::manual_inherit_from::ManualInheritFrom;
use crate::rules::unquoted_uri::UnquotedUri;
use crate::scope_graph::ScopeGraph;
pub mod let_order;
pub mod list_to_attrs_map;
pub mod manual_inherit;
pub mod manual_inherit_from;
pub mod redundant_let;
pub mod redundant_parameter_forwarding;
pub mod unquoted_uri;
#[derive(Debug)]
pub struct Diagnostic {
pub file_id: FileId,
pub finding: Finding,
}
#[derive(Debug)]
pub struct Finding {
pub rule_id: &'static str,
pub range: ast::SourceRange,
pub message: &'static str,
pub binding: Option<String>,
pub expected_order: Option<Vec<String>>,
}
impl std::fmt::Display for Diagnostic {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
formatter,
"[{}] {}",
self.finding.rule_id, self.finding.message
)?;
if let Some(binding) = &self.finding.binding {
write!(formatter, ": {binding}")?;
}
Ok(())
}
}
pub trait NodeRule {
type Node;
const ID: &'static str;
fn select(data: &ast::NodeData) -> Option<&Self::Node>;
fn check(node: &Self::Node) -> Option<&'static str>;
}
pub trait TokenRule {
type Token;
const ID: &'static str;
fn select(data: &ast::TokenData) -> Option<&Self::Token>;
fn check(token: &Self::Token) -> Option<&'static str>;
}
pub fn run_rules(file: &ast::ParsedFile, graph: &ScopeGraph, source: &str) -> Vec<Diagnostic> {
let node_diagnostics = file
.nodes
.iter()
.flat_map(|node| {
[
run_node_rule::<ListToAttrsMap>(node),
run_node_rule::<ManualInherit>(node),
run_node_rule::<ManualInheritFrom>(node),
]
})
.flatten();
let token_diagnostics = file
.tokens
.iter()
.flat_map(|token| [run_token_rule::<UnquotedUri>(token)])
.flatten();
let let_order_diagnostics =
let_order::check(graph, source)
.into_iter()
.map(|finding| Finding {
rule_id: "let_order",
range: finding.range,
message: "Let bindings must follow dependency order",
binding: None,
expected_order: Some(finding.expected_order),
});
let redundant_let_diagnostics =
redundant_let::check(&file.root)
.into_iter()
.map(|finding| Finding {
rule_id: "redundant_let",
range: finding.range,
message: "Inline this returned let binding",
binding: None,
expected_order: None,
});
let redundant_parameter_forwarding_diagnostics =
redundant_parameter_forwarding::check(&file.root)
.into_iter()
.map(|finding| Finding {
rule_id: "redundant_parameter_forwarding",
range: finding.range,
message: "Use the outer parameter instead of forwarding it",
binding: None,
expected_order: None,
});
node_diagnostics
.chain(token_diagnostics)
.chain(let_order_diagnostics)
.chain(redundant_let_diagnostics)
.chain(redundant_parameter_forwarding_diagnostics)
.filter(|finding| !is_suppressed(source, finding.range, finding.rule_id))
.map(|finding| Diagnostic {
file_id: file.file_id,
finding,
})
.collect()
}
pub fn is_suppressed(source: &str, range: ast::SourceRange, rule_id: &str) -> bool {
let line = source[range.start..].lines().next().unwrap_or_default();
line_suppresses(line, rule_id) || preceding_line_suppresses(source, range, rule_id)
}
fn preceding_line_suppresses(source: &str, range: ast::SourceRange, rule_id: &str) -> bool {
let Some((preceding_source, _current_line)) = source[..range.start].rsplit_once('\n') else {
return false;
};
let preceding_line = preceding_source.lines().next_back().unwrap_or_default();
line_suppresses(preceding_line, rule_id)
}
fn line_suppresses(line: &str, rule_id: &str) -> bool {
let Some(comment) = line.split_once('#').map(|(_, comment)| comment.trim()) else {
return false;
};
if comment == "NOLINT" {
return true;
}
comment
.strip_prefix("NOLINT(")
.and_then(|rules| rules.strip_suffix(')'))
.is_some_and(|rules| {
rules
.split(',')
.any(|candidate| candidate.trim() == rule_id)
})
}
fn run_node_rule<R>(node: &ast::Node) -> Option<Finding>
where
R: NodeRule,
{
let typed_node = R::select(&node.data)?;
let message = R::check(typed_node)?;
Some(Finding {
rule_id: R::ID,
range: node.range,
message,
binding: None,
expected_order: None,
})
}
fn run_token_rule<R>(token: &ast::Token) -> Option<Finding>
where
R: TokenRule,
{
let typed_token = R::select(&token.data)?;
let message = R::check(typed_token)?;
Some(Finding {
rule_id: R::ID,
range: token.range,
message,
binding: None,
expected_order: None,
})
}

View File

@@ -1,87 +0,0 @@
use crate::{
ast,
rules::is_suppressed,
scope_graph::{LetScope, NodeId, ScopeGraph},
};
pub struct Finding {
pub range: ast::SourceRange,
pub expected_order: Vec<String>,
}
pub fn check(graph: &ScopeGraph, source: &str) -> Vec<Finding> {
graph
.let_scopes()
.iter()
.flat_map(|let_scope| {
let expected = expected_order(graph, let_scope)
.into_iter()
.filter(|declaration| !binding_suppressed(let_scope, *declaration, source))
.collect::<Vec<_>>();
let actual = let_scope
.bindings
.iter()
.filter(|binding| !is_suppressed(source, binding.range, "let_order"))
.map(|binding| binding.declaration)
.collect::<Vec<_>>();
(!actual.starts_with(&expected)).then(|| Finding {
range: let_scope.range,
expected_order: expected
.iter()
.map(|declaration| binding_name(let_scope, *declaration).to_owned())
.collect(),
})
})
.collect()
}
fn binding_suppressed(let_scope: &LetScope, declaration: NodeId, source: &str) -> bool {
let binding = let_scope
.bindings
.iter()
.find(|binding| binding.declaration == declaration)
.expect("let declaration");
is_suppressed(source, binding.range, "let_order")
}
fn binding_name(let_scope: &LetScope, declaration: NodeId) -> &str {
&let_scope
.bindings
.iter()
.find(|binding| binding.declaration == declaration)
.expect("let declaration")
.name
}
fn expected_order(graph: &ScopeGraph, let_scope: &LetScope) -> Vec<NodeId> {
let mut order = Vec::new();
visit_references(graph, &let_scope.entry_references, let_scope, &mut order);
order
}
fn visit_references(
graph: &ScopeGraph,
references: &[NodeId],
let_scope: &LetScope,
order: &mut Vec<NodeId>,
) {
for reference in references {
for declaration in graph.resolve(*reference) {
let Some(binding) = let_scope
.bindings
.iter()
.find(|binding| binding.declaration == declaration)
else {
continue;
};
if order.contains(&declaration) {
continue;
}
order.push(declaration);
visit_references(graph, &binding.references, let_scope, order);
}
}
}

View File

@@ -1,58 +0,0 @@
use crate::{ast, rules::NodeRule};
pub struct ListToAttrsMap;
impl NodeRule for ListToAttrsMap {
type Node = ast::Binding;
const ID: &'static str = "list_to_attrs_map";
fn select(data: &ast::NodeData) -> Option<&Self::Node> {
let ast::NodeData::Binding(binding) = data;
Some(binding)
}
fn check(node: &Self::Node) -> Option<&'static str> {
matches_list_to_attrs_map(&node.value)
.then_some("Use `lib.genAttrs'` instead of `lib.listToAttrs` after `map`")
}
}
fn matches_list_to_attrs_map(expr: &ast::Expr) -> bool {
let ast::Expr::Apply(application) = unwrap_expr(expr) else {
return false;
};
is_lib_list_to_attrs(&application.lambda) && is_map_application(&application.argument)
}
fn unwrap_expr(expr: &ast::Expr) -> &ast::Expr {
match expr {
ast::Expr::Other(expressions) if expressions.len() == 1 => unwrap_expr(&expressions[0]),
_ => expr,
}
}
fn is_lib_list_to_attrs(expr: &ast::Expr) -> bool {
matches!(
unwrap_expr(expr),
ast::Expr::Select(select) if select.receiver == "lib" && select.attr.name == "listToAttrs"
)
}
fn is_map_application(expr: &ast::Expr) -> bool {
let ast::Expr::Apply(application) = unwrap_expr(expr) else {
return false;
};
is_map(&application.lambda)
}
fn is_map(expr: &ast::Expr) -> bool {
match unwrap_expr(expr) {
ast::Expr::Ident(ident) => ident.name == "map",
ast::Expr::Apply(application) => is_map(&application.lambda),
_ => false,
}
}

View File

@@ -1,24 +0,0 @@
use crate::{ast, rules::NodeRule};
pub struct ManualInherit;
impl NodeRule for ManualInherit {
type Node = ast::Binding;
const ID: &'static str = "manual_inherit";
fn select(data: &ast::NodeData) -> Option<&Self::Node> {
let ast::NodeData::Binding(binding) = data;
Some(binding)
}
fn check(node: &Self::Node) -> Option<&'static str> {
match &node.value {
ast::Expr::Ident(value) if node.key == *value => {
Some("Use `inherit` for this assignment")
}
_ => None,
}
}
}

View File

@@ -1,24 +0,0 @@
use crate::{ast, rules::NodeRule};
pub struct ManualInheritFrom;
impl NodeRule for ManualInheritFrom {
type Node = ast::Binding;
const ID: &'static str = "manual_inherit_from";
fn select(data: &ast::NodeData) -> Option<&Self::Node> {
let ast::NodeData::Binding(binding) = data;
Some(binding)
}
fn check(node: &Self::Node) -> Option<&'static str> {
match &node.value {
ast::Expr::Select(select) if node.key == select.attr => {
Some("Use `inherit` for this selected attribute")
}
_ => None,
}
}
}

View File

@@ -1,98 +0,0 @@
use crate::ast;
pub struct Finding {
pub range: ast::SourceRange,
}
pub fn check(expr: &ast::Expr) -> Vec<Finding> {
let mut findings = Vec::new();
check_expr(expr, &mut findings);
findings
}
fn check_expr(expr: &ast::Expr, findings: &mut Vec<Finding>) {
match expr {
ast::Expr::Let {
range,
bindings,
body,
} => {
if is_redundant(bindings, body) {
findings.push(Finding { range: *range });
}
for binding in bindings {
check_expr(&binding.value, findings);
}
check_expr(body, findings);
}
ast::Expr::AttrSet(bindings) => {
for binding in bindings {
check_expr(&binding.value, findings);
}
}
ast::Expr::Lambda { body, .. } => check_expr(body, findings),
ast::Expr::Apply(application) => {
check_expr(&application.lambda, findings);
check_expr(&application.argument, findings);
}
ast::Expr::Other(expressions) => {
for expression in expressions {
check_expr(expression, findings);
}
}
ast::Expr::Ident(_) | ast::Expr::Select(_) => { }
}
}
fn is_redundant(bindings: &[ast::Binding], body: &ast::Expr) -> bool {
let Some((binding_index, binding)) = bindings
.iter()
.enumerate()
.find(|(_, binding)| is_ident(body, &binding.key.name))
else {
return false;
};
!references_name(&binding.value, &binding.key.name)
&& !bindings.iter().enumerate().any(|(candidate_index, candidate)| {
candidate_index != binding_index && references_name(&candidate.value, &binding.key.name)
})
}
fn is_ident(expr: &ast::Expr, name: &str) -> bool {
matches!(unwrap_expr(expr), ast::Expr::Ident(ident) if ident.name == name)
}
fn references_name(expr: &ast::Expr, name: &str) -> bool {
match expr {
ast::Expr::Ident(ident) => ident.name == name,
ast::Expr::Select(select) => select.receiver == name,
ast::Expr::Apply(application) => {
references_name(&application.lambda, name) || references_name(&application.argument, name)
}
ast::Expr::Let { bindings, body, .. } => {
!bindings.iter().any(|binding| binding.key.name == name)
&& (bindings
.iter()
.any(|binding| references_name(&binding.value, name))
|| references_name(body, name))
}
ast::Expr::AttrSet(bindings) => bindings
.iter()
.any(|binding| references_name(&binding.value, name)),
ast::Expr::Lambda { parameters, body } => {
!parameters.iter().any(|parameter| parameter.name == name)
&& references_name(body, name)
}
ast::Expr::Other(expressions) => expressions
.iter()
.any(|expression| references_name(expression, name)),
}
}
fn unwrap_expr(expr: &ast::Expr) -> &ast::Expr {
match expr {
ast::Expr::Other(expressions) if expressions.len() == 1 => unwrap_expr(&expressions[0]),
_ => expr,
}
}

View File

@@ -1,244 +0,0 @@
use crate::ast;
pub struct Finding {
pub range: ast::SourceRange,
}
pub fn check(expr: &ast::Expr) -> Vec<Finding> {
let mut findings = Vec::new();
check_expr(expr, &[], &mut findings);
findings
}
fn check_expr(expr: &ast::Expr, outer_parameters: &[ast::Ident], findings: &mut Vec<Finding>) {
match expr {
ast::Expr::Let { bindings, body, .. } => {
check_let(bindings, body, outer_parameters, findings);
for binding in bindings {
check_expr(&binding.value, outer_parameters, findings);
}
check_expr(body, outer_parameters, findings);
}
ast::Expr::AttrSet(bindings) => {
for binding in bindings {
check_expr(&binding.value, outer_parameters, findings);
}
}
ast::Expr::Lambda { parameters, body } => check_expr(body, parameters, findings),
ast::Expr::Apply(application) => {
check_expr(&application.lambda, outer_parameters, findings);
check_expr(&application.argument, outer_parameters, findings);
}
ast::Expr::Other(expressions) => {
for expression in expressions {
check_expr(expression, outer_parameters, findings);
}
}
ast::Expr::Ident(_) | ast::Expr::Select(_) => { }
}
}
fn check_let(
bindings: &[ast::Binding],
let_body: &ast::Expr,
outer_parameters: &[ast::Ident],
findings: &mut Vec<Finding>,
) {
for binding in bindings {
let parameters = curried_parameters(&binding.value);
for (parameter_index, parameter) in parameters.iter().enumerate() {
if !outer_parameters
.iter()
.any(|outer_parameter| outer_parameter.name == parameter.name)
{
continue;
}
let usage = helper_usage(
bindings,
let_body,
&binding.key.name,
&parameter.name,
parameter_index,
);
if usage.calls > 0 && !usage.invalid {
findings.push(Finding {
range: binding.range,
});
break;
}
}
}
}
#[derive(Default)]
struct Usage {
calls: usize,
invalid: bool,
}
fn helper_usage(
bindings: &[ast::Binding],
body: &ast::Expr,
helper_name: &str,
parameter_name: &str,
parameter_index: usize,
) -> Usage {
let mut usage = Usage::default();
for binding in bindings {
inspect_usage(
&binding.value,
helper_name,
parameter_name,
parameter_index,
&mut usage,
);
}
inspect_usage(body, helper_name, parameter_name, parameter_index, &mut usage);
usage
}
fn inspect_usage(
expr: &ast::Expr,
helper_name: &str,
parameter_name: &str,
parameter_index: usize,
usage: &mut Usage,
) {
match expr {
ast::Expr::Ident(ident) => {
if ident.name == helper_name {
usage.invalid = true;
}
}
ast::Expr::Select(_) => { }
ast::Expr::Apply(_) => {
let (lambda, arguments) = application_parts(expr);
if is_ident(lambda, helper_name) {
let Some(argument) = arguments.get(parameter_index) else {
usage.invalid = true;
return;
};
if is_forwarded_parameter(argument, parameter_name) {
usage.calls += 1;
} else {
usage.invalid = true;
}
for argument in arguments {
inspect_usage(
argument,
helper_name,
parameter_name,
parameter_index,
usage,
);
}
} else {
for argument in arguments {
inspect_usage(
argument,
helper_name,
parameter_name,
parameter_index,
usage,
);
}
inspect_usage(lambda, helper_name, parameter_name, parameter_index, usage);
}
}
ast::Expr::Let { bindings, body, .. } => {
if bindings.iter().any(|binding| {
binding.key.name == helper_name || binding.key.name == parameter_name
}) {
return;
}
for binding in bindings {
inspect_usage(
&binding.value,
helper_name,
parameter_name,
parameter_index,
usage,
);
}
inspect_usage(body, helper_name, parameter_name, parameter_index, usage);
}
ast::Expr::AttrSet(bindings) => {
for binding in bindings {
inspect_usage(
&binding.value,
helper_name,
parameter_name,
parameter_index,
usage,
);
}
}
ast::Expr::Lambda { parameters, body } => {
if parameters.iter().any(|parameter| {
parameter.name == helper_name || parameter.name == parameter_name
}) {
return;
}
inspect_usage(body, helper_name, parameter_name, parameter_index, usage);
}
ast::Expr::Other(expressions) => {
for expression in expressions {
inspect_usage(
expression,
helper_name,
parameter_name,
parameter_index,
usage,
);
}
}
}
}
fn curried_parameters(expr: &ast::Expr) -> Vec<&ast::Ident> {
let mut parameters = Vec::new();
let mut body = expr;
while let ast::Expr::Lambda {
parameters: lambda_parameters,
body: lambda_body,
} = body
{
parameters.extend(lambda_parameters);
body = lambda_body;
}
parameters
}
fn application_parts(expr: &ast::Expr) -> (&ast::Expr, Vec<&ast::Expr>) {
let mut arguments = Vec::new();
let mut lambda = unwrap_expr(expr);
while let ast::Expr::Apply(application) = lambda {
arguments.push(&*application.argument);
lambda = unwrap_expr(&application.lambda);
}
arguments.reverse();
(lambda, arguments)
}
fn is_ident(expr: &ast::Expr, name: &str) -> bool {
matches!(unwrap_expr(expr), ast::Expr::Ident(ident) if ident.name == name)
}
fn is_forwarded_parameter(expr: &ast::Expr, parameter_name: &str) -> bool {
match unwrap_expr(expr) {
ast::Expr::Ident(ident) => ident.name == parameter_name,
ast::Expr::AttrSet(bindings) => matches!(
bindings.as_slice(),
[binding] if binding.key.name == parameter_name && is_ident(&binding.value, parameter_name)
),
_ => false,
}
}
fn unwrap_expr(expr: &ast::Expr) -> &ast::Expr {
match expr {
ast::Expr::Other(expressions) if expressions.len() == 1 => unwrap_expr(&expressions[0]),
_ => expr,
}
}

View File

@@ -1,19 +0,0 @@
use crate::{ast, rules::TokenRule};
pub struct UnquotedUri;
impl TokenRule for UnquotedUri {
type Token = String;
const ID: &'static str = "unquoted_uri";
fn select(data: &ast::TokenData) -> Option<&Self::Token> {
match data {
ast::TokenData::UnquotedUri(uri) => Some(uri),
}
}
fn check(_token: &Self::Token) -> Option<&'static str> {
Some("URI literals should be quoted")
}
}

View File

@@ -1,206 +0,0 @@
use crate::ast::{self, ParsedFile};
#[derive(Debug)]
pub(crate) struct ScopeGraph {
nodes: Vec<Node>,
edges: Vec<Edge>,
lets: Vec<LetScope>,
}
impl ScopeGraph {
pub(crate) fn from_file(file: &ParsedFile) -> Self {
let mut graph = Self {
nodes: Vec::new(),
edges: Vec::new(),
lets: Vec::new(),
};
let root = graph.add_scope(None);
graph.build_expr(&file.root, root);
graph
}
pub(crate) fn let_scopes(&self) -> &[LetScope] {
&self.lets
}
fn build_expr(&mut self, expr: &ast::Expr, scope: NodeId) -> Vec<NodeId> {
match expr {
ast::Expr::Ident(ident) => vec![self.add_reference(&ident.name, scope)],
ast::Expr::Let {
range,
bindings,
body,
} => self.build_let(*range, bindings, body, scope),
ast::Expr::AttrSet(bindings) => bindings
.iter()
.flat_map(|binding| self.build_expr(&binding.value, scope))
.collect(),
ast::Expr::Lambda { parameters, body } => {
let scope = self.add_scope(Some(scope));
for parameter in parameters {
self.add_declaration(&parameter.name, scope);
}
self.build_expr(body, scope)
}
ast::Expr::Apply(application) => [
self.build_expr(&application.lambda, scope),
self.build_expr(&application.argument, scope),
]
.concat(),
ast::Expr::Other(expressions) => expressions
.iter()
.flat_map(|expression| self.build_expr(expression, scope))
.collect(),
ast::Expr::Select(select) => vec![self.add_reference(&select.receiver, scope)],
}
}
fn build_let(
&mut self,
range: ast::SourceRange,
bindings: &[ast::Binding],
body: &ast::Expr,
parent: NodeId,
) -> Vec<NodeId> {
let scope = self.add_scope(Some(parent));
let mut graph_bindings = bindings
.iter()
.map(|binding| Binding {
declaration: self.add_declaration(&binding.key.name, scope),
name: binding.key.name.clone(),
references: Vec::new(),
range: binding.range,
})
.collect::<Vec<_>>();
for (binding, graph_binding) in bindings.iter().zip(&mut graph_bindings) {
graph_binding.references = self.build_expr(&binding.value, scope);
}
let entry_references = self.build_expr(body, scope);
let references = graph_bindings
.iter()
.flat_map(|binding| binding.references.iter().copied())
.chain(entry_references.iter().copied())
.collect();
self.lets.push(LetScope {
range,
bindings: graph_bindings,
entry_references,
});
references
}
pub(crate) fn resolve(&self, reference: NodeId) -> Vec<NodeId> {
let Node::Reference(name) = &self.nodes[reference.0] else {
return Vec::new();
};
let Some(mut scope) = self.edge_target(reference, Node::is_scope) else {
return Vec::new();
};
loop {
let declarations = self
.edge_targets(scope, |node| matches!(node, Node::Declaration(declaration) if declaration.name == *name))
.collect::<Vec<_>>();
if !declarations.is_empty() {
return declarations;
}
let Some(parent) = self.edge_target(scope, Node::is_scope) else {
return Vec::new();
};
scope = parent;
}
}
fn add_scope(&mut self, parent: Option<NodeId>) -> NodeId {
let scope = self.add_node(Node::Scope);
if let Some(parent) = parent {
self.add_edge(scope, parent);
}
scope
}
fn add_declaration(&mut self, name: &str, scope: NodeId) -> NodeId {
let declaration = self.add_node(Node::Declaration(Declaration {
name: name.to_owned(),
}));
self.add_edge(scope, declaration);
declaration
}
fn add_reference(&mut self, name: &str, scope: NodeId) -> NodeId {
let reference = self.add_node(Node::Reference(name.to_owned()));
self.add_edge(reference, scope);
reference
}
fn add_node(&mut self, node: Node) -> NodeId {
let id = NodeId(self.nodes.len());
self.nodes.push(node);
id
}
fn add_edge(&mut self, from: NodeId, to: NodeId) {
self.edges.push(Edge { from, to });
}
fn edge_target(&self, from: NodeId, predicate: fn(&Node) -> bool) -> Option<NodeId> {
self.edge_targets(from, predicate).next()
}
fn edge_targets<'graph>(
&'graph self,
from: NodeId,
predicate: impl Fn(&Node) -> bool + 'graph,
) -> impl Iterator<Item = NodeId> + 'graph {
self.edges
.iter()
.filter(move |edge| edge.from == from && predicate(&self.nodes[edge.to.0]))
.map(|edge| edge.to)
}
}
#[derive(Debug)]
enum Node {
Scope,
Declaration(Declaration),
Reference(String),
}
impl Node {
fn is_scope(&self) -> bool {
matches!(self, Self::Scope)
}
}
#[derive(Debug)]
struct Declaration {
name: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct NodeId(usize);
#[derive(Debug)]
struct Edge {
from: NodeId,
to: NodeId,
}
#[derive(Debug)]
pub(crate) struct LetScope {
pub(crate) range: ast::SourceRange,
pub(crate) bindings: Vec<Binding>,
pub(crate) entry_references: Vec<NodeId>,
}
#[derive(Debug)]
pub(crate) struct Binding {
pub(crate) declaration: NodeId,
pub(crate) name: String,
pub(crate) references: Vec<NodeId>,
pub(crate) range: ast::SourceRange,
}

View File

@@ -1,29 +0,0 @@
{ pkgs }:
let
first = 1;
second = first;
in {
firstField = first;
secondField = second;
nested = let
innerSecond = innerFirst;
innerFirst = first;
in {
result = innerSecond;
};
parameter = first: let
usesParameter = first;
in {
result = usesParameter;
};
path = ./. + "/foo";
url = "https://example.com";
inherit pkgs;
different = other;
nested.package = nested.package;
"quoted" = quoted;
${dynamic} = dynamic;
from = pkgs.from.other;
fallback = pkgs.fallback or null;
}

View File

@@ -1,4 +0,0 @@
{ pkgs }:
{
inherit pkgs;

View File

@@ -1,17 +0,0 @@
let
second = first;
first = 1;
nested = let
nestedFirst = first;
nestedSecond = nestedFirst;
in {
result = nestedSecond;
};
in {
package = package;
from = pkgs.from;
url = https://example.com;
firstField = first;
secondField = second;
nestedField = nested;
}

View File

@@ -1 +0,0 @@
../../craft-skill

View File

@@ -0,0 +1,22 @@
# Skill mechanics
The skill-specific branch of [`agent-writing-guide`](SKILL.md): what changes when the document is a skill (frontmatter, the invocation choice, and router skills). Everything else about writing it is the universal reference in `SKILL.md`.
## Invocation
Two choices, trading the two loads:
- A **model-invoked** skill keeps a `description`, so the agent can fire it autonomously, and other skills can reach it. You can still type its name: model-invocation always _includes_ user reach; a description only ever adds agent discovery, never removes the human's. The description is the skill's top-level context pointer, forced to stay loaded at all times: permanent context load in exchange for discoverability. A model-invoked skill whose content is all reference is also one home for shared reference: another skill can invoke it, so reference needed by several skills lives in one place. Mechanics: omit `disable-model-invocation`, and write a model-facing description carrying the trigger branches (the pointer-writing rules in `SKILL.md` apply in full).
- A **user-invoked** skill strips the description from the agent's reach: only the human typing its name can invoke it, and no other skill can. Zero context load, but it spends cognitive load: you are the index that must remember it exists. Mechanics: set `disable-model-invocation: true`; the `description` becomes human-facing: a one-line summary, trigger lists stripped.
Pick model-invocation only when the agent must reach the skill on its own, or another skill must. If it only ever fires by hand, make it user-invoked and pay no context load.
Shared reference that two user-invoked skills both need can live in neither: neither skill exposes model invocation. Push it to a plain file outside the skill system: external reference any skill can point at.
## Splitting by invocation
The invocation cut of splitting (the sequence cut lives in `SKILL.md`): split off a model-invoked skill when you have a distinct leading word that should trigger it on its own (a trigger word you actually use in your prompts), or another skill must reach it. You pay context load for the new always-loaded description, so that independent reach has to be worth it.
## Router skills
When user-invoked skills multiply past what you can remember, that piled-up cognitive load is cured by a **router skill**: one user-invoked skill that names the others and when to reach for each, so the human has one skill to remember instead of many. It can only hint, never fire them: `disable-model-invocation: true` prevents model invocation, so nothing but the human can reach them.

View File

@@ -0,0 +1,81 @@
---
name: agent-writing-guide
description: Writing documents for agents. Use when creating or editing skills, or modifying AGENTS.md or CLAUDE.md.
---
Reference for writing any document an agent consumes: a skill, an `AGENTS.md` / `CLAUDE.md`, a doc reached by a pointer. The packaging differs; the writing does not: the same levers make each one predictable, since the agent takes the same _process_ every run rather than producing the same output.
When the document you're writing is a skill, read [`SKILL-MECHANICS.md`](SKILL-MECHANICS.md) for frontmatter, invocation choice, and router skills.
## Context pointers
A **context pointer** is a reference held in the agent's context that names some out-of-context material and encodes the condition for reaching it. A skill's description is one; a line in `AGENTS.md` naming a doc is the same object. The pointer's _wording_, not its target, decides when the agent reaches the material, and how reliably. A must-have target behind a weakly worded pointer is a variance bug: sharpen the wording first, and inline the material only if sharpening fails.
A pointer does two jobs: state what the material is, and list the **branches** that should trigger reaching it (a branch is a distinct case the document handles, so different runs take different paths through it). Every word of an always-loaded pointer costs on every turn, so it earns even harder pruning than the body:
- **Front-load the leading word**: the pointer is where it does its triggering work.
- **One trigger per branch.** Synonyms that rename a single branch are one branch written twice; collapse them and keep only genuinely distinct branches.
- **Cut identity the body already carries.**
## The two loads
Every document and pointer you add spends one of two budgets:
- **Context load** is the cost of always-loaded material on the agent's window: an `AGENTS.md` line, a skill description, anything sitting in context every turn, spending tokens and attention whether or not it fires.
- **Cognitive load** is the cost on the human: which documents exist and when to reach for each. The human is the index. Not a cost to minimise: it is the price of human agency; spend it where human judgement matters, remove it where it does not.
Material reached only through a pointer escapes context load at the price of the pointer's own line; material with no pointer at all rides entirely on cognitive load.
## Information hierarchy
A document is built from two content types: **steps** (the ordered actions the agent performs) and **reference** (definitions, rules, facts consulted on demand). The two mix freely: all steps (a recipe), all reference (a review's rules, this skill), or both. The core decision is where each piece sits on the **information hierarchy**, a ladder ranked by how immediately the agent needs the material:
1. **In-file step** is the primary tier: what the agent does, in order.
2. **In-file reference** is consulted on demand. Often a legitimately flat peer-set (every rule of a review on one rung), which is a fine arrangement, not a smell.
3. **Disclosed reference** is pushed out into a separate file, reached by a context pointer, loaded only when the pointer fires. Spans a sibling file in the same folder through fully external reference that lives anywhere and any document can point at.
Push too little down and the top bloats; push too much and you hide material the agent actually needs. That tension is the whole decision.
**Progressive disclosure** is the move down the ladder (out of the main file and behind a pointer) so the top stays legible. Not primarily a token optimisation: it is how the hierarchy is protected. Branching is the cleanest disclosure test: inline what every branch needs, and push behind a pointer what only some branches reach. When a document has steps, in-file reference that should be disclosed buries them and turns attending to them into a coin-flip: a variance lever, not just a legibility one.
**Co-location** is the within-file companion: where the ladder decides _how far down_ a piece sits, co-location decides _what sits beside it_ once there. Keep a concept's definition, rules, and caveats under one heading rather than scattered, so reading one part brings its neighbours with it. The test: the document should read like documentation written for the agent. Grouped material reads that way; scattered material does not. (Distinct from duplication: that repeats one meaning in two places; scattering fragments one meaning across many.)
**Sprawl** is the failure mode here: a document simply too long, even when every line is live and unique. Attention thins across the excess, and every extra line is one more to keep relevant. The cure is the ladder: disclose reference behind pointers, and split by branch or sequence so each path carries only what it needs.
## Steps and completion criteria
Every step ends on a **completion criterion**, the condition that tells the agent the work is done. Two properties make it a lever:
- **Clarity**: can the agent tell done from not-done? A vague bound ("understanding reached") invites **premature completion**: ending the step before it is genuinely done, attention slipping to _being done_. The visible steps still ahead (the **post-completion steps**) supply the pull; the criterion's clarity is the resistance. Defend in order: **sharpen the bound first** (local and cheap); only if it is irreducibly fuzzy _and_ you observe the rush, hide the later steps by splitting the sequence. Hiding only works across a real context boundary (a hand-off or a subagent dispatch; an inline call leaves the later steps in context and clears nothing).
- **Demand**: how much it requires. "Every modified model accounted for" forces thorough work where "produce a change list" does not. Demand drives **legwork** (the digging the agent does within the work, latent in the wording rather than written as its own step), and it is not step-bound: "every rule applied" binds a body of flat reference just as "every step done" binds a sequence, which is how an all-reference document still carries an exhaustiveness bar.
The strongest criteria are both checkable and exhaustive.
## When to split
Splitting one document into two spends one of the two loads, so split only when the cut earns it:
- **By sequence**: split a run of steps where the post-completion steps tempt the agent to rush the one in front of it. Keeping them out of view drives more legwork on the current task. Beware the reverse: merging sequences exposes each step's later steps to what follows, inviting premature completion.
- **By invocation**, skill-specific: see [`SKILL-MECHANICS.md`](SKILL-MECHANICS.md).
## Leading words
A **leading word** is a compact concept already living in the model's pretraining that the agent thinks with while running the document (_lesson_, _fog of war_, _tracer bullets_). Repeated as a token, never as a sentence, it accumulates a distributed definition and anchors a whole region of behaviour in the fewest tokens, by recruiting priors the model already holds. Coining your own works if you define it clearly, but a made-up word recruits no priors: you pay in definition tokens what a pretrained word gives free; reach for an existing word first.
It anchors twice. In the body, _execution_: the agent reaches for the same behaviour every time the word appears, and inside flat reference it focuses attention on a class of thing to look for. In a pointer, _invocation_: when the same word lives in your prompts, your docs, and your codebase, the agent links that shared language to the material and reaches it more reliably.
Hunt for opportunities to refactor with leading words. A triad spelled out at three sites, a pointer spending a sentence to gesture at one idea. Each is a passage begging to collapse into a single token:
- "fast, deterministic, low-overhead" → _tight_ (a _tight_ loop).
- "a loop you believe in" → _red_, turning a fuzzy gate into a binary observable state (the loop goes _red_ on the bug, or it doesn't).
You win twice: fewer tokens, and a sharper hook for the agent to hang its thinking on. Assume every document is carrying restatements that leading words retire. Go find them.
**Negation** is the failure mode beside this lever: steering by prohibition drags the forbidden behaviour into context and makes it _more_ available, not less. _Don't think of an elephant_, and the elephant is all there is; the negation is a weak modifier the strongly-activated concept overruns, so the ban half-reads as an instruction to do the thing. Prompt the **positive**: state the target behaviour ("write one-line comments") so the banned one is never spoken. A prohibition earns its place only as a hard guardrail you cannot phrase positively; even then, pair it with the positive target so attention lands on what to do.
## Pruning
- Keep each meaning in a **single source of truth**: one authoritative place, so changing the behaviour is a one-place edit. **Duplication** (the same meaning in more than one place) costs maintenance and tokens, and inflates a meaning's prominence on the ladder past its real rank. (The accidental inverse of a leading word, which repeats a token on purpose, never the meaning.)
- The **environment** is a source of truth too (`package.json` scripts, config files, the directory layout, `--help` output), and a document that restates it is a **cache**: a copy of a lookup, earning its load only when the lookup is expensive. Cache what the agent cannot find by looking: the unwritten convention, the reason behind a choice, the gotcha no config confesses. Leave the one-file, one-command lookups to the environment, where they cannot go stale.
- Check every line for **relevance**: does it still bear on what the document does? A line loses relevance by never bearing on the task (mere exposition, or a branch that should be disclosed) or by going stale as the behaviour or world it describes changes. Shorter documents are easier to keep relevant. Without a pruning discipline the default fate is **sediment**: stale layers that settle because adding feels safe and removing feels risky, until you must core down through them to find what is still live.
- Hunt **no-ops** sentence by sentence: an instruction the model already obeys by default pays load to say nothing. The test (does it change behaviour versus the default?) is model-relative, not reader-relative: two people disagreeing about a no-op disagree about the default, and settle it by running the document, not by debate. When a sentence fails, delete the whole sentence rather than trim words from it. The test also grades leading words: a word too weak to beat the default (_be thorough_ when the agent is already thorough-ish) is a no-op, and the fix is a stronger word (_relentless_), not a different technique.

View File

@@ -0,0 +1,146 @@
---
name: conventional-commits
description: Use when writing or reviewing Conventional Commit messages.
---
# Conventional Commits 1.0.0
## Summary
The Conventional Commits specification is a lightweight convention on top of commit messages.
It provides an easy set of rules for creating an explicit commit history;
which makes it easier to write automated tools on top of.
This convention dovetails with [SemVer](http://semver.org),
by describing the features, fixes, and breaking changes made in commit messages.
The commit message should be structured as follows:
---
```
<type>[optional scope]: <description>
[optional body]
[optional footer(s)]
```
---
The commit contains the following structural elements, to communicate intent to the
consumers of your library:
1. **fix:** a commit of the _type_ `fix` patches a bug in your codebase (this correlates with [`PATCH`](http://semver.org/#summary) in Semantic Versioning).
2. **feat:** a commit of the _type_ `feat` introduces a new feature to the codebase (this correlates with [`MINOR`](http://semver.org/#summary) in Semantic Versioning).
3. **BREAKING CHANGE:** a commit that has a footer `BREAKING CHANGE:`, or appends a `!` after the type/scope, introduces a breaking API change (correlating with [`MAJOR`](http://semver.org/#summary) in Semantic Versioning).
A BREAKING CHANGE can be part of commits of any _type_.
4. _types_ other than `fix:` and `feat:` are allowed, for example [@commitlint/config-conventional](https://github.com/conventional-changelog/commitlint/tree/master/%40commitlint/config-conventional) (based on the [Angular convention](https://github.com/angular/angular/blob/22b96b9/CONTRIBUTING.md#type)) recommends `build:`, `chore:`,
`ci:`, `docs:`, `style:`, `refactor:`, `perf:`, `test:`, and others.
5. _footers_ other than `BREAKING CHANGE: <description>` may be provided and follow a convention similar to
[git trailer format](https://git-scm.com/docs/git-interpret-trailers).
Additional types are not mandated by the Conventional Commits specification, and have no implicit effect in Semantic Versioning (unless they include a BREAKING CHANGE).
A scope may be provided to a commit’s type, to provide additional contextual information and is contained within parenthesis, e.g., `feat(parser): add ability to parse arrays`.
## Examples
### Commit message with description and breaking change footer
```
feat: allow provided config object to extend other configs
BREAKING CHANGE: `extends` key in config file is now used for extending other config files
```
### Commit message with `!` to draw attention to breaking change
```
feat!: send an email to the customer when a product is shipped
```
### Commit message with scope and `!` to draw attention to breaking change
```
feat(api)!: send an email to the customer when a product is shipped
```
### Commit message with both `!` and BREAKING CHANGE footer
```
chore!: drop support for Node 6
BREAKING CHANGE: use JavaScript features not available in Node 6.
```
### Commit message with no body
```
docs: correct spelling of CHANGELOG
```
### Commit message with scope
```
feat(lang): add Polish language
```
### Commit message with multi-paragraph body and multiple footers
```
fix: prevent racing of requests
Introduce a request id and a reference to latest request. Dismiss
incoming responses other than from latest request.
Remove timeouts which were used to mitigate the racing issue but are
obsolete now.
Reviewed-by: Z
Refs: #123
```
## Specification
The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [RFC 2119](https://www.ietf.org/rfc/rfc2119.txt).
1. Commits MUST be prefixed with a type, which consists of a noun, `feat`, `fix`, etc.,
followed by the OPTIONAL scope, OPTIONAL `!`, and REQUIRED terminal colon and space.
2. The type `feat` MUST be used when a commit adds a new feature to your application or library.
3. The type `fix` MUST be used when a commit represents a bug fix for your application.
4. A scope MAY be provided after a type.
A scope MUST consist of a noun describing a section of the codebase surrounded by parenthesis, e.g., `fix(parser):`
5. A description MUST immediately follow the colon and space after the type/scope prefix.
The description is a short summary of the code changes, e.g., _fix: array parsing issue when multiple spaces were contained in string_.
6. A longer commit body MAY be provided after the short description, providing additional contextual information about the code changes.
The body MUST begin one blank line after the description.
7. A commit body is free-form and MAY consist of any number of newline separated paragraphs.
8. One or more footers MAY be provided one blank line after the body.
Each footer MUST consist of a word token, followed by either a `:<space>` or `<space>#` separator, followed by a string value (this is inspired by the [git trailer convention](https://git-scm.com/docs/git-interpret-trailers)).
9. A footer’s token MUST use `-` in place of whitespace characters, e.g., `Acked-by` (this helps differentiate the footer section from a multi-paragraph body).
An exception is made for `BREAKING CHANGE`, which MAY also be used as a token.
10. A footer’s value MAY contain spaces and newlines, and parsing MUST terminate when the next valid footer token/separator pair is observed.
11. Breaking changes MUST be indicated in the type/scope prefix of a commit, or as an entry in the footer.
12. If included as a footer, a breaking change MUST consist of the uppercase text BREAKING CHANGE, followed by a colon, space, and description, e.g., _BREAKING CHANGE: environment variables now take precedence over config files_.
13. If included in the type/scope prefix, breaking changes MUST be indicated by a `!` immediately before the `:`.
If `!` is used, `BREAKING CHANGE:` MAY be omitted from the footer section, and the commit description SHALL be used to describe the breaking change.
14. Types other than `feat` and `fix` MAY be used in your commit messages, e.g., _docs: updated ref docs._
15. The units of information that make up Conventional Commits MUST NOT be treated as case sensitive by implementors, with the exception of BREAKING CHANGE which MUST be uppercase.
16. BREAKING-CHANGE MUST be synonymous with BREAKING CHANGE, when used as a token in a footer.
## FAQ
### How does Conventional Commits handle revert commits?
Reverting code can be complicated: are you reverting multiple commits?
if you are reverting a feature, should the next release instead be a patch?
Conventional Commits does not make an explicit effort to define revert behavior.
Instead we leave it to tooling authors to use the flexibility of _types_ and _footers_ to develop their logic for handling reverts.
One recommendation is to use the `revert` type, and a footer that references the commit SHAs that are being reverted:
```
revert: let us never again speak of the noodle incident
Refs: 676104e, a215868
```

View File

@@ -1,161 +0,0 @@
# Glossary — Skill Craft
This glossary defines the checks for [`craft-skill`](SKILL.md).
Each term is a lever on **predictability**.
## Predictability
The degree to which a skill makes the agent follow the same process on every run.
Predictability does not require identical output.
A brainstorming skill can predictably produce different ideas.
## Invocation
How the agent or operator reaches a skill.
Invocation controls who pays the load for discovery.
### Model-invoked
A skill that the harness exposes to the agent's available-skills list.
The agent can load it without an explicit operator command.
Use model invocation when the agent must discover the skill on its own.
### User-invoked
A skill that the operator runs deliberately through the harness invocation mechanism.
Use user invocation when human judgment decides when the skill applies.
For Pi, keep the required description and add `disable-model-invocation: true`.
### Description
Required metadata that states what the skill does and when to use it.
For model-invoked skills, the description carries the trigger condition.
For user-invoked skills, the description remains valid metadata.
### Context pointer
A short reference that tells the agent when to load out-of-context material.
The pointer's wording controls whether the agent reaches the target.
Fix weak wording before moving the target inline.
The description is the top-level context pointer for a model-invoked skill.
A link to a sibling reference file is a lower-level context pointer.
### Context load
The permanent attention cost of model-invoked skill descriptions.
More discoverable skills create more context load.
Use context load to decide whether a skill needs model invocation.
### Cognitive load
The memory cost that user-invoked skills place on the operator.
More user-invoked skills make the operator remember more names and uses.
Use cognitive load to decide whether a skill needs discoverability.
## Information hierarchy
How a skill ranks information by the moment the agent needs it.
Keep the active procedure above supporting reference.
Move branch-specific or large reference behind context pointers.
### Steps
Ordered actions that the agent performs.
Put steps in `SKILL.md` when the skill has an active procedure.
End each step with a completion criterion.
### Reference
Material that the agent consults while following steps.
Keep short reference near the step that needs it.
Move large or branch-specific reference to sibling files.
### External reference
Authoritative material that lives outside the skill directory.
Point to external reference instead of duplicating project policy.
Use it when another file owns the meaning.
### Progressive disclosure
Moving reference out of `SKILL.md` and behind a precise context pointer.
Use progressive disclosure to protect the skill's active procedure.
Keep must-read material inline when a pointer would miss too often.
### Co-location
Keeping a concept's rules, caveats, and examples near one another.
Use co-location so one read gives the agent the complete local meaning.
Do not scatter one concept across unrelated sections.
## Steering
How a skill shapes the agent's runtime behavior.
Steering turns a document into a repeatable process.
### Branch
A distinct path through a skill.
A branch handles a case that does not run the same steps as other cases.
Do not call ordinary checklist items branches.
### Leading word
A compact term that anchors a repeated behavior.
Prefer words already used by prompts, docs, or code.
Repeat the word, not the full explanation.
### Completion criterion
The condition that tells the agent a step is complete.
A strong completion criterion is checkable and demanding.
Use it to prevent early movement to the next step.
### Legwork
The work the agent performs inside a step.
Strong completion criteria increase legwork.
Weak criteria let the agent stop after surface-level work.
### Post-completion steps
The steps visible after the current step.
Visible later steps can pull the agent forward too early.
Hide later steps only when a real context boundary exists.
## Failure modes
Use these findings during audit and verification.
Quote the offending passage when a finding applies.
### Premature completion
A step ends before its necessary work is complete.
This usually comes from a vague completion criterion.
Fix the local criterion before splitting the skill.
### Duplication
One meaning has more than one authoritative expression.
Duplication increases maintenance cost and false emphasis.
Replace duplicates with one source and pointers to it.
### Sediment
Old content remains after the skill's behavior changes.
Sediment makes the agent attend to stale instructions.
Remove lines that no longer affect the skill's current behavior.
### Sprawl
`SKILL.md` contains too much live material.
Sprawl hides the active procedure among supporting details.
Move reference down the information hierarchy.
### No-op
An instruction does not change the agent's default behavior.
No-op instructions spend attention without adding control.
Judge no-op instructions against behavior, not style.
Delete a no-op sentence instead of shortening it.
Cut no-op sentences unless they anchor a target-project convention.

View File

@@ -1,116 +0,0 @@
---
name: craft-skill
description: Draft or audit an Agent Skill for structural predictability. Run deliberately as /skill:craft-skill when creating or improving a skill.
disable-model-invocation: true
---
# craft-skill
Draft or audit an Agent Skill.
Judge the skill against one bar: **predictability**.
Predictability means the agent follows the same process on every run.
Read [`GLOSSARY.md`](GLOSSARY.md) before applying glossary terms.
Use this skill for skill structure, not general prose review.
Apply project writing rules when the target project defines them.
## Choose the branch
Use **Draft** when creating a new skill source.
Use **Audit** when reviewing an existing skill in its authoritative source.
Finish when one branch matches the user's requested change.
## Draft
1. Resolve the destination.
Read the target project's instructions and skill-source conventions.
Prefer an existing source directory over a new convention.
Trace symlinks and generated placements to their source.
Ask the user when multiple writable sources remain plausible.
Finish when the destination is writable and authoritative.
2. Create the skill structure.
Create a directory whose name matches the skill name.
Add `SKILL.md` with valid Agent Skills frontmatter.
Add `disable-model-invocation: true` only for Pi user-invoked skills.
Add sibling files only when they protect the **information hierarchy**.
Finish when the file layout matches the target harness and project.
3. Write the skill body.
Put active **steps** in `SKILL.md`.
Keep shared **reference** near the steps that need it.
Move large or branch-specific reference behind precise **context pointers**.
Front-load the **leading word** in descriptions and other context pointers.
Write pointer text for the condition that loads the target.
Give each step a checkable **completion criterion**.
Cut sentences that do not change agent behavior.
Use relative paths for all skill-local references.
Finish when each branch has ordered steps, resolved references, and checkable completion criteria.
## Audit
1. Locate the authoritative source.
Read the target project's instructions and skill-source conventions.
Inspect enabled-skill directories only to find the source.
Do not edit symlinks, generated files, installed packages, or vendored copies.
Ask the user when multiple sources claim the same skill.
Finish when you have identified the authoritative source.
2. Read the skill surface.
Read `SKILL.md` and every disclosed file.
Read project documents that the skill treats as authoritative.
Record which file owns each meaning before judging duplication.
Finish when all referenced behavior is visible.
3. Apply the checklist.
Quote each passage that fails a glossary check.
Check **invocation** against the intended harness.
Check **context pointers** for weak trigger wording.
Check **information hierarchy** for buried steps or disclosed required material.
Check **completion criteria** for vague or weak stopping points.
Check **leading words** for repeated explanations they can replace.
Check **pruning** for sentences that explain default model behavior.
Check **duplication**, **sediment**, **sprawl**, and **no-op** instructions.
Finish when every finding has quoted evidence or no finding remains.
4. Report or fix findings.
Report findings by default.
Fix findings only when the user requests edits.
Preserve behavior that passes the checklist.
Change only structural skill problems unless the user expands the scope.
Finish when you have reported each finding or fixed each requested finding.
## Verify
1. Run deterministic checks.
Verify required frontmatter exists.
Verify the name is portable and matches the directory.
Verify the description is specific and under 1024 characters.
Verify every skill-local reference resolves with a relative path.
Verify context pointers name when to load referenced material.
Verify disclosed files exist.
Verify each retained sentence changes behavior or records target-project policy.
Verify no stale harness-specific assumption remains.
Finish when each check passes or the final report names checks that could not run.
2. Re-read against the glossary.
Re-check **invocation**, **information hierarchy**, and **completion criteria**.
Re-check **duplication**, **sediment**, **sprawl**, and **no-op** instructions.
Fix any new structural finding.
Finish when no unresolved structural finding remains.
3. Report the result.
List every changed path.
State whether you enabled the skill or only authored it.
Finish when the user can review the exact files changed.

View File

@@ -1,88 +0,0 @@
---
name: grill
description: Stress-test a plan, decision, or design through a one-question-at-a-time interview. Use when the user asks to grill, stress-test, pressure-test, challenge, interrogate, or poke holes in a plan.
---
# grill
Interview the user until the session has no open or blocked questions.
Open questions define the ending condition for the grill session.
Blocked questions track known decisions with unsettled prerequisites.
Do not begin implementation during or after grill without an explicit user instruction.
A completed grill summary is not an instruction to build.
## Run the interview
1. Prepare the grill.
Read the conversation, files, and docs that can settle facts or reveal constraints.
Resolve factual questions yourself when tools can answer them.
Do not ask the user for facts you can find.
Build the required-question set from the known plan or idea.
Put ready questions under `Open questions:`.
Put known questions with unsettled prerequisites under `Blocked questions:`.
Finish when both sections contain every known required question.
2. Start the interview.
Show `Open questions:` and `Blocked questions:` in short form.
Include titles only, not full question bodies.
Use Markdown list items in both sections.
Mark each initial item with `- [ ]`.
Ask exactly one numbered question in the same turn.
The question title must match an item under `Open questions:`.
Finish when the interview has started with exactly one numbered question.
3. Process the answer.
Account for the user's answer before asking another question.
Resolve, update, remove, unblock, or add questions as the answer requires.
Use `- [ ]` for unchanged unresolved questions.
Use `- [+]` for questions added by the latest answer.
Use `- [u]` for questions updated by the latest answer.
Use `- [x]` for questions resolved by the latest answer.
Use `- [-]` for questions removed by the latest answer.
Include a cause note for each `- [+]`, `- [u]`, and `- [-]` change.
Indent cause notes by two spaces under the changed question.
Show `- [+]`, `- [u]`, `- [x]`, and `- [-]` for one turn only.
After that turn, keep an updated question visible as `- [ ]`.
After that turn, remove resolved and removed questions from the visible list.
Move unblocked questions from `Blocked questions:` to `Open questions:` with `- [u]`.
Do not use `- [+]` for unblocked questions because they are not new.
Add questions only when the latest answer directly causes them.
When the user extends scope instead of answering, account for the new question before pursuing it.
Do not add optional follow-up questions to either section.
Put optional follow-up questions in the final summary instead.
Resolve newly answerable facts yourself.
Finish when every list change has an explicit marker and required cause note.
4. Ask the next question.
Show `Open questions:` and `Blocked questions:` on every active grill turn.
Keep `- [ ]` items visible every turn.
Preserve agent judgment when the user reframes or invalidates a question.
Show the resulting list change instead of following a rigid reframe algorithm.
If the user catches incorrect accounting, briefly explain the error.
Then show the corrected question sections.
Ask exactly one numbered question when `Open questions:` contains an unresolved item.
The question title must match an item currently shown under `Open questions:`.
Give concrete options with trade-offs.
Label options with `A.`, `B.`, `C.`, and later letters.
Use the same labels in the recommendation.
Give a recommendation and rationale.
Probe vague words, overloaded terms, and hidden assumptions.
Use concrete scenarios to test concept boundaries and edge cases.
When code contradicts the user's claim, quote both the claim and the code behavior.
If the turn includes a correction, file edit, apology, or explanation, still end with the next numbered question.
Finish when the turn ends with the next numbered question.
5. Close or pause.
Close when `Open questions:` and `Blocked questions:` are empty.
Output a concise summary of every decision reached.
Include optional follow-up questions that were not added to either section.
Do not act on the summary unless the user gives a new implementation instruction.
If the user changes tasks, state that grill is paused.
End the turn with the final decision summary or the pause statement.
Finish when the summary is delivered or grill is explicitly paused.

View File

@@ -12,10 +12,7 @@ After editing Nix files, run:
```bash
nix run .#fix
bazel run //src/natu:natu -- <modified-nix-paths>
```
Pass every modified Nix path to Natu.
Finish when both commands succeed and the Nix change follows the loaded rules.
If a command fails, report the failure.
Finish when the command succeeds and the Nix change follows the loaded rules.
If the command fails, report the failure.

View File

@@ -1,62 +0,0 @@
# Document Format
## Template
```md
## Problem Statement
The problem that the user is facing, from the user's perspective.
## Solution
The solution to the problem, from the user's perspective.
## User Stories
An extensive, numbered list of user stories, covering all aspects of the feature. Each user story should be in the format of:
1. As an <actor>, I want a <feature>, so that <benefit>
<user-story-example>
1. As a mobile bank customer, I want to see balance on my accounts, so that I can make better informed decisions about my spending
</user-story-example>
## Implementation Decisions
A list of implementation decisions that were made. This can include:
- The modules that will be built/modified
- The interfaces of those modules that will be modified
- Technical clarifications from the developer
- Architectural decisions
- Schema changes
- API contracts
- Specific interactions
## Testing Decisions
A list of testing decisions that were made. Include:
- A description of what makes a good test (only test external behavior, not implementation details)
- Which modules will be tested
- Prior art for the tests, that is, similar tests in the codebase
## Out of Scope
A description of the things that are out of scope for this spec.
## Further Notes
Any further notes about the feature.
```
## Rules
- **Do not include specific file paths or code snippets.**
They can become outdated quickly.
Exception: include a prototype snippet when it records a decision more precisely than prose.
Examples include a state machine, reducer, schema, or type shape.
Inline the snippet in the relevant implementation decision.
Note briefly that the snippet came from a prototype.
Trim the snippet to the decision-rich parts.
Do not include a working demo.

View File

@@ -1,64 +0,0 @@
---
name: to-document
description: Draft a requested summary, specification, plan, decision record, or similar document from conversation and repository context.
---
Do not start with an interview when the conversation gives a usable subject.
Ask before drafting only when the conversation lacks a usable subject.
Do not put draft contents in the chat response.
Always persist the draft to a file.
Do not implement the draft contents unless the operator gives a separate instruction.
Treat a completed draft as documentation, not an instruction to build.
## Process
1. Identify the subject.
Use the conversation as the primary source.
If the conversation lacks a usable subject, ask what the document is about.
Do not ask clarifying questions before drafting when a usable subject exists.
Finish when you have a subject or a question that requests the missing subject.
2. Gather repository facts that the draft needs.
Inspect files when repository details matter.
Do not invent modules, paths, commands, flows, contracts, or conventions.
Distinguish confirmed facts from assumptions.
Finish when each repository-specific claim has support or an explicit assumption marker.
3. Choose the document shape.
Infer the document type and title from context.
Load [DOCUMENT-FORMAT.md](DOCUMENT-FORMAT.md) when the operator requests no specific format.
Adapt the structure only when the requested document type needs different sections.
Preserve useful sections for decisions, testing, scope, and notes.
Finish when the draft has a title and section plan that fit the requested document.
4. Write the draft.
Capture known context accurately.
Mark assumptions and gaps explicitly.
Include decisions that the conversation settled.
Include open questions only as gaps, not as an interview.
Keep the document focused on the operator's problem and intended use.
Finish when the draft contains the relevant facts, decisions, assumptions, gaps, and scope.
5. Persist the draft.
Use `docs/00 INBOX/ai` as the default destination.
Use the operator's requested path when one exists.
Derive a kebab-case slug from the inferred title.
Create the destination directory when it does not exist.
If the target file exists, summarize the expected change.
Confirm before overwriting an existing file.
Do not print the draft in chat instead of writing it.
Finish when the draft is written or overwrite confirmation is pending.
6. Finish with the result.
Report the written path.
Do not include the draft contents in the response.
Do not continue into implementation without an explicit instruction.
Finish when the operator can find the written draft.

7
third_party/BUILD vendored
View File

@@ -1,4 +1,4 @@
load("@rules_rust//crate_universe:defs.bzl", "crate", "crates_vendor")
load("@rules_rust//crate_universe:defs.bzl", "crates_vendor")
sh_binary(
name = "bazel_for_cargo_bazel",
@@ -10,11 +10,6 @@ crates_vendor(
bazel = ":bazel_for_cargo_bazel",
cargo_lockfile = "//:Cargo.lock",
manifests = ["//:Cargo.toml"],
packages = {
"rnix": crate.spec(
version = "=0.14.0",
),
},
mode = "local",
tags = ["manual"],
vendor_path = "crates",

View File

@@ -43,42 +43,6 @@ alias(
tags = ["manual"],
)
alias(
name = "googletest-0.14.3",
actual = "//third_party/crates/googletest-0.14.3:googletest",
tags = ["manual"],
)
alias(
name = "googletest",
actual = "//third_party/crates/googletest-0.14.3:googletest",
tags = ["manual"],
)
alias(
name = "rnix-0.14.0",
actual = "//third_party/crates/rnix-0.14.0:rnix",
tags = ["manual"],
)
alias(
name = "rnix",
actual = "//third_party/crates/rnix-0.14.0:rnix",
tags = ["manual"],
)
alias(
name = "rowan-0.16.1",
actual = "//third_party/crates/rowan-0.16.1:rowan",
tags = ["manual"],
)
alias(
name = "rowan",
actual = "//third_party/crates/rowan-0.16.1:rowan",
tags = ["manual"],
)
alias(
name = "serde-1.0.229",
actual = "//third_party/crates/serde-1.0.229:serde",

View File

@@ -1 +0,0 @@
{"$comment":"This file only protects against accidental modifications. It is not a security mechanism and does not protect against malicious changes.","files":{".cargo_vcs_info.json":"fa452b0920e10ae97397f4cb336b629f7cbe5de0bed8fd8046ce8c137c06e2a4",".github/FUNDING.yml":"0c65f392d32a8639ba7986bbb42ca124505b462122382f314c89d84c95dd27f1",".github/dependabot.yml":"ea498dc2f28b89e80cf42a1349ac48ba9a9cc4d53f6cb21333481a4611f95abb",".github/workflows/ci.yml":"2d9409bedd406551a2e7e62158f3826c54c38a15d35e2a1a660e47499ea1999e",".vim/coc-settings.json":"8237c8f41db352b0d83f1bb10a60bc2f60f56f3234afbf696b4075c8d4d62d9b","COPYING":"01c266bced4a434da0051174d6bee16a4c82cf634e2679b6155d40d75012390f","Cargo.lock":"9b5026fc4b42d1470b586a636f7c0e843ca9a056f4137727bf7ba36baaa9c9b0","Cargo.toml":"7ff243aed78547f286729c3c60d97577fbc685546120263548d7c4f2a3884bc1","Cargo.toml.orig":"6c8341535cb4f736c1ac6b18292df2c572ccb18740bb9325e42b22c67f9e27da","DESIGN.md":"59c960e1b73b1d7fb41e4df6c0c1b1fcf44dd2ebc8a349597a7d0595f8cb5130","LICENSE-MIT":"0f96a83840e146e43c0ec96a22ec1f392e0680e6c1226e6f3ba87e0740af850f","README.md":"afc4d559a98cf190029af0bf320fc0022725e349cd2a303aac860254e28f3c53","UNLICENSE":"7e12e5df4bae12cb21581ba157ced20e1986a0508dd10d0e8a4ab9a4cf94e85c","rustfmt.toml":"1ca600239a27401c4a43f363cf3f38183a212affc1f31bff3ae93234bbaec228","src/ahocorasick.rs":"c699c07df70be45c666e128509ad571a7649d2073e4ae16ac1efd6793c9c6890","src/automaton.rs":"22258a3e118672413119f8f543a9b912cce954e63524575c0ebfdf9011f9c2dd","src/dfa.rs":"197075923eb9d760a552f4e8652310fd4f657736613a9b1444ae05ef5d525da3","src/lib.rs":"66dea84d227f269b2f14ecc8109a97e96245b56c22eef0e8ce03b2343b8d6e66","src/macros.rs":"c6c52ae05b24433cffaca7b78b3645d797862c5d5feffddf9f54909095ed6e05","src/nfa/contiguous.rs":"f435c131ce84927e5600109722d006533ea21442dddaf18e03286d8caed82389","src/nfa/mod.rs":"ee7b3109774d14bbad5239c16bb980dd6b8185ec136d94fbaf2f0dc27d5ffa15","src/nfa/noncontiguous.rs":"de94f02b04efd8744fb096759a8897c22012b0e0ca3ace161fd87c71befefe04","src/packed/api.rs":"d555a8c7a6da33b75f1f90e21ee970629f92f7bddd4b408b78656cd93fe1a3d6","src/packed/ext.rs":"66be06fde8558429da23a290584d4b9fae665bf64c2578db4fe5f5f3ee864869","src/packed/mod.rs":"0020cd6f07ba5c8955923a9516d7f758864260eda53a6b6f629131c45ddeec62","src/packed/pattern.rs":"0e4bca57d4b941495d31fc8246ad32904eed0cd89e3cda732ad35f4deeba3bef","src/packed/rabinkarp.rs":"403146eb1d838a84601d171393542340513cd1ee7ff750f2372161dd47746586","src/packed/teddy/README.md":"3a43194b64e221543d885176aba3beb1224a927385a20eca842daf6b0ea2f342","src/packed/teddy/builder.rs":"08ec116a4a842a2bb1221d296a2515ef3672c54906bed588fb733364c07855d3","src/packed/teddy/generic.rs":"ea252ab05b32cea7dd9d71e332071d243db7dd0362e049252a27e5881ba2bf39","src/packed/teddy/mod.rs":"17d741f7e2fb9dbac5ba7d1bd4542cf1e35e9f146ace728e23fe6bbed20028b2","src/packed/tests.rs":"8e2f56eb3890ed3876ecb47d3121996e416563127b6430110d7b516df3f83b4b","src/packed/vector.rs":"70c325cfa6f7c5c4c9a6af7b133b75a29e65990a7fe0b9a4c4ce3c3d5a0fe587","src/tests.rs":"c68192ab97b6161d0d6ee96fefd80cc7d14e4486ddcd8d1f82b5c92432c24ed5","src/transducer.rs":"02daa33a5d6dac41dcfd67f51df7c0d4a91c5131c781fb54c4de3520c585a6e1","src/util/alphabet.rs":"6dc22658a38deddc0279892035b18870d4585069e35ba7c7e649a24509acfbcc","src/util/buffer.rs":"f9e37f662c46c6ecd734458dedbe76c3bb0e84a93b6b0117c0d4ad3042413891","src/util/byte_frequencies.rs":"2fb85b381c038c1e44ce94294531cdcd339dca48b1e61f41455666e802cbbc9e","src/util/debug.rs":"ab301ad59aa912529cb97233a54a05914dd3cb2ec43e6fec7334170b97ac5998","src/util/error.rs":"ecccd60e7406305023efcc6adcc826eeeb083ab8f7fbfe3d97469438cd4c4e5c","src/util/int.rs":"e264e6abebf5622b59f6500210773db36048371c4e509c930263334095959a52","src/util/mod.rs":"7ab28d11323ecdbd982087f32eb8bceeee84f1a2583f3aae27039c36d58cf12c","src/util/prefilter.rs":"183e32aa9951d9957f89062e4a6ae7235df7060722a3c91995a3d36db5a98111","src/util/primitives.rs":"f89f3fa1d8db4e37de9ca767c6d05e346404837cade6d063bba68972fafa610b","src/util/remapper.rs":"9f12d911583a325c11806eeceb46d0dfec863cfcfa241aed84d31af73da746e5","src/util/search.rs":"ac16607e69a3ff24d27c0680dc9afcd5bb7b7cb272179d5475300a2035fdf7e3","src/util/special.rs":"7d2f9cb9dd9771f59816e829b2d96b1239996f32939ba98764e121696c52b146"},"package":"c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"}

View File

@@ -1,6 +0,0 @@
{
"git": {
"sha1": "5178060ce73d91938f8582d0360e3be031380440"
},
"path_in_vcs": ""
}

Some files were not shown because too many files have changed in this diff Show More