Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

Merge pull request #989 from rubenlr/nixos-module

AkitaOnRailsf7d52c8d8d8a
diff --cc .github/CODEOWNERS
index 00000000,00000000..886d17f5
new file mode 100644
--- /dev/null
+++ b/.github/CODEOWNERS
@@@ -1,0 -1,0 +1,7 @@@
++# Nix packaging and module maintenance.
++/nix/ @rubenlr
++/flake.nix @rubenlr
++/flake.lock @rubenlr
++/.github/workflows/nix.yml @rubenlr
++/scripts/check-nix-packaging.sh @rubenlr
++/scripts/test-nixos-systemd-container.sh @rubenlr
diff --cc .github/workflows/nix.yml
index b6203fc0,987aa0bc..dc7ba0ea
--- a/.github/workflows/nix.yml
+++ b/.github/workflows/nix.yml
@@@ -1,6 -1,11 +1,8 @@@
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 + NixOS systemd container
-# smoke) and aarch64-darwin (package + artifact smoke only). NixOS checks and
-# the OCI/systemd container smoke always target x86_64-linux and stay on the
-# Linux leg — Darwin attrs would add noise without signal.
++# Builds the flake so the Nix packaging cannot rot unnoticed. Linux package
++# and module evaluation are the fast path. Darwin and the privileged NixOS
++# container smoke run only on schedule, manual dispatch, or a `full-ci` PR.
#
# 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
@@@ -14,16 -19,20 +16,21 @@@
# demand.
on:
push:
-- branches: [main]
++ branches: [main, release/2.6]
paths:
- 'flake.nix'
+ - 'nix/**'
- 'Cargo.lock'
- 'Cargo.toml'
- 'rust-toolchain.toml'
+ - 'scripts/check-nix-packaging.sh'
+ - 'scripts/test-nixos-systemd-container.sh'
- '.github/workflows/nix.yml'
pull_request:
++ types: [opened, synchronize, reopened, labeled]
paths:
- 'flake.nix'
+ - 'nix/**'
- 'Cargo.lock'
- 'Cargo.toml'
- 'rust-toolchain.toml'
@@@ -38,9 -49,17 +47,9 @@@ permissions
contents: read
jobs:
-- build:
- name: nix build
- 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 }}
++ build-linux:
++ name: nix build (x86_64-linux)
+ runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: cachix/install-nix-action@13d8dd58da0234aa297dedd986986ccb8e7f3e24 # v31.11.1
@@@ -49,7 -68,28 +58,43 @@@
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: nix build --print-build-logs '.#packages.x86_64-linux.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'
++ - run: nix build --print-build-logs '.#checks.x86_64-linux.nixos-module-eval'
+ # One runtime path: packages.x86_64-linux.nixos-ai-memory-docker builds
+ # system.build.toplevel once (via the docker-image tarball) and the
+ # script imports that rootfs, starts systemd, and checks install +
+ # /healthz + dataDir restart/volume persistence.
+ #
+ # Non-goals for this step (do not expand here):
+ # - A→B package upgrade / SQLite-wiki migration matrix
+ # - Exhaustive settings-options.nix key matrix
+ # - Soft fake-systemd without a real unit start
+ # - Claiming the app Docker image covers the NixOS module
+ # - Darwin / multi-arch NixOS OCI (Linux x86_64 only by design)
- # - Re-asserting sandbox keys (covered by nixos-sandbox-parity)
- - if: matrix.system == 'x86_64-linux'
++ - if: >-
++ github.event_name == 'schedule' ||
++ github.event_name == 'workflow_dispatch' ||
++ (github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'full-ci'))
+ run: scripts/test-nixos-systemd-container.sh
++
++ build-darwin:
++ name: nix build (aarch64-darwin)
++ if: >-
++ github.event_name == 'schedule' ||
++ github.event_name == 'workflow_dispatch' ||
++ (github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'full-ci'))
++ runs-on: macos-latest
++ steps:
++ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
++ - uses: cachix/install-nix-action@13d8dd58da0234aa297dedd986986ccb8e7f3e24 # v31.11.1
++ with:
++ extra_nix_config: |
++ experimental-features = nix-command flakes
++ - run: nix build --print-build-logs '.#packages.aarch64-darwin.default'
++ - run: scripts/check-nix-packaging.sh ./result
diff --cc AGENTS.md
index 273645c5,4d05d9ad..371b771a
--- a/AGENTS.md
+++ b/AGENTS.md
@@@ -310,7 -310,10 +310,11 @@@ 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.
++- `.github/workflows/nix.yml` runs the Linux package and NixOS module eval for
++ affected changes. Darwin and the privileged systemd-container smoke run on
++ schedule, manual dispatch, or a `full-ci` pull request.
- CI additionally runs `cargo build --release --bin ai-memory` on
Linux/macOS, a Docker image smoke test, `cargo audit` (with the ignores
listed in `ci.yml`), and differential gitleaks scanning.
diff --cc CHANGELOG.md
index eeb1a88d,819023cd..fa8f65f8
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -8,189 -8,44 +8,196 @@@ and this project adheres to [Semantic V
## [Unreleased]
### 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`, agenix/sops wiring, refusal contracts (age+sops mutex, secrets
- in `settings.auth`, forbidden `settings.bind`), `ExecStart`
- (`--data-dir` / `serve` / `--transport http`), default `StateDirectory` vs
- custom `dataDir` tmpfiles/`ReadWritePaths`, and cheap
- network-online / `openFirewall` / `MemoryMax` / `TasksMax` round-trips.
- `packages.x86_64-linux.nixos-ai-memory-docker` builds one NixOS
- `system.build.toplevel` (via the docker-image rootfs tarball) and
- `scripts/test-nixos-systemd-container.sh` runs a privileged systemd
- container smoke (`systemctl` + in-container `/healthz` + dataDir
- restart/volume persistence) on the Linux `nix.yml` leg. The existing
- `flake.nix` package/devShell/CLI build is unchanged. (#989)
++- Added a NixOS module exposed as `nixosModules.default`, with a dedicated
++ non-login service user, a hardened systemd unit, declarative non-secret
++ settings, agenix/sops/environment-file secret sources, and opt-in web,
++ firewall, and resource settings. Non-loopback binds require exactly one
++ secret source; expensive Darwin and privileged container checks run only in
++ the full CI tier. (#989)
+- Added `ai-memory doctor` reporting for Claude Code's default native
+ `memory/` store for the current repository: location, file count, and whether
+ the nearest marker's `ignore_paths` would exclude a read. Repository-root
+ resolution keeps worktrees and subdirectories on the same report, and the
+ output warns that shell/PowerShell compatibility hooks do not enforce the
+ exclusion. (#1003)
+- Added per-event outcomes to `/hook/batch` acknowledgements and process-lifetime
+ ingest counters for stored events, replays, recovery, ignored endings,
+ collisions and failures. Legacy acknowledgement fields were preserved. (#1015)
+- Added receipt outcomes and delivery counts to the companion relay. Opening a
+ schema 1 queue now upgrades it atomically to schema 2; older relay binaries
+ refuse schema 2, so downgrade requires a pre-upgrade backup with all queue
+ users stopped. Pending order and existing delivery metadata were preserved.
+ Receipts now retain their first known outcome. (#1015)
+- Added `ai-memory list-projects [--workspace] [--json]`: a plain, scriptable
+ listing of every workspace/project pair the server knows about, sorted by
+ workspace then project. Previously the only way to see this from outside
+ an interactive `show` session was to call `GET /api/v1/projects` directly.
+ (#1022)
+- Added scope and policy preflight to `ai-memory hook --check-capture`, including
+ event eligibility, sanitized routing hints and server-remapping information.
+ Partial scope, excluded events, rejected profiles and oversized hints refuse
+ capture. Inspection neither ingests events nor claims handoffs. (#1019)
+- Added the latest scoped consolidation job's state and attempt count to HTTP
+ session summaries and MCP `memory_read_session_observations`. The field is
+ `null` when no job exists; provider errors remain private and existing session
+ ownership filters are preserved. (#1018)
+- Added incremental paging to scoped HTTP `recent` reads with `updated_since`
+ and an opaque, scope-bound cursor. Queries preserve equal-time ordering,
+ exclude expired and superseded pages and recheck authorization on each
+ request. Calls without incremental arguments retain their existing array
+ response. Added a generic MCP/HTTP integration guide. (#1017)
+- Added machine-authenticated `GET /identity`, available with the web UI
+ disabled, and `ai-memory doctor` diagnostics for caller identity, external
+ capture ownership and sessions with multiple capture sources (native events
+ or distinct extensions, including backfill).
+ Mixed-source counts preserve scope, session ownership and time-window filters;
+ older servers leave unsupported fields unknown. (#1016)
### 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 and the
- NixOS systemd container smoke stay on the Linux leg only. (#989)
+- Documented FutureInfra as an endpoint for the existing `openai-compat`
+ provider. (#1026)
+
### Fixed
-- NixOS systemd container smoke injects a NixOS `PATH` on every
- `docker exec` (`/run/current-system/sw/bin` + profile + `/bin`) so
- `systemctl`/`curl`/`chown` resolve after activation. Bare `chown` under
- `/bin/sh` previously exited 127 once `/healthz` already passed; absolute
- profile paths alone were also missing until activation linked
- `current-system`. Host-side `/healthz` stays in-container because the
- module's default `127.0.0.1` bind is unreachable through Docker
- published ports. (#989)
+- Fixed completed retries and no-op session endings advancing
+ `last_persisted_ms` without a durable write. Recovery still advances the
+ timestamp when it commits a new page or terminal effect. (#1015)
+- `ai-memory doctor` now warns when the nearest `.ai-memory.toml`'s
+ `[capture]` section is invalid. This fails closed today — every file and
+ shell tool event is reduced to metadata until the marker is fixed, nothing
+ leaks — but nothing surfaced that it had happened, so an operator could
+ believe `ignore_paths` was excluding paths it no longer was. The check is
+ based on the same resolution state the live hook path uses (not just
+ whether the TOML parses), so it also catches a `[capture]` table that
+ parses fine but is still rejected at compile time, e.g. an unsupported glob
+ character in `ignore_paths`. (#1021)
+- Fixed the shell and PowerShell hook scripts mishandling a `$HOME` that ends
+ in a separator: the shell walks missed a marker between the checkout and
+ home, and the PowerShell walks went past home and read a marker above it.
+ Both now match the native `ai-memory hook` walk. (#1023)
+- Fixed `ai-memory run --jail` leaving the `ssh` toggle unchecked when
+ `git push` goes over SSH but `origin`'s fetch URL does not show it: an HTTPS
+ `origin` with an SSH `pushurl` or `pushInsteadOf`, or a `host:path` remote
+ using an `~/.ssh/config` alias. The interactive offer now also uses
+ ai-jail's own dry-run preflight, so a backend that exists but fails ai-jail's
+ trust checks is treated as unavailable instead of producing a broken offer.
+ (#1024)
++
+## [2.5.2] - 2026-10-01
+### Added
+- Added `ai-memory run --jail[=TOGGLES]` and `--no-jail`, and an interactive
+ checklist after the `--yolo` ai-jail offer, to choose which ai-jail
+ credentials and capabilities the jailed session gets. Bare `--jail` re-runs
+ inside ai-jail without asking, using smart defaults: every credential present
+ on the host (`~/.config/gh`, `~/.aws`, `~/.kube`, `~/.config/gcloud`,
+ `~/.docker/config.json`), SSH when `origin` is an SSH remote, and worktree
+ metadata in a linked worktree; host capabilities (`docker`, `gpu`,
+ `display`, `pictures`, `tailscale`) stay off, and anything else is left to
+ the user's own ai-jail config. `--jail=github,aws,no-mise` is exact: it
+ passes every checklist row it does not name as `--no-X`, so a global
+ `~/.ai-jail` cannot add to it (`all` and `none` also work); the checklist
+ likewise passes unchecked rows as `--no-X`. `--jail` works without `--yolo`
+ and in scripts, and fails instead of running unjailed when ai-jail is not
+ usable. Only toggles the installed ai-jail advertises in its
+ `--help` are offered or passed; the credential mounts need ai-jail 2.5.0.
+ ai-jail's security switches (`seccomp`, `landlock`, `private-home`, …) are
+ never accepted. `--no-jail` skips the offer while keeping the `--yolo`
+ warning. A project `.ai-jail` in the launch directory replaces the checklist
+ and the bare-`--jail` defaults (ai-jail loads it under its own trust rules;
+ `--jail=…` still applies on top), and every jailed re-run now passes
+ `--no-save-config`, so ai-jail no longer writes ai-memory's `--network` /
+ `--agent-state` / credential flags into the repository's `.ai-jail`.
+
+### Fixed
+- Fixed the shell and PowerShell session-start hooks for Claude Code, Codex,
+ Cursor, Gemini CLI, OpenCode, Command Code, Devin, and Antigravity CLI not
+ sending the marker's `[briefing]` keys (`briefing`, `briefing_budget`) on the
+ handoff request, so a repository with `inject_on_session_start = true` got
+ the handoff without its compiled brief on script installs (Docker wrapper,
+ `setup-agent`). Only the native `ai-memory hook` command and the Kiro CLI and
+ Kimi Code scripts sent them; all now match `docs/marker-file.md`. (#998)
+- Fixed a wiki checkpoint leaving `.git/index` behind the commit it made. A
+ path-scoped checkpoint wrote the index file only once every 50 commits, so
+ between writes `HEAD` and the working tree held the new page while the index
+ still named the old blob, and `git status` from outside the server showed
+ every checkpointed page as `MM`; a checkpoint with nothing to commit left a
+ stale index the same way. The history itself was always correct. Not specific
+ to Windows. (#983, #1006)
+- Fixed a wiki checkpoint failing instead of retrying when a full walk listed a
+ file that was gone by the time it was read (libgit2's `Os`-class "failed to
+ read file into stream", e.g. an atomic writer's temp file renamed away
+ mid-walk). It now takes the same bounded racy-read retry as a file changed
+ mid-write; unrelated I/O errors still fail fast. This was also the source of
+ an intermittent `concurrent_commits_queue_instead_of_failing` CI failure.
+
+### Security
+- Fixed GHSA-gf78-hf8g-vffm: `memory_read_page` with `include_related` returning pages from
+ projects the caller cannot read under per-project authorization, and walking
+ through them to reach others: in multi-user mode an authenticated user without
+ a grant saw the paths, titles, kinds, and project names of pages in a
+ `restricted` project up to three hops away (never their bodies). `page_links`
+ and the graph already hid them; the multi-hop related walk now filters every
+ hop the same way. Installs without authorization, and root, are unchanged.
+ (#999)
+- Fixed CLI `ai-memory message send` (`POST /admin/messages/send`) bypassing
+ `message_send` admission: it inserted the message without consulting a
+ configured webhook's reject policy or notifying observers, while the MCP
+ send path enforced both. It now runs admission at the recipient scope before
+ the insert — a rejection returns 403 and stores nothing — and notifies
+ observers only after a successful commit, without waiting on nonblocking
+ ones. (#756)
+
+## [2.5.1] - 2026-10-01
+
+### Fixed
+- Fixed `ai-memory run --yolo`'s ai-jail re-exec aborting when the wrapped
+ command carried a flag that ai-jail also defines: `run claude --yolo --env
+ GH_TOKEN=…` failed with "flag --env after command would be passed to the
+ child". The invocation now separates ai-jail's sandbox flags from the
+ wrapped command with `--`; forwarding such a flag also needs ai-jail 2.4.2 or
+ later, whose guard honors the separator.
+- Fixed the `--yolo` ai-jail offer appearing when accepting it could not
+ work. It is now shown only on Linux/macOS when both ai-jail and its sandbox
+ backend (`bwrap` / `sandbox-exec`) are present — never on Windows, even with a
+ file named `ai-jail` on `PATH` — and otherwise the run proceeds without the
+ question. The re-exec runs the exact binary that was found, so a
+ `~/.local/bin`-only ai-jail no longer fails to exec after the user accepted.
+- Fixed `--true-yolo`. It now implies `--yolo` (the warning, the ai-jail
+ offer, and each harness's dangerous mode), so passing it alone no longer
+ bypassed Claude's permissions with no warning; it is interchangeable with
+ `--yolo` for non-Claude harnesses instead of printing "ignoring it"; and it is
+ recognized after native arguments (`run claude --model opus --true-yolo`)
+ instead of being passed to Claude as an unknown option. The `claude_true_yolo`
+ config key now
+ only upgrades an explicit `--yolo`/`--true-yolo` launch, as documented,
+ rather than applying `bypassPermissions` to every managed Claude run.
+- Fixed relaunching right after an interrupted `ai-memory run` failing with
+ "workstream is already active: owned by … until …" when the previous
+ launcher could not release its lease (killed, terminal closed, or an
+ ai-jail sandbox torn down). An interactive launch now names the holder and
+ waits for that lease to lapse (at most one ~90-second lease; Ctrl-C aborts),
+ then starts by itself. A holder that renews the lease meanwhile is reported
+ as a launcher still running — never displaced — and non-interactive launches
+ keep the short retry window.
+- Fixed `--true-yolo` claiming protections it never provided. It set three
+ `CLAUDE_CODE_DISABLE_*RM*` environment variables that Claude Code does not
+ read, and passed an empty `permissions.ask` array that cannot clear `ask`
+ rules from other settings scopes (Claude Code unions them). Both were
+ removed; true-yolo now forces only `bypassPermissions`, and the docs state
+ that Claude still honors your own `ask` rules and command-safety checks in
+ every mode.
+
+### Security
+- Fixed GHSA-vh98: a capture-exclusion candidate or shell argument spelled
+ with a leading `//` (e.g. `//repo/secret/token.txt`) self-classified as a
+ Windows UNC path regardless of the actual host, so it matched zero POSIX
+ `ignore_paths` patterns (a flavor mismatch) and was captured instead of
+ dropped. Path flavor for an untrusted candidate is now derived from the
+ host (the cwd) rather than the candidate string alone, both in the native
+ hook (`ai-memory-hooks` `capture_policy.rs`) and the generated
+ OpenCode/OMP/Pi/OpenClaw TypeScript integrations
+ (`ai-memory-cli` `render_shared.rs`); a genuine Windows/UNC host's UNC
+ candidates are unaffected.
-
## [2.5.0] - 2026-09-30
### Added
diff --cc README.md
index 06a80e33,b7093e76..3b4d9021
--- a/README.md
+++ b/README.md
@@@ -106,6 -106,6 +106,7 @@@ caveats is in [`docs/support-matrix.md`
| Area | Status |
| --- | --- |
| Linux | Supported |
++| NixOS module | Supported |
| macOS | Supported |
| Windows via WSL2 | Supported |
| Native Windows | Experimental |
@@@ -369,6 -369,60 +370,62 @@@ record, so the next managed launch wire
unwired, launch with `--no-autowire` or set `AI_MEMORY_RUN_AUTOWIRE=false`. Install commands are idempotent and write
timestamped 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,
++`systemd.services.ai-memory` unit. It creates a dedicated `ai-memory` system
++user (`nologin`, no linger) and applies a NixOS-specific 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.
++Declarative non-secret config lives in `services.ai-memory.settings`. Common
++keys are typed for discoverability and the TOML freeform type keeps every
++other current and future `config.toml` key usable without duplicating the Rust
++schema. The module renders a generated TOML file and passes `--config`;
++network and web-listener controls stay in the module's top-level options.
+
-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).
++Secrets such as `AI_MEMORY_AUTH_TOKEN` never go in `settings` or the
++world-readable Nix store. This includes `llm_headers`, which can carry API
++credentials; set `AI_MEMORY_LLM_HEADERS` in `ageSecret`, `sopsSecret`, or
++`environmentFile` instead. These three secret sources are mutually exclusive.
++Non-loopback binds require one; loopback may omit them and tolerates a missing
++environment 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 use
Day to day, you mostly do not think about ai-memory. Hooks capture
diff --cc docs/install.md
index 5f2b4285,e330b764..0e4de6fe
--- a/docs/install.md
+++ b/docs/install.md
@@@ -738,6 -740,62 +740,61 @@@ AI_MEMORY_NATIVE_TEST_IMAGE=quay.io/too
---
+ ## Nix / NixOS
+
+ User-facing NixOS module setup lives in the [README NixOS
+ section](../README.md#nixos) (`nixosModules.default`,
+ `services.ai-memory.enable`). This section is the maintainer test ladder
+ for the flake and module — what CI runs, and what each tier proves.
+
+ ### Maintainer test ladder
+
+ 1. **Package smoke** — `nix build .#packages.<system>.default` then
+ `scripts/check-nix-packaging.sh ./result` (binary `--version`, hooks
- tree, config template, `nix run`). Runs on Linux and Darwin in
- `.github/workflows/nix.yml`.
++ tree, config template, `nix run`). Linux runs on affected pushes and pull
++ requests. Darwin runs on schedule, manual dispatch, or a `full-ci` PR.
+ 2. **Eval contracts** — `nix build .#checks.x86_64-linux.nixos-module-eval`
- and `nixos-sandbox-parity`. Cheap Linux-only asserts for enable/bind/
- `--config`/secrets wiring, refusal messages (age+sops mutex, secrets in
- `settings.auth`, `settings.bind`), `ExecStart` (`--data-dir`, `serve`,
- `--transport http`), default `StateDirectory` vs custom `dataDir`
- tmpfiles/`ReadWritePaths`, and sandbox key parity with
- `nix/systemd-sandbox.nix`.
++ runs cheap Linux-only assertions for enable/bind/`--config`/secrets wiring,
++ literal loopback handling, IPv6 address formatting, mutually exclusive
++ secret sources, secrets in `settings.auth`, forbidden `settings.bind`,
++ escaped `ExecStart`, default `StateDirectory`, custom `dataDir` tmpfiles,
++ `ReadWritePaths`, and the NixOS sandbox keys.
+ 3. **Toplevel → OCI → container smoke** — one closure path. Building
+ `packages.x86_64-linux.nixos-ai-memory-docker` builds
+ `system.build.toplevel` once (via the nixpkgs docker-image tarball);
+ there is no separate bare-toplevel CI job. Then:
+
+ ```bash
+ scripts/test-nixos-systemd-container.sh
+ ```
+
+ That script imports the rootfs, runs a privileged systemd container,
+ checks `systemctl is-active ai-memory` and in-container `curl /healthz`
+ (the module's default loopback bind is unreachable via Docker `-p`),
+ writes a
+ marker under `/var/lib/ai-memory`, restarts the unit, and (by default)
- remounts a named volume once. Wired into the Linux leg of `nix.yml`
- only (same path filters as the rest of the Nix job).
++ remounts a named volume once. It is privileged, so it runs only on schedule,
++ manual dispatch, or a `full-ci` pull request.
+
+ **Non-goals** (do not treat these as covered by the ladder above):
+
+ - A→B flake/package upgrade or SQLite-wiki migration matrices
-- Exhaustive `settings-options.nix` key coverage
++- Exhaustive typed settings coverage (unknown TOML keys use `freeformType`)
+ - Soft/fake systemd without a real unit start
+ - Claiming the published app Docker image covers the NixOS module path
+ - Darwin / multi-arch NixOS OCI (Linux x86_64 only by design)
+
+ Useful knobs for the container smoke:
+
+ ```bash
+ AI_MEMORY_NIXOS_TEST_KEEP=1 scripts/test-nixos-systemd-container.sh
+ AI_MEMORY_NIXOS_TEST_VOLUME=0 scripts/test-nixos-systemd-container.sh
+ AI_MEMORY_NIXOS_TEST_IMAGE=ai-memory-nixos-test scripts/test-nixos-systemd-container.sh
+ AI_MEMORY_DOCKER=podman scripts/test-nixos-systemd-container.sh
+ ```
+
+ ---
+
## macOS menu bar app
On a Mac, the self-contained menu bar app is the GUI install: it bundles the
diff --cc docs/security-boundaries.md
index 26d0d931,a842ed85..453a5e97
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@@ -51,17 -50,15 +51,17 @@@ boundary not yet built
| 10d | Workspace delete's own row counts are scope-bound to `workspace_id` (a workspace's *own* rows are never over- or under-counted by a sibling workspace's), its cross-workspace observation/handoff cascade is reported by both preview and confirm rather than prevented (same as `purge-project` one level down), the non-empty guard fails closed without `force`, and `delete-workspace`'s `dry_run` always wins | `ai-memory-store/src/ops.rs` `delete_workspace` — every direct count and the `DELETE FROM workspaces` itself are scoped by `workspace_id = ?1`; the two `collateral_*` counts are scoped by `workspace_id != ?1` so a row is counted as one or the other but never both; `projects_deleted > 0 && !force → WorkspaceNotEmpty` fail-closed, and a missing workspace is `NotFound`, both checked identically under `PurgeMode::Preview` and `PurgeMode::Commit`; whole op in one transaction; `admin.rs` `handle_delete_workspace` checks `req.dry_run` unconditionally, before building the confirmed path, mirroring `reclaim-ledger-versions`/`purge-project`; root-only gate is the shared `/admin/*` multi-user auth ladder, not a separate check | `admin_move.rs` `delete_workspace_dry_run_never_counts_a_different_workspaces_rows` — previewing workspace A counts only its own project/page/session/observation/handoff rows, not workspace B's (which holds two like-named projects and its own full row set), and a session living in B that stamps an observation directly into A is counted in A's own `observations_deleted`, never in `collateral_observations_deleted` (the two counts are mutually exclusive by construction); `admin_move.rs` `delete_workspace_force_true_and_dry_run_true_still_only_previews` — `{"force": true, "dry_run": true}` deletes nothing; `ops.rs` `delete_workspace_dry_run_changes_nothing` — every table's row count, including `workspaces` itself and the `purged_scopes` tombstone (the two tables a confirmed delete's own transaction writes to), is identical before/after a `PurgeMode::Preview` run; `ops.rs` `delete_workspace_dry_run_and_confirmed_delete_both_report_collateral_damage_in_another_workspace` and `admin_move.rs` of the same name — deleting workspace W collaterally deletes an observation, and orphans a handoff's session reference, in a *different* workspace (via `sessions` cascading out of W), and both the preview and the confirmed response count it identically — the cascade itself is reported, not blocked, by either; `admin_move.rs` `delete_workspace_dry_run_refuses_non_empty_without_force` / `delete_workspace_dry_run_nonexistent_workspace_returns_404` — same `409`/`404` a confirmed delete would give; `admin.rs` `multiuser_delete_workspace_dry_run_rejects_db_user_and_anonymous` — root reaches the preview handler (404 control), DB user gets 403, anonymous gets 401 | STRONG |
| 10e | Reconcile-tombstone of a disk-deleted page is opt-in, soft, scope-bound, and false-positive-guarded (invariant #16, #929 delete-half) | `ai-memory-wiki/src/watcher.rs` — off by default (`[maintenance] reconcile_tombstones_deleted_pages`); a page is tombstoned only after its file is observed missing on two consecutive passes (streak resets if the path's `PageId` changed), re-verified against the live filesystem immediately before acting, with reserved/indexed-but-unwalked paths (`bootstrap.md`, `_meta.md`, `_pending/`, `sessions/*.md`) excluded and a circuit breaker that skips a whole scope when `> max(3, 50%)` of its pages look missing or a non-partial walk finds nothing; `ai-memory-store/src/ops.rs` `soft_delete_for_reconcile_if_latest` is a soft tombstone (`is_latest=0` + `superseded_at`, decay's shape) through the single writer actor in one transaction — never a filesystem write — scoped to the page's own `(workspace_id, project_id)` | `watcher.rs` `reconcile_delete_disabled_by_default_never_tombstones_a_missing_page`, `reconcile_delete_cross_project_isolation` (project A's deletion never tombstones project B's same-path page), `reconcile_tombstone_refuses_a_stale_latest_id`, `reconcile_tombstone_refuses_when_the_file_still_exists`, `reconcile_tombstone_never_touches_the_filesystem`; `ops.rs` `reconcile_tombstone_resurrects_instead_of_orphaning_on_recreate` | STRONG |
| 10f | Session-time repair is scope-bound (no cross-project timestamp rewrite) | `ai-memory-store/src/ops.rs` `repair_session_times` — every candidate is read back and updated with `WHERE id=? AND workspace_id=? AND project_id=?`; a row outside that 3-tuple is reported `NotFound` and untouched, same code path as an id that does not exist at all; `ai-memory-mcp/src/admin.rs` `handle_repair_session_times` passes the caller's `(workspace, project)` straight through, never the candidate's own | `ops.rs` `repair_session_times_does_not_touch_a_session_of_another_project` (control: sibling session in-scope repaired in the same batch); `admin_repair_session_times.rs` `cross_project_session_is_not_found_and_untouched`; both bite-checked by dropping the `project_id` filter | STRONG |
-| 11a | Hook backpressure (202/429) + bounded fan-out (invariant #5) | `ai-memory-hooks/src/router.rs` semaphore→429, 202 immediately, `MAX_HOOK_BATCH_ITEMS`, bounded LRU limiter | `router.rs` `handle_hook_returns_429_when_ingest_saturated`, `ingest_rate_limiter_is_bounded` | STRONG |
-| 11b | Capture exclusions drop before storage | `ai-memory-hooks` `capture_policy.rs` `inspect`→`Drop` (before semaphore/spawn), including shell commands whose arguments name an ignored path (`match_command`; argv elements matched whole and tokenized); an invalid marker makes file and shell calls metadata-only, and the server admits a metadata-only shell body only under an invalid marker (`router.rs` `metadata_protocol_is_legal`); generated OpenCode/OMP/Pi/OpenClaw integrations mirror it in `render_shared.rs` `ts_capture_policy_v1` (`captureMatchCommand`) | `capture_policy.rs` per-agent `…honors_exclusions` tests, `shell_fixture_vectors` (shared `capture-policy.json` `shell` drop/keep vectors: tool aliases incl. OpenClaw/Devin `exec`, `workdir`, glob directories, Windows paths), `shell_tool_shapes_of_every_adapter_honor_exclusions`, `fixture_vectors` (incl. TS-adapter `bash`/`exec` vectors); `shell_matching_is_off_when_inactive_and_fails_closed_when_invalid_or_over_budget`; `router.rs` `capture_protocol_shell_decisions_survive_server_reinspection`, `capture_protocol_invalid_marker_shell_is_metadata_only` (active metadata-only shell refused, older client's invalid-marker keep stripped, commandless control kept), `capture_protocol_unparseable_marker_strips_shell_events` (server fallback for an unparseable marker), `capture_protocol_invalid_shell_metadata_claim_must_be_canonical` (a stripped shell claim with a path count or non-`extracted` state is refused); `capture_policy.rs` `invalid_marker_strips_shell_calls_with_unparseable_commands`, `long_bash_lc_script_in_argv_is_not_dropped_by_the_match_budget`; `hook.rs` `shell_command_reading_an_ignored_path_is_dropped_before_spool`; `render_shared.rs` `generated_capture_policy_v1_node_runtime_evidence` (runs the same fixture sections against the emitted TypeScript; `#[ignore]` locally, run with `--ignored` under Node 24 by the Linux CI test job) | STRONG |
+| 11a | Hook backpressure (202/429) + bounded fan-out (invariant #5) | `ai-memory-hooks/src/router.rs` semaphore→429, 202 immediately, `MAX_HOOK_BATCH_ITEMS`, bounded LRU limiter; batch acknowledgements retain only processed indices and classify terminal drops without consuming capacity | `router.rs` `handle_hook_returns_429_when_ingest_saturated`, `ingest_rate_limiter_is_bounded`; `router.rs` `handle_hook_batch_skips_rate_limited_first_item_and_accepts_later_source`, `handle_hook_batch_reports_failed_index_after_rate_limited_skip`, `handle_hook_batch_drops_subagent_events_before_capacity_check` (each asserts result indices and includes an accepted control) | STRONG |
+| 11b | Capture exclusions drop before storage | `ai-memory-hooks` `capture_policy.rs` `inspect`→`Drop` (before semaphore/spawn), including shell commands whose arguments name an ignored path (`match_command`; argv elements matched whole and tokenized); an invalid marker makes file and shell calls metadata-only, and the server admits a metadata-only shell body only under an invalid marker (`router.rs` `metadata_protocol_is_legal`); generated OpenCode/OMP/Pi/OpenClaw integrations mirror it in `render_shared.rs` `ts_capture_policy_v1` (`captureMatchCommand`). Candidate/argument flavor (`Flavor::Posix` vs `Flavor::Windows`, used to pick which `ignore_paths` patterns even apply) is derived from the **host** (the cwd), never from the candidate string alone — a POSIX-host candidate spelled with a leading `//` is collapsed to a single `/` before flavor detection (`normalize_candidate`; TS `captureNormalize`'s `windowsHost` parameter, sourced from `captureHostWindows(cwd)`), fixing GHSA-vh98 (a `//`-prefixed candidate used to self-classify as `Flavor::Windows` regardless of host, matching zero POSIX patterns and being captured instead of dropped); a genuine Windows/UNC host (cwd itself windows-flavored) is unaffected; `hook.rs` `--check-capture` preflight uses the same capture policy before any spool or spawn | `capture_policy.rs` per-agent `…honors_exclusions` tests, `shell_fixture_vectors` (shared `capture-policy.json` `shell` drop/keep vectors: tool aliases incl. OpenClaw/Devin `exec`, `workdir`, glob directories, Windows paths, and a POSIX-host leading-`//` command via `/{root}/docs/adr/x.md`), `shell_tool_shapes_of_every_adapter_honor_exclusions`, `fixture_vectors` (incl. TS-adapter `bash`/`exec` vectors, and `normalization`'s leading-`//` POSIX vectors alongside the kept Windows-cwd UNC vectors as the no-regression control); `shell_matching_is_off_when_inactive_and_fails_closed_when_invalid_or_over_budget`; `router.rs` `capture_protocol_shell_decisions_survive_server_reinspection`, `capture_protocol_invalid_marker_shell_is_metadata_only` (active metadata-only shell refused, older client's invalid-marker keep stripped, commandless control kept), `capture_protocol_unparseable_marker_strips_shell_events` (server fallback for an unparseable marker), `capture_protocol_invalid_shell_metadata_claim_must_be_canonical` (a stripped shell claim with a path count or non-`extracted` state is refused); `capture_policy.rs` `invalid_marker_strips_shell_calls_with_unparseable_commands`, `long_bash_lc_script_in_argv_is_not_dropped_by_the_match_budget`, **`a_leading_double_slash_candidate_does_not_escape_posix_ignore_paths_via_flavor_mismatch`** (GHSA-vh98 adversarial: attempts the `//repo/secret/...` violation on a POSIX host, proves it now drops, with a plain-single-slash control and a Windows-hosted genuine-UNC control both still correct — fails on the pre-fix code); `hook.rs` `shell_command_reading_an_ignored_path_is_dropped_before_spool`; `render_shared.rs` `generated_capture_policy_v1_node_runtime_evidence` (runs the same fixture sections, including the GHSA-vh98 vectors, against the emitted TypeScript; `#[ignore]` locally, run with `--ignored` under Node 24 by the Linux CI test job); `hook.rs` `check_capture_refuses_partial_scope_and_excluded_content` (ignored-path and partial-scope violations refused, complete public-path control passes), `check_capture_bounds_marker_hints_and_refuses_oversized_scope` (513-byte hints refused, 512-byte control passes; native routing preserved) | STRONG |
| 11c | Capture hook ≤200ms budget (invariant #5) | `hooks/_lib.sh` capture path `curl --max-time 0.2` (context-fetch 1.0s and background drain 2.0s are separate, larger-budget paths) | none (shell-script timeout; hard to unit-test) — watch on any capture-path change | WATCH |
-| 11d | Hook server-profile routing: a marker-selected server gets only its own capture and its own token (#992) | `ai-memory-cli/src/server_profiles.rs` `resolve` (validated `ProfileName`, strict `servers.toml` parse, `roots` required once two profiles exist, component-wise root match) and `marker.rs` `find_server_selection` (inherited down the tree, any value shape counts); `commands/hook.rs` `resolve_hook_route` drops a `Rejected` route before spool, handoff and backfill, and hands the drainer no live token for a profile route; `commands/hook_spool.rs` `static_retry_token` (a profile entry retries only with its own stored token), the loopback reroot skip, and chunk splitting on `profile`; generated TS `captureServerRouted` drops a routed repository and gates `fetchHandoff`; `hooks/_lib.sh` `ai_memory_server_routed` (flag refused by `ai_memory_post_hook`/`ai_memory_get_handoff`) and `hooks/lib/ai-memory-hook.ps1` `Test-AiMemoryServerRouted` drop it in the script hooks | `hook.rs` `each_repository_spools_to_its_own_profile_with_its_own_token`, `a_selection_that_does_not_resolve_emits_nothing` (unknown / tokenless / outside roots / roots required / invalid name, plus a resolving control), `session_start_handoff_comes_from_the_profile_server_only`, `a_repository_without_a_server_key_keeps_the_install_default`; `hook_spool.rs` `a_profile_entry_is_never_retried_with_the_install_live_token` (server B accepts exactly the install's live token and must still not get it), `a_profile_entry_recovers_with_its_own_rotated_token` (control), `a_profile_entry_on_a_dead_loopback_port_is_not_rerouted_to_the_default`, `profile_and_default_entries_at_one_address_ride_separate_batches`; `server_profiles.rs` roots/registry/name tests; `marker.rs` `nested_markers_without_server_inherit_the_ancestor_selection`; `install_hooks.rs` `generated_integrations_fail_closed_on_a_server_profile_marker`, `openclaw_plugin.rs` `openclaw_plugin_fails_closed_on_a_server_profile_marker`, and the `server-routed-*` checks in `generated_capture_policy_v1_node_runtime_evidence`; `hook.rs` `an_event_without_a_payload_cwd_routes_by_the_process_cwd`, `a_refused_route_prints_nothing_for_kimi_user_prompts`; `hook_spool.rs` `a_profile_entry_is_not_retried_with_a_token_issued_for_a_new_url`; `server_profiles.rs` `changing_the_url_without_a_token_discards_the_old_token`, `omitted_roots_keep_the_registered_ones`; `marker.rs` `outside_home_the_walk_reaches_a_marker_above_the_checkout_root`, `encoding_noise_cannot_hide_a_server_key`, `an_unreadable_marker_is_a_refused_selection`; `backfill.rs` `a_spawned_backfill_authenticates_like_the_hook_that_spawned_it`; `tests/hooks/test_lib.sh` "server profiles (#992)" section; `hook.rs` `a_mixed_spool_drains_each_event_only_to_its_own_server` (two token-gated servers, one spool, one drain: each server receives exactly its own event with exactly its own bearer); `tests/suite/server_profiles.rs` (the built binary: `server add` → `hook` spools to the profile with its token, unknown profile spools nothing, `uninstall` removes the tokens; `two_real_servers_each_receive_only_their_own_repository` runs two real `ai-memory serve` children with different root tokens and checks on each server which repository landed there); `ai-memory-hooks` `powershell_server_routed.rs` `server_routed_guard_mirrors_the_native_walk` (runs `Test-AiMemoryServerRouted` under real PowerShell: inherited, BOM, look-alike keys, the `$HOME` boundary with its control, past a checkout root outside home, current directory) | STRONG for native hooks, generated TS, `.sh` and `.ps1` hooks. Known gap: an older binary draining a shared spool ignores `profile` |
-| 12 | Network/auth posture | `config.rs` loopback `DEFAULT_BIND`; `serve.rs` `validate_http_exposure`, `require_allowed_host`; `auth.rs` `require_bearer` | `serve.rs` host-guard (missing→400 / forged→403), non-loopback-requires-token; `auth.rs` wrong-token 401 | STRONG |
+| 11d | Hook server-profile routing: a marker-selected server gets only its own capture and its own token (#992) | `ai-memory-cli/src/server_profiles.rs` `resolve` (validated `ProfileName`, strict `servers.toml` parse, `roots` required once two profiles exist, component-wise root match) and `marker.rs` `find_server_selection` (inherited down the tree, any value shape counts); `commands/hook.rs` `resolve_hook_route` drops a `Rejected` route before spool, handoff and backfill, and hands the drainer no live token for a profile route; `commands/hook_spool.rs` `static_retry_token` (a profile entry retries only with its own stored token), the loopback reroot skip, and chunk splitting on `profile`; generated TS `captureServerRouted` drops a routed repository and gates `fetchHandoff`; `hooks/_lib.sh` `ai_memory_server_routed` (flag refused by `ai_memory_post_hook`/`ai_memory_get_handoff`) and `hooks/lib/ai-memory-hook.ps1` `Test-AiMemoryServerRouted` drop it in the script hooks; `--check-capture` refuses a rejected server-profile selection without printing its token or URL | `hook.rs` `each_repository_spools_to_its_own_profile_with_its_own_token`, `a_selection_that_does_not_resolve_emits_nothing` (unknown / tokenless / outside roots / roots required / invalid name, plus a resolving control), `session_start_handoff_comes_from_the_profile_server_only`, `a_repository_without_a_server_key_keeps_the_install_default`; `hook_spool.rs` `a_profile_entry_is_never_retried_with_the_install_live_token` (server B accepts exactly the install's live token and must still not get it), `a_profile_entry_recovers_with_its_own_rotated_token` (control), `a_profile_entry_on_a_dead_loopback_port_is_not_rerouted_to_the_default`, `profile_and_default_entries_at_one_address_ride_separate_batches`; `server_profiles.rs` roots/registry/name tests; `marker.rs` `nested_markers_without_server_inherit_the_ancestor_selection`; `install_hooks.rs` `generated_integrations_fail_closed_on_a_server_profile_marker`, `openclaw_plugin.rs` `openclaw_plugin_fails_closed_on_a_server_profile_marker`, and the `server-routed-*` checks in `generated_capture_policy_v1_node_runtime_evidence`; `hook.rs` `an_event_without_a_payload_cwd_routes_by_the_process_cwd`, `a_refused_route_prints_nothing_for_kimi_user_prompts`; `hook_spool.rs` `a_profile_entry_is_not_retried_with_a_token_issued_for_a_new_url`; `server_profiles.rs` `changing_the_url_without_a_token_discards_the_old_token`, `omitted_roots_keep_the_registered_ones`; `marker.rs` `outside_home_the_walk_reaches_a_marker_above_the_checkout_root`, `encoding_noise_cannot_hide_a_server_key`, `an_unreadable_marker_is_a_refused_selection`; `backfill.rs` `a_spawned_backfill_authenticates_like_the_hook_that_spawned_it`; `tests/hooks/test_lib.sh` "server profiles (#992)" section; `hook.rs` `a_mixed_spool_drains_each_event_only_to_its_own_server` (two token-gated servers, one spool, one drain: each server receives exactly its own event with exactly its own bearer); `tests/suite/server_profiles.rs` (the built binary: `server add` → `hook` spools to the profile with its token, unknown profile spools nothing, `uninstall` removes the tokens; `two_real_servers_each_receive_only_their_own_repository` runs two real `ai-memory serve` children with different root tokens and checks on each server which repository landed there); `ai-memory-hooks` `powershell_server_routed.rs` `server_routed_guard_mirrors_the_native_walk` (runs `Test-AiMemoryServerRouted` under real PowerShell: inherited, BOM, look-alike keys, the `$HOME` boundary with its control, past a checkout root outside home, current directory); `hook.rs` `a_selection_that_does_not_resolve_emits_nothing` (rejected routes refuse preflight; resolved profile control passes); `tests/hooks/test_lib.sh` and `powershell_home.rs` `a_trailing_separator_on_home_keeps_the_walk_boundary` (a `$HOME` ending in `/` or `\` keeps both script walks at home: a `server` marker above it routes nothing, with a root-home control that does) | STRONG for native hooks, generated TS, `.sh` and `.ps1` hooks. Known gap: an older binary draining a shared spool ignores `profile` |
- | 12 | Network/auth posture | `config.rs` loopback `DEFAULT_BIND`; `serve.rs` `validate_http_exposure`, `require_allowed_host`; `auth.rs` `require_bearer`; `serve.rs` mounts `/identity` inside the host and machine-auth gates even with web disabled | `serve.rs` host-guard (missing→400 / forged→403), non-loopback-requires-token; `auth.rs` wrong-token 401; `serve.rs` `machine_identity_remains_authenticated_with_web_disabled_and_expired_keys` (wrong and expired keys refused, valid machine key accepted, web remains disabled) | STRONG |
++| 12 | Network/auth posture | `config.rs` loopback `DEFAULT_BIND`; `serve.rs` `validate_http_exposure`, `require_allowed_host`; `auth.rs` `require_bearer`; `serve.rs` mounts `/identity` inside the host and machine-auth gates even with web disabled; `nix/nixos-module.nix` treats only literal `127.0.0.1`/`::1` as loopback, requires exactly one secret environment source for other binds, keeps secret auth and `llm_headers` values out of the Nix store, and brackets IPv6 in `ExecStart` | `serve.rs` host-guard (missing→400 / forged→403), non-loopback-requires-token; `auth.rs` wrong-token 401; `serve.rs` `machine_identity_remains_authenticated_with_web_disabled_and_expired_keys` (wrong and expired keys refused, valid machine key accepted, web remains disabled); `flake.nix` `nixos-module-eval` refuses `localhost` and `0.0.0.0` without a secret source, refuses two secret sources, `settings.auth` secrets, and `settings.llm_headers`, with literal IPv4/IPv6 loopback and one-source controls | STRONG |
| 13 | Managed-run transcript attribution (concurrent launches in one checkout, invariant #16) | `ai-memory-store/src/workstream.rs` `link_native_session` stamps `native_session_linked_at` on its own run only, both `finish` updates drop the stamp when the session changes, `run_status` reports it; `ai-memory-cli/src/commands/run.rs` `resolve_native_session_after_run` takes a linked session only when `ai-memory-workstream` `native_session_in_checkout` holds it for this checkout (OpenCode by recorded directory), never falls back to a link it set aside, and turns an `AmbiguousNativeSession` into a warning with nothing imported; `ai-memory-workstream/src/transcript.rs` `discover_crush` claims only the one top-level session created (or, with `--continue`, touched) during the run, and in a data directory outside the project only one that edited a file in it | `multi_session.rs` `a_session_linked_by_one_managed_run_is_not_another_runs`; `run.rs` `a_session_linked_during_the_run_wins_over_discovery` (concurrent newer session, another checkout's link refused, no fallback to it, unlinked control); `transcript.rs` `native_session_in_checkout_checks_the_opencode_directory`; `store/src/lib.rs` `managed_run_status_reports_a_link_made_during_the_run`; `run.rs` `ambiguous_crush_discovery_keeps_the_run`; `transcript.rs` `crush_discovery_claims_only_the_session_the_run_created`, `crush_discovery_in_a_shared_store_claims_only_an_edit_here` | PARTIAL: a run whose child links nothing still falls back to discovering the newest session in the checkout; Crush, which has no hooks, relies on that discovery alone and claims nothing when it is ambiguous |
-| 14 | Per-project authorization (#708) | `ai-memory-store/src/project_authz.rs` `authorize_project` / `ProjectAuthz::authorize` choke point (V68 `project_grants` + `projects.access_mode`, default `open`; V69 `projects.created_by` feeds `is_creator`); `scope.rs` `ScopeResolver::with_project_authz` (reader pool for reads, writer actor for writes) and its free forms `authorize_scope_for` / `*_guarded`, attached for every DB user by `ai-memory-mcp` `scope_resolver_as`, `ai-memory-web` `authorize_read` / `lookup_project`, and `ai-memory-hooks` (`grants.rs` `authorize_resolved` for run/workstream ids, the capture check in `router.rs`); read-shaped mutations resolve at `ProjectAccess::Write` (`resolve_existing_args(.., need)`); unscoped reads filtered before `LIMIT` by `reader.rs` `readable_repository_sql`; `WriterHandle::authorize_project` as defense in depth. Page ids are never taken from a caller (only derived from already-authorized hits), so there is no page-id entry point to guard | `tests/suite/project_authz.rs` (decision matrix, ship-inert, resolver gate); `tests/suite/access_mode.rs` `every_caller_against_both_modes`, `a_restricted_project_admits_the_team_and_refuses_the_outsider`, `new_projects_follow_the_server_default_and_admit_their_creator`; `scope.rs` `the_argument_shape_does_not_decide_the_level`, `a_user_reaches_only_what_they_were_granted`, `creating_authorizes_against_a_project_that_already_exists`, `a_refused_scope_fails_the_search_instead_of_shortening_it`; `grants.rs` `search_finds_only_what_the_viewer_may_read`, `the_limit_counts_only_what_the_viewer_may_see`, `the_workspace_handoff_comes_only_from_readable_repositories`; `ai-memory-mcp` `server.rs` `a_reader_may_read_everything_and_change_nothing`, `bob_cannot_read_alices_page_in_a_restricted_project`, `bob_cannot_find_alices_page_by_searching_in_a_restricted_project`, `bob_cannot_consolidate_a_session_in_alices_repository`, `a_restricted_projects_queues_need_write`; `ai-memory-hooks` `a_capture_needs_writer_on_the_repository_it_lands_in`, `session_start_delivers_nothing_from_a_repository_the_viewer_cannot_read`, `run_and_workstream_ids_only_answer_someone_who_may_reach_the_repository`; `ai-memory-web` `web_reads_honour_grants_in_a_restricted_project`, `metadata_shows_only_what_the_viewer_may_read` — each with a granted or open-project control, and proven to fail with the choke point (18 tests) or the SQL filter (9 tests) neutralized | STRONG — slice 3 closed both bypass classes (unscoped reads, raw-id entry points) and added the root-only management surface. Out of scope by design: per-project administrators (granting/restricting is root-only), and access modes, creators and grants live only in SQLite, so `reindex` resets them |
+| 13b | Managed-run lease exclusivity (one active run per workstream, invariant #16) | `ai-memory-store/src/workstream.rs` `prepare_run` expires lapsed leases and refuses any other `active` run on the workstream inside one transaction (`StoreError::WorkstreamBusy`), regardless of the `lease_owner` label; `heartbeat` renews only `active` rows. `ai-memory-cli/src/commands/run.rs` `wait_out_held_lease` (interactive relaunch) only waits for a reported expiry and retries — it never cancels or claims another run, so the server's busy check stays the sole arbiter | `store/src/lib.rs` `managed_workstream_batches_are_idempotent_and_release_the_lease` (second prepare refused while active); `run.rs` `a_renewed_lease_is_reported_as_a_live_owner_not_taken_over` (renewing holder is reported, never displaced), with controls `interactive_launch_waits_out_a_lapsing_lease_then_proceeds` and `ctrl_c_aborts_the_held_lease_wait_immediately` | STRONG for exclusivity. The `lease_owner` label (`host:pid`) is informational only and not unique inside ai-jail (every jailed launcher reports `ai-sandbox:<ns-pid>`), so it must never become an ownership key |
+| 14 | Per-project authorization (#708) | `ai-memory-store/src/project_authz.rs` `authorize_project` / `ProjectAuthz::authorize` choke point (V68 `project_grants` + `projects.access_mode`, default `open`; V69 `projects.created_by` feeds `is_creator`); `scope.rs` `ScopeResolver::with_project_authz` (reader pool for reads, writer actor for writes) and its free forms `authorize_scope_for` / `*_guarded`, attached for every DB user by `ai-memory-mcp` `scope_resolver_as`, `ai-memory-web` `authorize_read` / `lookup_project`, and `ai-memory-hooks` (`grants.rs` `authorize_resolved` for run/workstream ids, the capture check in `router.rs`); read-shaped mutations resolve at `ProjectAccess::Write` (`resolve_existing_args(.., need)`); unscoped reads filtered before `LIMIT` by `reader.rs` `readable_repository_sql`; `WriterHandle::authorize_project` as defense in depth. Page ids are never taken from a caller (only derived from already-authorized hits), so there is no page-id entry point to guard; incremental `recent` resolves and authorizes the requested project before decoding its scope-bound cursor; batch outcomes do not bypass the capture grant or session owner check | `tests/suite/project_authz.rs` (decision matrix, ship-inert, resolver gate); `tests/suite/access_mode.rs` `every_caller_against_both_modes`, `a_restricted_project_admits_the_team_and_refuses_the_outsider`, `new_projects_follow_the_server_default_and_admit_their_creator`; `scope.rs` `the_argument_shape_does_not_decide_the_level`, `a_user_reaches_only_what_they_were_granted`, `creating_authorizes_against_a_project_that_already_exists`, `a_refused_scope_fails_the_search_instead_of_shortening_it`; `grants.rs` `search_finds_only_what_the_viewer_may_read`, `the_limit_counts_only_what_the_viewer_may_see`, `the_workspace_handoff_comes_only_from_readable_repositories`; `ai-memory-mcp` `server.rs` `a_reader_may_read_everything_and_change_nothing`, `bob_cannot_read_alices_page_in_a_restricted_project`, `bob_cannot_find_alices_page_by_searching_in_a_restricted_project`, `bob_cannot_consolidate_a_session_in_alices_repository`, `a_restricted_projects_queues_need_write`; `ai-memory-hooks` `a_capture_needs_writer_on_the_repository_it_lands_in`, `session_start_delivers_nothing_from_a_repository_the_viewer_cannot_read`, `run_and_workstream_ids_only_answer_someone_who_may_reach_the_repository`; `ai-memory-web` `web_reads_honour_grants_in_a_restricted_project`, `metadata_shows_only_what_the_viewer_may_read` — each with a granted or open-project control, and proven to fail with the choke point (18 tests) or the SQL filter (9 tests) neutralized; `routes.rs` `api_recent_incremental_rechecks_restricted_scope_on_cursor` (a valid cursor cannot bypass a revoked grant; granted control passes), `api_recent_incremental_paginates_over_120_pages_and_binds_cursor`; `mcp_stateless_http.rs` `generic_machine_client_writes_queries_and_claims_a_handoff` (real machine key, foreign scope and partial scope refused); `router.rs` `an_unauthorized_batch_item_is_consumed_rather_than_retried`, `batch_acknowledges_foreign_collision_then_commits_next_item` (refused foreign item followed by a legitimate stored item) | STRONG — slice 3 closed both bypass classes (unscoped reads, raw-id entry points) and added the root-only management surface. Out of scope by design: per-project administrators (granting/restricting is root-only), and access modes, creators and grants live only in SQLite, so `reindex` resets them |
| 14b | Repository identity routing (#708) | `ai-memory-store/src/ops.rs` `resolve_project_by_identity` — one transaction; an identity already on a project is never overwritten; an unclaimed project is claimed only when the capturing user may write it (the choke point's `resolve_project_authz` on the same transaction), otherwise it is returned unclaimed; a different identity under the same name splits into a new project with no shared `repo_path`; `ai-memory-hooks/src/router.rs` `cache_key_for` keys the path cache by identity too; `ai-memory-core/src/repository_identity.rs` strips credentials from remote URLs client-side, and the server accepts only the routing rungs (`explicit`, `git_remote`) from the wire | `tests/suite/identity_resolution.rs` `an_outsider_cannot_take_an_unclaimed_projects_identity` (control: `an_existing_project_is_claimed_in_place`), `two_unrelated_repositories_with_one_folder_name_stay_apart`, `a_created_or_split_project_admits_its_creator`; `router.rs` `one_path_with_two_remotes_is_two_projects`, `two_api_checkouts_with_different_remotes_get_two_projects` (a manifest rung on the wire is ignored); `repository_identity.rs` credential and normalisation tables — the claim guard and the cache key each proven to fail their test when removed | STRONG — first claimant wins: in a restricted workspace a user who creates a project under a remote identity first holds it until root grants others |
| 14c | Client-supplied event time is bounded and self-scoped (#919) | `ai-memory-hooks/src/payload.rs` `HookEnvelope::occurred_at_micros` — a `/hook` caller's optional `occurred_at` must be `> 0` and `<= now + 5min`; it only sets the caller's *own* admitted session's `started_at`/`ended_at`/`created_at`, never another session/project/user, and the ingest dedup `seen_at`/TTL stays on `now` | `payload.rs` `occurred_at_micros_rejects_a_far_future_timestamp`, `…_rejects_non_positive_values`, `…_rejects_garbage_strings` | MEDIUM — self-scoped numeric bound; no cross-tenant surface (a client already controls its own content) |
+| 14d | `include_related` shows and walks only readable projects (#708) | `ai-memory-store/src/reader.rs` `related_walk(.., viewer)` — both the outgoing and incoming hop queries carry `readable_repository_predicate("pg.project_id", viewer)`, the same far-end filter `page_links` applies, so a page in a project the viewer cannot read is neither returned nor expanded; `ai-memory-mcp/src/server.rs` `memory_read_page` passes `viewer_from_parts`, and the access bump only touches the filtered nodes | `related_walk.rs` `the_walk_hides_and_does_not_cross_projects_the_viewer_cannot_read` (an outgoing and an incoming neighbour in an ungranted restricted project are absent, and so is a granted page reachable only through one; control: a granted restricted project is shown, and no viewer walks the whole graph) — fails with the predicate removed; `ai-memory-mcp` `server.rs` `bob_does_not_see_restricted_pages_through_the_related_walk` (an ungranted user's `memory_read_page{include_related}` omits the restricted page; control: no viewer still reaches it) — fails with `memory_read_page` passing `None` instead of `viewer_from_parts` | STRONG |
## Keeping this current (the standing protocol)
diff --cc flake.nix
index aea314fe,ce69db44..c8317b9a
--- a/flake.nix
+++ b/flake.nix
@@@ -49,7 -50,249 +50,274 @@@
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";
+ };
+ };
++ localhostNoSecrets = mkNixos {
++ services.ai-memory = {
++ enable = true;
++ bind = "localhost";
++ };
++ };
++ withIpv6Loopback = mkNixos {
++ services.ai-memory = {
++ enable = true;
++ bind = "::1";
++ };
++ };
+ bothAgeAndSops = mkNixos {
+ services.ai-memory = {
+ enable = true;
+ ageSecret = "ai-memory-env";
+ sopsSecret = "ai-memory/env";
+ };
+ };
++ ageAndEnvironmentFile = mkNixos {
++ services.ai-memory = {
++ enable = true;
++ ageSecret = "ai-memory-env";
++ environmentFile = "/run/ai-memory/env";
++ };
++ };
+ secretsInSettings = mkNixos {
+ services.ai-memory = {
+ enable = true;
+ settings.auth.bearer_token = "sekrit";
+ };
+ };
++ headersInSettings = mkNixos {
++ services.ai-memory = {
++ enable = true;
++ settings.llm_headers = [ "Authorization: Bearer sekrit" ];
++ };
++ };
+ bindInSettings = mkNixos {
+ services.ai-memory = {
+ enable = true;
+ settings.bind = "0.0.0.0";
+ };
+ };
+ withCustomDataDir = mkNixos {
+ services.ai-memory = {
+ enable = true;
- dataDir = "/data/custom-ai-memory";
++ dataDir = "/data/custom ai-memory";
+ };
+ };
+ withFirewall = mkNixos {
+ services.ai-memory = {
+ enable = true;
+ openFirewall = true;
+ };
+ };
+ withLimits = mkNixos {
+ services.ai-memory = {
+ enable = true;
+ memoryMax = "2G";
+ tasksMax = 512;
+ };
+ };
+
+ failingAssertions = sys: lib.filter (a: !a.assertion) sys.config.assertions;
+ nonLoopbackFailing = failingAssertions nonLoopbackNoSecrets;
++ localhostFailing = failingAssertions localhostNoSecrets;
+ ageSopsFailing = failingAssertions bothAgeAndSops;
++ ageEnvironmentFailing = failingAssertions ageAndEnvironmentFile;
+ secretsFailing = failingAssertions secretsInSettings;
++ headersFailing = failingAssertions headersInSettings;
+ bindFailing = failingAssertions bindInSettings;
+
+ enabledSc = enabled.config.systemd.services.ai-memory.serviceConfig;
+ enabledUnit = enabled.config.systemd.services.ai-memory;
+ execStart = enabledSc.ExecStart;
+ settingsExec =
+ withSettings.config.systemd.services.ai-memory.serviceConfig.ExecStart;
++ ipv6Exec = withIpv6Loopback.config.systemd.services.ai-memory.serviceConfig.ExecStart;
+ ageUnit = withAge.config.systemd.services.ai-memory;
+ customSc = withCustomDataDir.config.systemd.services.ai-memory.serviceConfig;
- customTmpfiles = withCustomDataDir.config.systemd.tmpfiles.rules;
++ customTmpfiles = withCustomDataDir.config.systemd.tmpfiles.settings."10-ai-memory";
+ limitsSc = withLimits.config.systemd.services.ai-memory.serviceConfig;
+
+ # One NixOS system for the container smoke path. Building its
+ # docker-image tarball builds system.build.toplevel once; there is
+ # no separate bare-toplevel check that would rebuild the same closure.
+ containerNixos = nixpkgs.lib.nixosSystem {
+ system = "x86_64-linux";
+ modules = [
+ self.nixosModules.default
+ (
+ { modulesPath, pkgs, ... }:
+ {
+ imports = [ "${modulesPath}/virtualisation/docker-image.nix" ];
+ system.stateVersion = "25.05";
+ networking.hostName = "ai-memory";
+ # Slim the closure: docs are useless inside the smoke image.
+ documentation.enable = false;
+ documentation.doc.enable = false;
+ documentation.info.enable = false;
+ documentation.man.enable = false;
+ documentation.nixos.enable = false;
+ # In-container /healthz probe (docker published ports cannot
+ # reach the module's default 127.0.0.1 bind).
+ environment.systemPackages = [ pkgs.curl ];
+ services.ai-memory.enable = true;
+ }
+ )
+ ];
+ };
+
+ nixosAiMemoryDocker =
+ linuxPkgs.runCommand "nixos-ai-memory-docker"
+ {
+ meta.description = "NixOS rootfs tarball with services.ai-memory for systemd-in-container smoke tests";
+ passthru = {
+ toplevel = containerNixos.config.system.build.toplevel;
+ tarball = containerNixos.config.system.build.tarball;
+ imageName = "ai-memory-nixos-test";
+ };
+ }
+ ''
+ mkdir -p "$out"
+ # Building this derivation builds toplevel via the tarball dep —
+ # single closure path for CI (no duplicate bare-toplevel job).
+ ln -s ${containerNixos.config.system.build.tarball}/tarball/*.tar.xz \
+ "$out/rootfs.tar.xz"
+ ln -s ${containerNixos.config.system.build.toplevel} "$out/toplevel"
+ printf '%s\n' "ai-memory-nixos-test" > "$out/image-name"
+ '';
+
+ nixosChecks = {
+ nixos-module-eval =
+ assert lib.hasInfix "--enable-web" execStart;
+ assert lib.hasInfix "--bind 127.0.0.1:49374" execStart;
+ assert lib.hasInfix "--data-dir" execStart;
+ assert lib.hasInfix " serve " (" " + execStart + " ");
+ assert lib.hasInfix "--transport http" 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 enabledSc.StateDirectory == "ai-memory";
+ assert lib.elem "/var/lib/ai-memory" enabledSc.ReadWritePaths;
+ 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 nonLoopbackFailing != [ ];
+ assert lib.any (a: lib.hasInfix "non-loopback bind requires" a.message)
+ nonLoopbackFailing;
++ assert lib.any (a: lib.hasInfix "non-loopback bind requires" a.message)
++ localhostFailing;
++ assert lib.hasInfix "--bind [::1]:49374" ipv6Exec;
+ assert lib.any (a: lib.hasInfix "mutually exclusive" a.message) ageSopsFailing;
++ assert lib.any (a: lib.hasInfix "mutually exclusive" a.message)
++ ageEnvironmentFailing;
+ assert lib.any (a: lib.hasInfix "settings.auth must not contain secrets" a.message)
+ secretsFailing;
++ assert lib.any (a: lib.hasInfix "settings.llm_headers" a.message) headersFailing;
+ assert lib.any (a: lib.hasInfix "settings.bind is not allowed" a.message)
+ bindFailing;
+ assert (customSc.StateDirectory or null) == null;
- assert lib.elem "/data/custom-ai-memory" customSc.ReadWritePaths;
- assert lib.any (r: lib.hasPrefix "d /data/custom-ai-memory 0750 " r) customTmpfiles;
++ assert lib.elem "/data/custom ai-memory" customSc.ReadWritePaths;
++ assert customTmpfiles."/data/custom ai-memory".d.mode == "0750";
++ assert customTmpfiles."/data/custom ai-memory".d.user == "ai-memory";
++ assert lib.hasInfix "/data/custom\\x20ai-memory" customSc.ExecStart;
+ assert lib.elem "network.target" enabledUnit.after;
+ assert !(lib.elem "network-online.target" (enabledUnit.wants or [ ]));
+ assert lib.elem "network-online.target" ageUnit.after;
+ assert lib.elem "network-online.target" ageUnit.wants;
+ assert lib.elem 49374 withFirewall.config.networking.firewall.allowedTCPPorts;
+ assert limitsSc.MemoryMax == "2G";
+ assert limitsSc.TasksMax == 512;
+ 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 builtins.lessThan sandboxKeys
- == lib.sort builtins.lessThan enabledSandboxKeys;
- linuxPkgs.runCommand "ai-memory-nixos-sandbox-parity" { } "touch $out";
+ };
+ in
+ (flake-utils.lib.eachDefaultSystem (
system:
let
pkgs = import nixpkgs {
diff --cc nix/nixos-module.nix
index 00000000,2b711208..b5e3a0be
mode 000000,100644..100644
--- a/nix/nixos-module.nix
+++ b/nix/nixos-module.nix
@@@ -1,0 -1,317 +1,334 @@@
+ # 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, ... }:
++{ config, lib, pkgs, utils, ... }:
+
+ 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";
++ isLoopback = lib.elem cfg.bind [ "127.0.0.1" "::1" ];
++ bindHost = if lib.hasInfix ":" cfg.bind then "[${cfg.bind}]" else cfg.bind;
+
+ 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;
+
++ secretSourceCount = lib.count (source: source != null) [
++ cfg.ageSecret
++ cfg.sopsSecret
++ cfg.environmentFile
++ ];
++
+ secretKeysInSettings =
+ let
- auth = cfg.settings.auth or { };
++ auth = cfg.settings.auth or null;
+ in
- lib.filter (k: (auth.${k} or null) != null) [
++ lib.filter (k: auth != null && (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}"
++ "${bindHost}:${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.
++ `enableWeb` service options win over duplicate keys here. The generated
++ file is in the world-readable Nix store: never put credentials here,
++ including `llm_headers`; use `AI_MEMORY_LLM_HEADERS` in one of the
++ secret environment-file options instead.
+ '';
+ };
+
+ 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.
++ exclusive with `sopsSecret` and `environmentFile`. 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.
++ exclusive with `ageSecret` and `environmentFile`. 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.
++ On non-loopback the file must exist. Mutually exclusive with
++ `ageSecret` and `sopsSecret`; prefer those 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 = secretSourceCount <= 1;
++ message = "services.ai-memory: ageSecret, sopsSecret, and environmentFile 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.llm_headers or null) == null;
++ message =
++ "services.ai-memory.settings.llm_headers may contain credentials and must not enter the Nix store; use AI_MEMORY_LLM_HEADERS in 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.tmpfiles.settings."10-ai-memory"."${cfg.dataDir}".d = {
++ mode = "0750";
++ user = cfg.user;
++ group = 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;
++ ExecStart = utils.escapeSystemdExecArgs 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 --cc nix/settings-options.nix
index 00000000,48dd9060..6f94d5d5
mode 000000,100644..100644
--- a/nix/settings-options.nix
+++ b/nix/settings-options.nix
@@@ -1,0 -1,334 +1,61 @@@
-# Typed `services.ai-memory.settings` options mirroring config.toml.
-# Secrets belong in age/sops/environmentFile, not here.
++# A small discoverability layer for common non-secret config.toml keys.
++#
++# The parent submodule has `freeformType = pkgs.formats.toml.type`, so every
++# current and future config key remains usable without copying Config's full
++# Rust schema into Nix. Secrets belong in an environment file, never 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 {
++ auth = lib.mkOption {
+ type = types.nullOr (types.submodule {
++ # Keep unknown keys visible to the module's explicit secret-key
++ # assertion, which gives a useful refusal instead of a type error.
++ freeformType = types.attrsOf types.anything;
+ 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; };
- };
- });
++ secure_cookie = lib.mkOption {
++ type = types.nullOr types.bool;
+ 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 {
- # Freeform so a mistaken secret key reaches the module assertion
- # ("settings.auth must not contain secrets") instead of a generic
- # "option does not exist" type error.
- freeformType = types.attrsOf types.str;
- 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);
++ root_username = lib.mkOption {
++ type = types.nullOr 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.
++ Non-secret auth settings only. Use ageSecret, sopsSecret, or
++ environmentFile for bearer tokens, password material, and other
++ credentials.
+ '';
+ };
+ }
diff --cc nix/systemd-sandbox.nix
index 00000000,3d1ad552..61b5b303
mode 000000,100644..100644
--- a/nix/systemd-sandbox.nix
+++ b/nix/systemd-sandbox.nix
@@@ -1,0 -1,66 +1,34 @@@
-# 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.
++# Systemd hardening for the NixOS ai-memory service.
+ { 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 --cc scripts/test-nixos-systemd-container.sh
index 00000000,ad147c3f..d53dc9e2
mode 000000,100755..100755
--- a/scripts/test-nixos-systemd-container.sh
+++ b/scripts/test-nixos-systemd-container.sh
@@@ -1,0 -1,253 +1,253 @@@
+ #!/usr/bin/env bash
+ # Privileged NixOS systemd-in-container smoke for services.ai-memory.
+ #
+ # Builds (or reuses) packages.x86_64-linux.nixos-ai-memory-docker — a rootfs
+ # tarball derived from one NixOS system.build.toplevel — imports it into
+ # Docker/Podman, starts systemd as PID 1, and checks:
+ # - systemctl is-active ai-memory
+ # - curl /healthz inside the container (module default bind is loopback;
+ # Docker published ports hit eth0 and cannot reach 127.0.0.1)
+ # - a marker under /var/lib/ai-memory survives systemctl restart
+ # - optional: the same marker survives a recreate with a named volume
+ #
+ # Boot race: right after /init, /run/current-system/sw/bin is not linked yet.
+ # wait_for_exec_ready polls until systemctl is executable (stderr quiet during
+ # that window). Early OCI "systemctl: not found in $PATH" lines are boot lag,
+ # not a unit failure — they must not appear once readiness is explicit.
+ #
+ # Non-goals (do not extend this script for them):
+ # - A→B flake/package upgrade or SQLite-wiki migration matrices
+ # - Exhaustive settings-options.nix key coverage
+ # - Soft/fake systemd without a real unit start
+ # - Claiming the app Docker image covers the NixOS module path
-# - Re-asserting sandbox key parity (see nixos-sandbox-parity)
++# - Re-asserting every sandbox key (covered by module evaluation)
+
+ set -euo pipefail
+
+ IMAGE_NAME="${AI_MEMORY_NIXOS_TEST_IMAGE:-ai-memory-nixos-test}"
+ CONTAINER_NAME="${AI_MEMORY_NIXOS_TEST_CONTAINER:-ai-memory-nixos-systemd-test}"
+ VOLUME_NAME="${AI_MEMORY_NIXOS_TEST_VOLUME_NAME:-ai-memory-nixos-test-data}"
+ KEEP="${AI_MEMORY_NIXOS_TEST_KEEP:-0}"
+ # Default on: one volume remount persistence pass. Set 0 to skip.
+ TEST_VOLUME="${AI_MEMORY_NIXOS_TEST_VOLUME:-1}"
+ # Probed via docker exec against the unit's loopback bind (not host-mapped).
+ HEALTH_URL="http://127.0.0.1:49374/healthz"
+ DATA_DIR="/var/lib/ai-memory"
+ MARKER_PATH="${DATA_DIR}/.ai-memory-nixos-ci-marker"
+ MARKER_VALUE="nixos-container-smoke"
+
+ ENGINE=""
+ ROOTFS=""
+ BUILT_IMAGE=0
+ # docker import leaves no image ENV PATH. Inject the NixOS system bin dirs
+ # on every exec (nixpkgs docker-image.nix documents /run/current-system/…).
+ # Profile path covers the brief window before activation links current-system.
+ NIXOS_PATH="/run/current-system/sw/bin:/nix/var/nix/profiles/system/sw/bin:/bin"
+
+ log() {
+ printf '\n==> %s\n' "$*"
+ }
+
+ fail() {
+ printf 'error: %s\n' "$*" >&2
+ exit 1
+ }
+
+ ctr_exec() {
+ "${ENGINE}" exec -e "PATH=${NIXOS_PATH}" "${CONTAINER_NAME}" "$@"
+ }
+
+ ctr_exec_root() {
+ "${ENGINE}" exec -u root -e "PATH=${NIXOS_PATH}" "${CONTAINER_NAME}" "$@"
+ }
+
+ repo_root() {
+ local script_dir
+ script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+ cd "${script_dir}/.." && pwd
+ }
+
+ detect_engine() {
+ if [ -n "${AI_MEMORY_DOCKER:-}" ]; then
+ ENGINE="${AI_MEMORY_DOCKER}"
+ return 0
+ fi
+ if command -v docker >/dev/null 2>&1; then
+ ENGINE=docker
+ return 0
+ fi
+ if command -v podman >/dev/null 2>&1; then
+ ENGINE=podman
+ return 0
+ fi
+ fail "need docker or podman on PATH (or set AI_MEMORY_DOCKER)"
+ }
+
+ cleanup() {
+ if [ "${KEEP}" = "1" ]; then
+ log "Keeping container ${CONTAINER_NAME} (AI_MEMORY_NIXOS_TEST_KEEP=1)"
+ return 0
+ fi
+ if [ -n "${ENGINE}" ]; then
+ "${ENGINE}" rm -f "${CONTAINER_NAME}" >/dev/null 2>&1 || true
+ if [ "${TEST_VOLUME}" = "1" ]; then
+ "${ENGINE}" volume rm -f "${VOLUME_NAME}" >/dev/null 2>&1 || true
+ fi
+ if [ "${BUILT_IMAGE}" = "1" ] && [ "${KEEP}" != "1" ]; then
+ "${ENGINE}" rmi -f "${IMAGE_NAME}" >/dev/null 2>&1 || true
+ fi
+ fi
+ }
+
+ # Activation links /run/current-system a few seconds after /init. Until then,
+ # docker exec with NIXOS_PATH fails with OCI "executable file not found".
+ # Poll quietly; fail hard if PATH never appears.
+ wait_for_exec_ready() {
+ local i
+ for i in $(seq 1 120); do
+ if ctr_exec test -x /run/current-system/sw/bin/systemctl >/dev/null 2>&1; then
+ log "PATH ready (systemctl executable)"
+ return 0
+ fi
+ sleep 0.5
+ done
+ fail "timed out waiting for /run/current-system/sw/bin/systemctl (activation PATH never appeared)"
+ }
+
+ wait_for_http() {
+ local url="$1"
+ local i
+ for i in $(seq 1 120); do
+ if ctr_exec curl -fsS "${url}" >/dev/null 2>&1; then
+ return 0
+ fi
+ sleep 0.5
+ done
+ ctr_exec journalctl -u ai-memory --no-pager -n 120 >&2 || true
+ fail "timed out waiting for in-container ${url}"
+ }
+
+ wait_for_active() {
+ local i
+ for i in $(seq 1 120); do
+ if ctr_exec systemctl is-active --quiet ai-memory; then
+ return 0
+ fi
+ sleep 0.5
+ done
+ ctr_exec systemctl status ai-memory --no-pager >&2 || true
+ ctr_exec journalctl -u ai-memory --no-pager -n 120 >&2 || true
+ fail "timed out waiting for systemctl is-active ai-memory"
+ }
+
+ run_container() {
+ local extra_args=("$@")
+ # Privileged + host cgroup namespace: systemd as PID 1 on cgroup v2 hosts
+ # (including GitHub Actions ubuntu-latest) needs this to activate units.
+ # No -p: default --bind is 127.0.0.1; published ports never reach it.
+ "${ENGINE}" run -d --name "${CONTAINER_NAME}" \
+ --privileged \
+ --cgroupns=host \
+ -v /sys/fs/cgroup:/sys/fs/cgroup:rw \
+ "${extra_args[@]}" \
+ "${IMAGE_NAME}" /init
+ }
+
+ write_marker() {
+ # PATH is injected so chown/coreutils resolve after activation.
+ ctr_exec_root /bin/sh -c \
+ "printf '%s\n' '${MARKER_VALUE}' > '${MARKER_PATH}' && chown ai-memory:ai-memory '${MARKER_PATH}'"
+ }
+
+ assert_marker() {
+ local got
+ got="$(ctr_exec cat "${MARKER_PATH}")"
+ if [ "${got}" != "${MARKER_VALUE}" ]; then
+ fail "marker mismatch at ${MARKER_PATH}: expected '${MARKER_VALUE}', got '${got}'"
+ fi
+ }
+
+ smoke_once() {
+ wait_for_exec_ready
+
+ log "Waiting for ai-memory unit"
+ wait_for_active
+ ctr_exec systemctl is-active ai-memory
+
+ log "Waiting for in-container ${HEALTH_URL}"
+ wait_for_http "${HEALTH_URL}"
+ ctr_exec curl -fsS "${HEALTH_URL}" >/dev/null
+
+ log "Writing marker and restarting ai-memory"
+ write_marker
+ ctr_exec systemctl restart ai-memory
+ wait_for_active
+ wait_for_http "${HEALTH_URL}"
+ assert_marker
+ log "Marker survived systemctl restart"
+ }
+
+ main() {
+ detect_engine
+ trap cleanup EXIT
+
+ local root
+ root="$(repo_root)"
+ cd "${root}"
+
+ case "$(uname -s)-$(uname -m)" in
+ Linux-x86_64 | Linux-amd64) ;;
+ *)
+ fail "NixOS container smoke is Linux x86_64 only (got $(uname -s)-$(uname -m))"
+ ;;
+ esac
+
+ log "Building packages.x86_64-linux.nixos-ai-memory-docker"
+ nix build --print-build-logs '.#packages.x86_64-linux.nixos-ai-memory-docker'
+ ROOTFS="$(pwd)/result/rootfs.tar.xz"
+ if [ ! -e "${ROOTFS}" ]; then
+ fail "missing rootfs tarball at ${ROOTFS}"
+ fi
+ if [ -f "$(pwd)/result/image-name" ]; then
+ IMAGE_NAME="$(tr -d '[:space:]' <"$(pwd)/result/image-name")"
+ fi
+
+ cleanup
+ # Re-arm trap after cleanup cleared a previous container.
+ trap cleanup EXIT
+
+ log "Importing rootfs into ${ENGINE} as ${IMAGE_NAME}"
+ "${ENGINE}" import "${ROOTFS}" "${IMAGE_NAME}"
+ BUILT_IMAGE=1
+
+ log "Starting privileged NixOS container ${CONTAINER_NAME}"
+ run_container
+
+ smoke_once
+
+ if [ "${TEST_VOLUME}" = "1" ]; then
+ log "Recreating with named volume ${VOLUME_NAME} at ${DATA_DIR}"
+ "${ENGINE}" rm -f "${CONTAINER_NAME}" >/dev/null
+ "${ENGINE}" volume rm -f "${VOLUME_NAME}" >/dev/null 2>&1 || true
+ "${ENGINE}" volume create "${VOLUME_NAME}" >/dev/null
+
+ run_container -v "${VOLUME_NAME}:${DATA_DIR}"
+ wait_for_exec_ready
+ wait_for_active
+ wait_for_http "${HEALTH_URL}"
+ write_marker
+
+ log "Remounting volume and checking marker survival"
+ "${ENGINE}" rm -f "${CONTAINER_NAME}" >/dev/null
+ run_container -v "${VOLUME_NAME}:${DATA_DIR}"
+ wait_for_exec_ready
+ wait_for_active
+ wait_for_http "${HEALTH_URL}"
+ assert_marker
+ log "Marker survived volume remount"
+ fi
+
+ log "NixOS systemd container smoke passed"
+ }
+
+ main "$@"