Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(nixos): introduce NixOS module for ai-memory service
Test4f197075bb03
diff --git a/.github/workflows/nix.yml b/.github/workflows/nix.ymlindex b6203fc0..14111c73 100644--- a/.github/workflows/nix.yml+++ b/.github/workflows/nix.yml@@ -1,6 +1,10 @@name: nix-# Builds the flake so the Nix packaging cannot rot unnoticed.+# Builds the flake on Linux and macOS so the Nix packaging cannot rot unnoticed.+#+# Matrix: x86_64-linux (package + NixOS module eval) and aarch64-darwin+# (package + artifact smoke only). NixOS checks always evaluate x86_64-linux+# and stay on the Linux leg — Darwin attrs would add noise without signal.## ai-memory does not otherwise test on Nix, so without this job `flake.nix`# is source nobody executes: it can break through a dependency bump, a@@ -17,16 +21,20 @@ on:branches: [main]paths:- 'flake.nix'+ - 'nix/**'- 'Cargo.lock'- 'Cargo.toml'- 'rust-toolchain.toml'+ - 'scripts/check-nix-packaging.sh'- '.github/workflows/nix.yml'pull_request:paths:- 'flake.nix'+ - 'nix/**'- 'Cargo.lock'- 'Cargo.toml'- 'rust-toolchain.toml'+ - 'scripts/check-nix-packaging.sh'- '.github/workflows/nix.yml'schedule:# Mondays 05:17 UTC. Off the hour so it does not pile onto the@@ -39,8 +47,16 @@ permissions:jobs:build:- name: nix build- runs-on: ubuntu-latest+ name: nix build (${{ matrix.system }})+ strategy:+ fail-fast: false+ matrix:+ include:+ - system: x86_64-linux+ runner: ubuntu-latest+ - system: aarch64-darwin+ runner: macos-latest+ runs-on: ${{ matrix.runner }}steps:- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1- uses: cachix/install-nix-action@13d8dd58da0234aa297dedd986986ccb8e7f3e24 # v31.11.1@@ -49,7 +65,14 @@ jobs:experimental-features = nix-command flakes# `nix flake check` would also evaluate every output; the build is the# claim worth verifying, and it is the expensive half anyway.- - run: nix build --print-build-logs- # The binary is what the flake promises. Run it, so a package that- # builds but cannot execute still fails.- - run: ./result/bin/ai-memory --version+ - run: nix build --print-build-logs '.#packages.${{ matrix.system }}.default'+ - run: scripts/check-nix-packaging.sh ./result+ # Eval-only smoke tests for the NixOS module (nixosModules.default):+ # proves the option wiring evaluates cleanly for both enable = true+ # and enable = false on a real Linux system, without building a full+ # NixOS system closure. See nix/nixos-module.nix and the assertions+ # in flake.nix's checks.x86_64-linux.+ - if: matrix.system == 'x86_64-linux'+ run: nix build --print-build-logs '.#checks.x86_64-linux.nixos-module-eval'+ - if: matrix.system == 'x86_64-linux'+ run: nix build --print-build-logs '.#checks.x86_64-linux.nixos-sandbox-parity'diff --git a/AGENTS.md b/AGENTS.mdindex 40121e96..23c96792 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -310,7 +310,10 @@ no tiers."$HOME\.rustup"`.- Shell-level checks: `tests/hooks/test_lib.sh`,- `tests/e2e/handoff_smoke.sh`, `scripts/check-native-packaging.sh`.+ `tests/e2e/handoff_smoke.sh`, `scripts/check-native-packaging.sh`,+ `scripts/check-nix-packaging.sh` (Nix flake output).+- `.github/workflows/nix.yml` matrix covers `x86_64-linux` + `aarch64-darwin`;+ NixOS module eval is Linux-only.- CI additionally runs `cargo build --release --bin ai-memory` onLinux/macOS, a Docker image smoke test, `cargo audit` (with the ignoreslisted in `ci.yml`), and differential gitleaks scanning.diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3a3b3aba..88eab5e3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Changed+- `.github/workflows/nix.yml` now builds the flake on `x86_64-linux` and+ `aarch64-darwin` with `scripts/check-nix-packaging.sh` artifact smoke tests+ (binary, hooks, config template, `nix run`); NixOS module eval stays on the+ Linux leg only. (#NNN)++### Added+- A NixOS module (`nix/nixos-module.nix`, exposed as `nixosModules.default`)+ so NixOS hosts can run `services.ai-memory.enable = true` as a hardened+ systemd service — dedicated `ai-memory` system user (`nologin`, gated by+ `createUser`) plus a shared systemd sandbox applied to both NixOS and the+ packaged FHS units (`nix/systemd-sandbox.nix`). Typed+ `services.ai-memory.settings` renders declarative `config.toml`; secrets use+ `ageSecret`, `sopsSecret`, or `environmentFile` (required for non-loopback+ binds). The web UI defaults off (`enableWeb = false`, matching the CLI+ flag's own default rather than the packaged unit's hardcoded+ `--enable-web`). `flake.nix` adds eval checks for sandbox keys, settings →+ `--config`, and agenix/sops wiring. The existing `flake.nix`+ package/devShell/CLI build is unchanged. (#NNN)+### Fixed- Grok Build CLI tool observations are no longer stored with an empty body.Grok posts Claude Code's snake_case tool fields (`tool_name` / `tool_input` /diff --git a/README.md b/README.mdindex 7805a6bd..0df9df64 100644--- a/README.md+++ b/README.md@@ -349,6 +349,60 @@ Auto-wiring is on by default; opt out with `ai-memory run --no-autowire` orand only what it installed. Install commands are idempotent and writetimestamped backups next to any file they touch.+### NixOS++This flake ships a NixOS module (`nixosModules.default`) with a+`systemd.services.ai-memory` unit. Isolation matches the packaged FHS unit:+a dedicated `ai-memory` system user (`nologin`, no linger) plus the same+systemd sandbox (`ProtectSystem = "strict"`, empty capability sets,+`MemoryDenyWriteExecute`, `RestrictAddressFamilies`, and the rest — see+[`nix/systemd-sandbox.nix`](nix/systemd-sandbox.nix)).++```nix+{+ inputs.ai-memory.url = "github:akitaonrails/ai-memory";++ outputs = { nixpkgs, ai-memory, ... }: {+ nixosConfigurations.myhost = nixpkgs.lib.nixosSystem {+ system = "x86_64-linux";+ modules = [+ ai-memory.nixosModules.default+ {+ services.ai-memory = {+ enable = true;+ # enableWeb = true; # off by default — the web UI is opt-in+ settings = {+ allowed_hosts = [ "localhost" "127.0.0.1" "::1" "homelab.example" ];+ log_level = "info";+ };+ # Loopback (default): secrets optional; missing env file is tolerated.+ # Non-loopback: set one of ageSecret, sopsSecret, or environmentFile.+ # ageSecret = "ai-memory-env"; # config.age.secrets.<name> (agenix)+ # sopsSecret = "ai-memory/env"; # config.sops.secrets.<name> (sops-nix)+ };+ }+ ];+ };+ };+}+```++Declarative non-secret config lives in `services.ai-memory.settings` (typed+options mirroring `config.toml`, plus `freeformType` for forward-compat keys).+The module renders a generated TOML file and passes `--config`. Top-level+`bind`, `port`, and `enableWeb` win over duplicate settings keys.++Secrets such as `AI_MEMORY_AUTH_TOKEN` never go in `settings` or the Nix+store. Use `ageSecret` / `sopsSecret` (consume `config.age` / `config.sops`+when the host imports agenix or sops-nix) or `environmentFile` as an escape+hatch. Non-loopback binds require one of those sources; loopback may omit+them and tolerates a missing env file (systemd `EnvironmentFile=-…`). Put TLS+in front of a LAN/WAN bind — see [`docs/https-via-proxy.md`](docs/https-via-proxy.md).++All options and defaults are in [`nix/nixos-module.nix`](nix/nixos-module.nix).+Entirely opt-in — `nix build`, `nix run`, `nix develop`, and the CLI are+unchanged if you don't import it.+## Everyday useDay to day, you mostly do not think about ai-memory. Hooks capturediff --git a/flake.lock b/flake.locknew file mode 100644index 00000000..1052b1b6--- /dev/null+++ b/flake.lock@@ -0,0 +1,84 @@+{+ "nodes": {+ "flake-utils": {+ "inputs": {+ "systems": "systems"+ },+ "locked": {+ "lastModified": 1731533236,+ "narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=",+ "owner": "numtide",+ "repo": "flake-utils",+ "rev": "11707dc2f618dd54ca8739b309ec4fc024de578b",+ "type": "github"+ },+ "original": {+ "owner": "numtide",+ "repo": "flake-utils",+ "rev": "11707dc2f618dd54ca8739b309ec4fc024de578b",+ "type": "github"+ }+ },+ "nixpkgs": {+ "locked": {+ "lastModified": 1787070829,+ "narHash": "sha256-vXNVDVtvfiQuXthP0NHPFdNvvMTkGpx0UP8oddIWbNk=",+ "owner": "NixOS",+ "repo": "nixpkgs",+ "rev": "0ae2bc1419c3f345984c2629e72e7a631820fa4d",+ "type": "github"+ },+ "original": {+ "owner": "NixOS",+ "repo": "nixpkgs",+ "rev": "0ae2bc1419c3f345984c2629e72e7a631820fa4d",+ "type": "github"+ }+ },+ "root": {+ "inputs": {+ "flake-utils": "flake-utils",+ "nixpkgs": "nixpkgs",+ "rust-overlay": "rust-overlay"+ }+ },+ "rust-overlay": {+ "inputs": {+ "nixpkgs": [+ "nixpkgs"+ ]+ },+ "locked": {+ "lastModified": 1787108576,+ "narHash": "sha256-WLhxXPMCzbeufsDZxdzkurLGBq74GX+JgLX8fFy6HZs=",+ "owner": "oxalica",+ "repo": "rust-overlay",+ "rev": "99607a06c2ea1290cd3258c11d1416dde9201f94",+ "type": "github"+ },+ "original": {+ "owner": "oxalica",+ "repo": "rust-overlay",+ "rev": "99607a06c2ea1290cd3258c11d1416dde9201f94",+ "type": "github"+ }+ },+ "systems": {+ "locked": {+ "lastModified": 1681028828,+ "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",+ "owner": "nix-systems",+ "repo": "default",+ "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",+ "type": "github"+ },+ "original": {+ "owner": "nix-systems",+ "repo": "default",+ "type": "github"+ }+ }+ },+ "root": "root",+ "version": 7+}diff --git a/flake.nix b/flake.nixindex aea314fe..bb3aeb60 100644--- a/flake.nix+++ b/flake.nix@@ -44,18 +44,147 @@outputs ={+ self,nixpkgs,flake-utils,rust-overlay,...}:- flake-utils.lib.eachDefaultSystem (+ let+ linuxPkgs = import nixpkgs {+ system = "x86_64-linux";+ overlays = [ (import rust-overlay) ];+ };+ inherit (linuxPkgs) lib;++ sandboxModule = import ./nix/systemd-sandbox.nix { inherit lib; };++ # Eval-only NixOS module smoke tests. Kept at the top level under+ # checks.x86_64-linux only — the eval always targets x86_64-linux, so+ # duplicating these under eachDefaultSystem would add noise on Darwin.+ ageSopsStub =+ { lib, ... }:+ {+ options.age.secrets = lib.mkOption {+ type = lib.types.attrsOf (lib.types.submodule {+ options.path = lib.mkOption { type = lib.types.path; };+ });+ default = { };+ };+ options.sops.secrets = lib.mkOption {+ type = lib.types.attrsOf (lib.types.submodule {+ options.path = lib.mkOption { type = lib.types.path; };+ });+ default = { };+ };+ config.age.secrets.ai-memory-env.path = "/run/agenix/ai-memory-env";+ config.sops.secrets."ai-memory/env".path = "/run/secrets/ai-memory/env";+ };++ mkNixos = extra: nixpkgs.lib.nixosSystem {+ system = "x86_64-linux";+ modules = [+ self.nixosModules.default+ ageSopsStub+ extra+ ];+ };++ # enableWeb defaults to false, so the enabled-smoke config sets+ # it explicitly to true — this exercises the --enable-web+ # wiring, it isn't asserting what the default is.+ enabled = mkNixos { services.ai-memory = { enable = true; enableWeb = true; }; };+ disabled = mkNixos { services.ai-memory.enable = false; };+ withSettings = mkNixos {+ services.ai-memory = {+ enable = true;+ settings.allowed_hosts = [+ "localhost"+ "127.0.0.1"+ "::1"+ ];+ settings.log_level = "info";+ };+ };+ withAge = mkNixos {+ services.ai-memory = {+ enable = true;+ bind = "0.0.0.0";+ ageSecret = "ai-memory-env";+ };+ };+ withSops = mkNixos {+ services.ai-memory = {+ enable = true;+ bind = "0.0.0.0";+ sopsSecret = "ai-memory/env";+ };+ };+ loopbackEnvFile = mkNixos {+ services.ai-memory = {+ enable = true;+ environmentFile = "/run/ai-memory/env";+ };+ };+ nonLoopbackNoSecrets = mkNixos {+ services.ai-memory = {+ enable = true;+ bind = "0.0.0.0";+ };+ };+ failingAssertions =+ lib.filter (a: !a.assertion) nonLoopbackNoSecrets.config.assertions;++ enabledSc = enabled.config.systemd.services.ai-memory.serviceConfig;+ execStart = enabledSc.ExecStart;+ settingsExec =+ withSettings.config.systemd.services.ai-memory.serviceConfig.ExecStart;++ nixosChecks = {+ nixos-module-eval =+ assert lib.hasInfix "--enable-web" execStart;+ assert lib.hasInfix "--bind 127.0.0.1:49374" execStart;+ assert !(disabled.config.systemd.services ? ai-memory);+ assert enabledSc.MemoryDenyWriteExecute == true;+ assert enabledSc.RestrictNamespaces == true;+ assert enabledSc.UMask == "0077";+ assert enabledSc.CapabilityBoundingSet == [ ];+ assert enabledSc.NoNewPrivileges == true;+ assert enabledSc.PrivateTmp == true;+ assert enabledSc.ProtectHome == true;+ assert enabledSc.ProtectSystem == "strict";+ assert lib.hasInfix "--config" settingsExec;+ assert withAge.config.systemd.services.ai-memory.serviceConfig.EnvironmentFile+ == "/run/agenix/ai-memory-env";+ assert withSops.config.systemd.services.ai-memory.serviceConfig.EnvironmentFile+ == "/run/secrets/ai-memory/env";+ assert loopbackEnvFile.config.systemd.services.ai-memory.serviceConfig.EnvironmentFile+ == "-/run/ai-memory/env";+ assert failingAssertions != [ ];+ assert lib.any (a: lib.hasInfix "non-loopback bind requires" a.message)+ failingAssertions;+ linuxPkgs.runCommand "ai-memory-nixos-module-eval" { } "touch $out";++ nixos-sandbox-parity =+ let+ sandboxKeys = lib.attrNames sandboxModule.aiMemorySystemSandbox;+ enabledSandboxKeys = lib.attrNames (+ lib.filterAttrs (name: _: lib.elem name sandboxKeys) enabledSc+ );+ in+ assert lib.sort lib.lessThanStr sandboxKeys+ == lib.sort lib.lessThanStr enabledSandboxKeys;+ linuxPkgs.runCommand "ai-memory-nixos-sandbox-parity" { } "touch $out";+ };+ in+ (flake-utils.lib.eachDefaultSystem (system:letpkgs = import nixpkgs {inherit system;overlays = [ (import rust-overlay) ];};+ inherit (pkgs) lib;# Read the same toolchain file the project pins for every other CI# path — rust-toolchain.toml says `channel = "1.95"`.@@ -142,5 +271,19 @@'';};}- );+ ))+ // {+ # Additive: a NixOS host can run `services.ai-memory.enable = true` to+ # get this binary as a hardened systemd service (see+ # nix/nixos-module.nix). Merged at the top level, not inside+ # eachDefaultSystem, because NixOS modules are not system-scoped.+ nixosModules.default =+ { pkgs, lib, ... }:+ {+ imports = [ ./nix/nixos-module.nix ];+ config.services.ai-memory.package = lib.mkDefault self.packages.${pkgs.system}.default;+ };++ checks.x86_64-linux = nixosChecks;+ };}diff --git a/nix/nixos-module.nix b/nix/nixos-module.nixnew file mode 100644index 00000000..2b711208--- /dev/null+++ b/nix/nixos-module.nix@@ -0,0 +1,317 @@+# NixOS module for the ai-memory MCP server.+#+# Standalone: no reference to `self` or anything flake-specific, so it stays+# importable outside this flake. `flake.nix`'s `nixosModules.default` wraps+# this file and supplies a default for `package` by closing over `self`.+{ config, lib, pkgs, ... }:++let+ cfg = config.services.ai-memory;+ sandbox = import ./systemd-sandbox.nix { inherit lib; };++ defaultDataDir = "/var/lib/ai-memory";+ usesDefaultDataDir = cfg.dataDir == defaultDataDir;++ isLoopback =+ cfg.bind == "127.0.0.1" || cfg.bind == "::1" || cfg.bind == "localhost";++ tomlFormat = pkgs.formats.toml { };++ # Strip null leaves so optional typed settings omit keys from generated TOML.+ pruneNulls =+ value:+ if value == null then+ null+ else if builtins.isAttrs value then+ lib.filterAttrs (_: v: v != null) (lib.mapAttrs (_: v: pruneNulls v) value)+ else+ value;++ settingsToml =+ let+ # Service-level bind/port/enableWeb win over duplicate settings keys.+ stripped = lib.filterAttrs (name: _: name != "bind") (pruneNulls cfg.settings);+ in+ if stripped == { } then+ null+ else+ tomlFormat.generate "ai-memory-config.toml" stripped;++ ageSecretPath =+ if cfg.ageSecret == null then+ null+ else+ config.age.secrets.${cfg.ageSecret}.path;++ sopsSecretPath =+ if cfg.sopsSecret == null then+ null+ else+ config.sops.secrets.${cfg.sopsSecret}.path;++ secretsFile =+ if cfg.ageSecret != null then+ ageSecretPath+ else if cfg.sopsSecret != null then+ sopsSecretPath+ else+ cfg.environmentFile;++ secretKeysInSettings =+ let+ auth = cfg.settings.auth or { };+ in+ lib.filter (k: (auth.${k} or null) != null) [+ "bearer_token"+ "token_pepper"+ "initial_root_password"+ "recovery_token"+ "actor_proxy_bearer_token"+ ];++ execStartArgs =+ [+ (lib.getExe cfg.package)+ "--data-dir"+ cfg.dataDir+ ]+ ++ lib.optionals (settingsToml != null) [+ "--config"+ "${settingsToml}"+ ]+ ++ [+ "serve"+ "--transport"+ "http"+ "--bind"+ "${cfg.bind}:${toString cfg.port}"+ ]+ ++ lib.optionals cfg.enableWeb [ "--enable-web" ];+in+{+ options.services.ai-memory = {+ enable = lib.mkEnableOption "the ai-memory MCP server as a systemd service";++ package = lib.mkOption {+ type = lib.types.package;+ description = ''+ The ai-memory package to run. No default here, so this module stays+ usable standalone. This repo's `flake.nix` supplies a default via+ `nixosModules.default`, which sets+ `services.ai-memory.package = lib.mkDefault self.packages.${pkgs.system}.default`.+ A consumer importing this file directly (bypassing that wrapper)+ must set this option themselves.+ '';+ };++ dataDir = lib.mkOption {+ type = lib.types.path;+ default = defaultDataDir;+ description = "Data directory passed as --data-dir (wiki, SQLite, config.toml).";+ };++ bind = lib.mkOption {+ type = lib.types.str;+ default = "127.0.0.1";+ description = "Host ai-memory's HTTP transport binds to.";+ };++ port = lib.mkOption {+ type = lib.types.port;+ default = 49374;+ description = "Port ai-memory's HTTP transport binds to.";+ };++ enableWeb = lib.mkOption {+ type = lib.types.bool;+ default = false;+ description = ''+ Pass --enable-web (mounts the built-in web UI at /web). Off by+ default, matching the underlying --enable-web CLI flag's own+ default — NOT the packaged FHS systemd unit, which hardcodes it on.+ '';+ };++ settings = lib.mkOption {+ type = lib.types.submodule {+ freeformType = tomlFormat.type;+ options = import ./settings-options.nix { inherit lib; };+ };+ default = { };+ description = ''+ Declarative config.toml fragment (non-secret keys only). Rendered to a+ generated file and passed as `--config`. Top-level `bind`, `port`, and+ `enableWeb` service options win over duplicate keys here.+ '';+ };++ ageSecret = lib.mkOption {+ type = lib.types.nullOr lib.types.str;+ default = null;+ example = "ai-memory-env";+ description = ''+ Name of a `config.age.secrets.<name>` entry (agenix). Mutually+ exclusive with `sopsSecret`. The host must import agenix; this module+ only consumes the decrypted path.+ '';+ };++ sopsSecret = lib.mkOption {+ type = lib.types.nullOr lib.types.str;+ default = null;+ example = "ai-memory/env";+ description = ''+ Name of a `config.sops.secrets.<name>` entry (sops-nix). Mutually+ exclusive with `ageSecret`. The host must import sops-nix; this module+ only consumes the decrypted path.+ '';+ };++ environmentFile = lib.mkOption {+ type = lib.types.nullOr lib.types.path;+ default = null;+ description = ''+ Escape hatch: explicit systemd EnvironmentFile path for secrets such as+ `AI_MEMORY_AUTH_TOKEN` (required once `bind` is non-loopback). On+ loopback, a missing file does not fail service start (leading `-`).+ On non-loopback the file must exist. Prefer `ageSecret` or+ `sopsSecret` when using agenix or sops-nix.+ '';+ };++ user = lib.mkOption {+ type = lib.types.str;+ default = "ai-memory";+ description = "System user the service runs as.";+ };++ group = lib.mkOption {+ type = lib.types.str;+ default = "ai-memory";+ description = "System group the service runs as.";+ };++ createUser = lib.mkOption {+ type = lib.types.bool;+ default = true;+ description = ''+ Create the dedicated system user and group. Defaults to true when+ `user` is `ai-memory`; set false when `user` names an existing+ account you manage elsewhere.+ '';+ };++ openFirewall = lib.mkOption {+ type = lib.types.bool;+ default = false;+ description = "Open the service `port` in the firewall when true.";+ };++ memoryMax = lib.mkOption {+ type = lib.types.nullOr lib.types.str;+ default = null;+ example = "2G";+ description = "Optional systemd MemoryMax for the service.";+ };++ tasksMax = lib.mkOption {+ type = lib.types.nullOr lib.types.int;+ default = null;+ description = "Optional systemd TasksMax for the service.";+ };+ };++ config = lib.mkIf cfg.enable (+ lib.mkMerge [+ {+ assertions = [+ {+ assertion = (cfg.ageSecret == null || cfg.sopsSecret == null);+ message = "services.ai-memory: ageSecret and sopsSecret are mutually exclusive";+ }+ {+ assertion = isLoopback || secretsFile != null;+ message =+ "services.ai-memory: non-loopback bind requires ageSecret, sopsSecret, or environmentFile (for AI_MEMORY_AUTH_TOKEN and related secrets)";+ }+ {+ assertion = secretKeysInSettings == [ ];+ message =+ "services.ai-memory.settings.auth must not contain secrets (${lib.concatStringsSep ", " secretKeysInSettings}); use ageSecret/sopsSecret/environmentFile";+ }+ {+ assertion = (cfg.settings.bind or null) == null;+ message = "services.ai-memory.settings.bind is not allowed; use the top-level bind/port options";+ }+ ];++ services.ai-memory.createUser = lib.mkDefault (cfg.user == "ai-memory");++ environment.systemPackages = [ cfg.package ];++ networking.firewall.allowedTCPPorts = lib.optionals cfg.openFirewall [ cfg.port ];+ }++ (lib.mkIf cfg.createUser {+ users.users.${cfg.user} = {+ isSystemUser = true;+ group = cfg.group;+ description = "ai-memory MCP server";+ home = cfg.dataDir;+ createHome = false;+ shell = "${pkgs.util-linuxMinimal}/bin/nologin";+ };+ users.groups.${cfg.group} = { };+ })++ (lib.mkIf (!usesDefaultDataDir && cfg.createUser) {+ systemd.tmpfiles.rules = [+ "d ${cfg.dataDir} 0750 ${cfg.user} ${cfg.group} -"+ ];+ })++ {+ systemd.services.ai-memory = {+ description = "ai-memory MCP server";+ documentation = [ "https://github.com/akitaonrails/ai-memory" ];+ after = if isLoopback then [ "network.target" ] else [ "network-online.target" ];+ wants = lib.optionals (!isLoopback) [ "network-online.target" ];+ wantedBy = [ "multi-user.target" ];++ serviceConfig = lib.mkMerge [+ {+ Type = "simple";+ User = cfg.user;+ Group = cfg.group;+ ExecStart = lib.concatStringsSep " " execStartArgs;+ Restart = "on-failure";+ RestartSec = "5s";+ TimeoutStopSec = "30s";+ StartLimitBurst = 5;+ StartLimitIntervalSec = "60s";+ ReadWritePaths = [ cfg.dataDir ];+ }+ (lib.optionalAttrs usesDefaultDataDir {+ StateDirectory = "ai-memory";+ StateDirectoryMode = "0750";+ })+ sandbox.aiMemorySystemSandbox+ (if secretsFile != null then+ if isLoopback then+ { EnvironmentFile = "-${secretsFile}"; }+ else+ { EnvironmentFile = "${secretsFile}"; }+ else+ { })+ (lib.optionalAttrs (cfg.memoryMax != null) {+ MemoryMax = cfg.memoryMax;+ })+ (lib.optionalAttrs (cfg.tasksMax != null) {+ TasksMax = cfg.tasksMax;+ })+ ];+ };+ }+ ]+ );+}diff --git a/nix/settings-options.nix b/nix/settings-options.nixnew file mode 100644index 00000000..69f9c2bc--- /dev/null+++ b/nix/settings-options.nix@@ -0,0 +1,330 @@+# Typed `services.ai-memory.settings` options mirroring config.toml.+# Secrets belong in age/sops/environmentFile, not here.+{ lib, ... }:++let+ inherit (lib) types;+in+{+ allowed_hosts = lib.mkOption {+ type = types.nullOr (types.listOf types.str);+ default = null;+ description = "Host-header allowlist (DNS-rebinding defence).";+ };++ log_level = lib.mkOption {+ type = types.nullOr types.str;+ default = null;+ };++ tcp_keepalive_secs = lib.mkOption {+ type = types.nullOr types.int;+ default = null;+ };++ server_url = lib.mkOption {+ type = types.nullOr types.str;+ default = null;+ };++ base_path = lib.mkOption {+ type = types.nullOr types.str;+ default = null;+ };++ hook_rate_per_sec = lib.mkOption {+ type = types.nullOr types.float;+ default = null;+ };++ hook_rate_burst = lib.mkOption {+ type = types.nullOr types.float;+ default = null;+ };++ capture_assistant = lib.mkOption {+ type = types.nullOr types.bool;+ default = null;+ };++ consolidate_on_session_end = lib.mkOption {+ type = types.nullOr types.bool;+ default = null;+ };++ backfill_on_start = lib.mkOption {+ type = types.nullOr types.bool;+ default = null;+ };++ run_autowire = lib.mkOption {+ type = types.nullOr types.bool;+ default = null;+ };++ strip_root_combinators = lib.mkOption {+ type = types.nullOr types.bool;+ default = null;+ };++ gemini_safe_schemas = lib.mkOption {+ type = types.nullOr types.bool;+ default = null;+ };++ reranker = lib.mkOption {+ type = types.nullOr types.str;+ default = null;+ };++ llm_provider = lib.mkOption {+ type = types.nullOr types.str;+ default = null;+ };++ llm_model = lib.mkOption {+ type = types.nullOr types.str;+ default = null;+ };++ llm_base_url = lib.mkOption {+ type = types.nullOr types.str;+ default = null;+ };++ llm_compat_strict = lib.mkOption {+ type = types.nullOr types.bool;+ default = null;+ };++ llm_timeout_secs = lib.mkOption {+ type = types.nullOr types.int;+ default = null;+ };++ llm_reasoning_effort = lib.mkOption {+ type = types.nullOr types.str;+ default = null;+ };++ llm_headers = lib.mkOption {+ type = types.nullOr (types.listOf types.str);+ default = null;+ };++ embedding_provider = lib.mkOption {+ type = types.nullOr types.str;+ default = null;+ };++ embedding_model = lib.mkOption {+ type = types.nullOr types.str;+ default = null;+ };++ embedding_dim = lib.mkOption {+ type = types.nullOr types.int;+ default = null;+ };++ embedding_base_url = lib.mkOption {+ type = types.nullOr types.str;+ default = null;+ };++ cors_allow_origins = lib.mkOption {+ type = types.nullOr (types.listOf types.str);+ default = null;+ };++ decay = lib.mkOption {+ type = types.nullOr (types.submodule {+ options = {+ lambda = lib.mkOption { type = types.nullOr types.float; default = null; };+ sigma = lib.mkOption { type = types.nullOr types.float; default = null; };+ mu = lib.mkOption { type = types.nullOr types.float; default = null; };+ salience_default = lib.mkOption { type = types.nullOr types.float; default = null; };+ cold_threshold = lib.mkOption { type = types.nullOr types.float; default = null; };+ hard_delete_after_days = lib.mkOption { type = types.nullOr types.int; default = null; };+ breadth_weight = lib.mkOption { type = types.nullOr types.float; default = null; };+ observation_retention_days = lib.mkOption { type = types.nullOr types.int; default = null; };+ observation_prune_batch = lib.mkOption { type = types.nullOr types.int; default = null; };+ compact_cold_episodic = lib.mkOption { type = types.nullOr types.bool; default = null; };+ dedup_cold_clusters = lib.mkOption { type = types.nullOr types.bool; default = null; };+ dedup_min_pts = lib.mkOption { type = types.nullOr types.int; default = null; };+ dedup_max_eps = lib.mkOption { type = types.nullOr types.float; default = null; };+ half_life_days = lib.mkOption {+ type = types.nullOr (types.submodule {+ options = {+ working = lib.mkOption { type = types.nullOr types.float; default = null; };+ episodic = lib.mkOption { type = types.nullOr types.float; default = null; };+ semantic = lib.mkOption { type = types.nullOr types.float; default = null; };+ procedural = lib.mkOption { type = types.nullOr types.float; default = null; };+ };+ });+ default = null;+ };+ };+ });+ default = null;+ };++ sanitize = lib.mkOption {+ type = types.nullOr (types.submodule {+ options = {+ extra_patterns = lib.mkOption {+ type = types.nullOr (types.listOf types.str);+ default = null;+ };+ allowlist = lib.mkOption {+ type = types.nullOr (types.listOf types.str);+ default = null;+ };+ };+ });+ default = null;+ };++ slots = lib.mkOption {+ type = types.nullOr (types.submodule {+ options = {+ per_user = lib.mkOption { type = types.nullOr types.bool; default = null; };+ };+ });+ default = null;+ };++ consolidation = lib.mkOption {+ type = types.nullOr (types.submodule {+ options = {+ max_input_tokens = lib.mkOption { type = types.nullOr types.int; default = null; };+ max_output_tokens = lib.mkOption { type = types.nullOr types.int; default = null; };+ };+ });+ default = null;+ };++ auto_improve = lib.mkOption {+ type = types.nullOr (types.submodule {+ options = {+ require_approval = lib.mkOption { type = types.nullOr types.bool; default = null; };+ on_session_end = lib.mkOption { type = types.nullOr types.bool; default = null; };+ min_observations = lib.mkOption { type = types.nullOr types.int; default = null; };+ min_session_duration_secs = lib.mkOption { type = types.nullOr types.int; default = null; };+ min_confidence = lib.mkOption { type = types.nullOr types.float; default = null; };+ max_input_tokens = lib.mkOption { type = types.nullOr types.int; default = null; };+ max_proposals_per_run = lib.mkOption { type = types.nullOr types.int; default = null; };+ eval = lib.mkOption {+ type = types.nullOr (types.submodule {+ options = {+ enabled = lib.mkOption { type = types.nullOr types.bool; default = null; };+ command = lib.mkOption { type = types.nullOr types.str; default = null; };+ timeout_secs = lib.mkOption { type = types.nullOr types.int; default = null; };+ targets = lib.mkOption {+ type = types.nullOr (types.listOf types.str);+ default = null;+ };+ min_delta = lib.mkOption { type = types.nullOr types.float; default = null; };+ };+ });+ default = null;+ };+ scheduler = lib.mkOption {+ type = types.nullOr (types.submodule {+ options = {+ enabled = lib.mkOption { type = types.nullOr types.bool; default = null; };+ interval_secs = lib.mkOption { type = types.nullOr types.int; default = null; };+ max_sessions_per_tick = lib.mkOption { type = types.nullOr types.int; default = null; };+ min_session_age_secs = lib.mkOption { type = types.nullOr types.int; default = null; };+ experience_every_sessions = lib.mkOption { type = types.nullOr types.int; default = null; };+ experience_sessions = lib.mkOption { type = types.nullOr types.int; default = null; };+ };+ });+ default = null;+ };+ };+ });+ default = null;+ };++ maintenance = lib.mkOption {+ type = types.nullOr (types.submodule {+ options = {+ enabled = lib.mkOption { type = types.nullOr types.bool; default = null; };+ forget_sweep_interval_secs = lib.mkOption { type = types.nullOr types.int; default = null; };+ lint_interval_secs = lib.mkOption { type = types.nullOr types.int; default = null; };+ embedding_backfill_interval_secs = lib.mkOption { type = types.nullOr types.int; default = null; };+ };+ });+ default = null;+ };++ dream = lib.mkOption {+ type = types.nullOr (types.submodule {+ options = {+ enabled = lib.mkOption { type = types.nullOr types.bool; default = null; };+ interval_secs = lib.mkOption { type = types.nullOr types.int; default = null; };+ idle_window_secs = lib.mkOption { type = types.nullOr types.int; default = null; };+ min_pts = lib.mkOption { type = types.nullOr types.int; default = null; };+ max_eps = lib.mkOption { type = types.nullOr types.float; default = null; };+ max_clusters_per_run = lib.mkOption { type = types.nullOr types.int; default = null; };+ min_cold_pages = lib.mkOption { type = types.nullOr types.int; default = null; };+ };+ });+ default = null;+ };++ retrieval = lib.mkOption {+ type = types.nullOr (types.submodule {+ options = {+ query_intent = lib.mkOption { type = types.nullOr types.bool; default = null; };+ session_recall_bonus = lib.mkOption { type = types.nullOr types.float; default = null; };+ abstract_vectors = lib.mkOption { type = types.nullOr types.bool; default = null; };+ belief_authority_weight = lib.mkOption { type = types.nullOr types.float; default = null; };+ };+ });+ default = null;+ };++ routing = lib.mkOption {+ type = types.nullOr (types.submodule {+ options = {+ mid_session = lib.mkOption { type = types.nullOr types.str; default = null; };+ };+ });+ default = null;+ };++ auto_scope = lib.mkOption {+ type = types.nullOr (types.submodule {+ options = {+ mode = lib.mkOption { type = types.nullOr types.str; default = null; };+ session_ttl_secs = lib.mkOption { type = types.nullOr types.int; default = null; };+ max_entries = lib.mkOption { type = types.nullOr types.int; default = null; };+ };+ });+ default = null;+ };++ auth = lib.mkOption {+ type = types.nullOr (types.submodule {+ options = {+ secure_cookie = lib.mkOption { type = types.nullOr types.bool; default = null; };+ root_username = lib.mkOption { type = types.nullOr types.str; default = null; };+ root_issuer = lib.mkOption { type = types.nullOr types.str; default = null; };+ root_subject = lib.mkOption { type = types.nullOr types.str; default = null; };+ root_email = lib.mkOption { type = types.nullOr types.str; default = null; };+ trusted_proxy_cidrs = lib.mkOption {+ type = types.nullOr (types.listOf types.str);+ default = null;+ };+ };+ });+ default = null;+ description = ''+ Non-secret auth settings only. Never put bearer_token, token_pepper,+ initial_root_password, recovery_token, or actor_proxy_bearer_token here —+ use ageSecret / sopsSecret / environmentFile instead.+ '';+ };+}diff --git a/nix/systemd-sandbox.nix b/nix/systemd-sandbox.nixnew file mode 100644index 00000000..3d1ad552--- /dev/null+++ b/nix/systemd-sandbox.nix@@ -0,0 +1,66 @@+# Shared systemd hardening for ai-memory (NixOS module + FHS units).+#+# Keep packaging/systemd/ai-memory.service and ai-memory-user.service aligned+# with these keys; scripts/check-native-packaging.sh asserts the system unit+# contains every entry below.+{ lib, ... }:++{+ # Full sandbox for the system unit (StateDirectory + /var/lib/ai-memory).+ aiMemorySystemSandbox = {+ CapabilityBoundingSet = [ ];+ AmbientCapabilities = [ ];+ MemoryDenyWriteExecute = true;+ RestrictAddressFamilies = [+ "AF_UNIX"+ "AF_INET"+ "AF_INET6"+ ];+ RestrictNamespaces = true;+ RestrictRealtime = true;+ RestrictSUIDSGID = true;+ LockPersonality = true;+ PrivateDevices = true;+ RemoveIPC = true;+ ProtectKernelTunables = true;+ ProtectKernelModules = true;+ ProtectKernelLogs = true;+ ProtectControlGroups = true;+ ProtectClock = true;+ ProtectHostname = true;+ SystemCallArchitectures = "native";+ UMask = "0077";+ NoNewPrivileges = true;+ PrivateTmp = true;+ ProtectHome = true;+ ProtectSystem = "strict";+ };++ # User-unit sandbox: same confinement where %h paths must stay writable.+ aiMemoryUserSandbox = {+ CapabilityBoundingSet = [ ];+ AmbientCapabilities = [ ];+ MemoryDenyWriteExecute = true;+ RestrictAddressFamilies = [+ "AF_UNIX"+ "AF_INET"+ "AF_INET6"+ ];+ RestrictNamespaces = true;+ RestrictRealtime = true;+ RestrictSUIDSGID = true;+ LockPersonality = true;+ PrivateDevices = true;+ RemoveIPC = true;+ ProtectKernelTunables = true;+ ProtectKernelModules = true;+ ProtectKernelLogs = true;+ ProtectControlGroups = true;+ ProtectClock = true;+ ProtectHostname = true;+ SystemCallArchitectures = "native";+ UMask = "0077";+ NoNewPrivileges = true;+ PrivateTmp = true;+ };+}diff --git a/packaging/systemd/ai-memory-user.service b/packaging/systemd/ai-memory-user.serviceindex d70e5947..6cc67b34 100644--- a/packaging/systemd/ai-memory-user.service+++ b/packaging/systemd/ai-memory-user.service@@ -8,6 +8,24 @@ EnvironmentFile=-%h/.config/ai-memory/envExecStart=/usr/bin/ai-memory --data-dir %h/.local/share/ai-memory --config %h/.config/ai-memory/config.toml serve --transport http --enable-webRestart=on-failureRestartSec=5s+CapabilityBoundingSet=+AmbientCapabilities=+MemoryDenyWriteExecute=true+RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6+RestrictNamespaces=true+RestrictRealtime=true+RestrictSUIDSGID=true+LockPersonality=true+PrivateDevices=true+RemoveIPC=true+ProtectKernelTunables=true+ProtectKernelModules=true+ProtectKernelLogs=true+ProtectControlGroups=true+ProtectClock=true+ProtectHostname=true+SystemCallArchitectures=native+UMask=0077NoNewPrivileges=truePrivateTmp=truediff --git a/packaging/systemd/ai-memory.service b/packaging/systemd/ai-memory.serviceindex 47badbd6..4f097a83 100644--- a/packaging/systemd/ai-memory.service+++ b/packaging/systemd/ai-memory.service@@ -12,8 +12,29 @@ EnvironmentFile=-/etc/ai-memory/envExecStart=/usr/bin/ai-memory --data-dir /var/lib/ai-memory --config /etc/ai-memory/config.toml serve --transport http --enable-webRestart=on-failureRestartSec=5s+TimeoutStopSec=30s+StartLimitBurst=5+StartLimitIntervalSec=60sStateDirectory=ai-memoryStateDirectoryMode=0750+CapabilityBoundingSet=+AmbientCapabilities=+MemoryDenyWriteExecute=true+RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6+RestrictNamespaces=true+RestrictRealtime=true+RestrictSUIDSGID=true+LockPersonality=true+PrivateDevices=true+RemoveIPC=true+ProtectKernelTunables=true+ProtectKernelModules=true+ProtectKernelLogs=true+ProtectControlGroups=true+ProtectClock=true+ProtectHostname=true+SystemCallArchitectures=native+UMask=0077NoNewPrivileges=truePrivateTmp=trueProtectHome=truediff --git a/scripts/check-native-packaging.sh b/scripts/check-native-packaging.shindex cbc68d1e..e8f38ff7 100755--- a/scripts/check-native-packaging.sh+++ b/scripts/check-native-packaging.sh@@ -184,12 +184,34 @@ main() {"${TMP_ROOT}/usr/lib/systemd/system/ai-memory-user-parse-test.service"systemd-analyze --root="${TMP_ROOT}" verify ai-memory-user-parse-test.service- log "Checking expected native paths and modes"+ log "Checking expected native paths, sandbox, and modes"assert_contains packaging/systemd/ai-memory.service "--data-dir /var/lib/ai-memory"assert_contains packaging/systemd/ai-memory.service "--config /etc/ai-memory/config.toml"assert_contains packaging/systemd/ai-memory.service "EnvironmentFile=-/etc/ai-memory/env"assert_contains packaging/systemd/ai-memory.service "StateDirectory=ai-memory"assert_contains packaging/systemd/ai-memory.service "ReadWritePaths=/var/lib/ai-memory"+ for sandbox_key in \+ "CapabilityBoundingSet=" \+ "AmbientCapabilities=" \+ "MemoryDenyWriteExecute=true" \+ "RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6" \+ "RestrictNamespaces=true" \+ "RestrictRealtime=true" \+ "RestrictSUIDSGID=true" \+ "LockPersonality=true" \+ "PrivateDevices=true" \+ "RemoveIPC=true" \+ "ProtectKernelTunables=true" \+ "ProtectKernelModules=true" \+ "ProtectKernelLogs=true" \+ "ProtectControlGroups=true" \+ "ProtectClock=true" \+ "ProtectHostname=true" \+ "SystemCallArchitectures=native" \+ "UMask=0077"; do+ assert_contains packaging/systemd/ai-memory.service "${sandbox_key}"+ assert_contains packaging/systemd/ai-memory-user.service "${sandbox_key}"+ doneassert_contains packaging/systemd/ai-memory-user.service "--data-dir %h/.local/share/ai-memory"assert_contains packaging/systemd/ai-memory-user.service "--config %h/.config/ai-memory/config.toml"assert_contains packaging/systemd/ai-memory-user.service "EnvironmentFile=-%h/.config/ai-memory/env"diff --git a/scripts/check-nix-packaging.sh b/scripts/check-nix-packaging.shnew file mode 100755index 00000000..22525194--- /dev/null+++ b/scripts/check-nix-packaging.sh@@ -0,0 +1,59 @@+#!/usr/bin/env bash+# CI-safe checks for the Nix flake package output.+#+# Validates the built prefix (hooks, config template, binary execution) and+# `nix run` wiring. Does not mutate the host or require systemd.++set -euo pipefail++PREFIX="${1:-}"++log() {+ printf '==> %s\n' "$*"+}++fail() {+ printf 'error: %s\n' "$*" >&2+ exit 1+}++repo_root() {+ local script_dir+ script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+ cd "${script_dir}/.." && pwd+}++main() {+ if [ -z "${PREFIX}" ]; then+ fail "usage: $0 <nix-build-result-prefix>"+ fi++ local binary="${PREFIX}/bin/ai-memory"+ if [ ! -x "${binary}" ]; then+ fail "missing executable: ${binary}"+ fi++ log "Checking ai-memory --version"+ "${binary}" --version++ local hooks_dir="${PREFIX}/share/ai-memory/hooks"+ if [ ! -d "${hooks_dir}" ]; then+ fail "missing hooks directory: ${hooks_dir}"+ fi+ if [ -z "$(ls -A "${hooks_dir}" 2>/dev/null)" ]; then+ fail "hooks directory is empty: ${hooks_dir}"+ fi++ local config_template="${PREFIX}/etc/ai-memory/config.default.toml"+ if [ ! -f "${config_template}" ]; then+ fail "missing config template: ${config_template}"+ fi++ log "Checking nix run smoke"+ cd "$(repo_root)"+ nix run . -- --version++ log "Nix packaging checks passed"+}++main "$@"