Skip to content

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

Rust

feat(cli): P1.5 user subcommands + docs/users.md

AkitaOnRailsf6c7e270e46f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4320f1cc..24e9bf46 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,33 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
+- **Multi-user attribution (v0.8 Phase 1, rolling out across milestones
+ P1.1–P1.8).** ai-memory's data model stays single-tenant — every
+ authenticated request sees every page — but writes can now be
+ attributed to a named user. Five `ai-memory user` subcommands
+ (`add`, `list`, `expire`, `revive`, `rotate-token`) manage a `users`
+ table; the auth middleware resolves every request to one of four
+ tiers (Anonymous, Root, DB user, 401), injects an
+ `Extension<ActorContext>` + `Extension<AuthLevel>` for downstream
+ consumers, and gates the root-only admin user-management endpoints.
+ Tokens are 32 bytes of OS CSPRNG, stored only as
+ `SHA-256(token || ":" || token_pepper)` (per-server pepper from
+ `[auth].token_pepper`, auto-generated on `ai-memory init`); see
+ [`docs/users.md`](docs/users.md) for the SHA-256-not-argon2id
+ rationale, the four-rung auth ladder, and the backward-compat
+ migration for pre-v0.8 installs. New v0.8 fields on `[auth]`:
+ `root_username` / `root_email` / `root_name` (label for the bearer
+ token's writes) and `token_pepper`. Per-page `author_id` + web UI
+ surfacing lands in P1.6/P1.7; this milestone set ships P1.1
+ (`ActorContext` + `UserId` in core), P1.2 (table + writer/reader
+ ops + V14 migration), P1.3 (auth middleware), P1.4 (root-gated
+ `POST/GET /admin/users` + `…/expire|revive|rotate-token`), and P1.5
+ (CLI subcommands). **No behaviour change for existing single-user
+ installs**: without `[auth].token_pepper` the multi-user lookup
+ stays dormant, user-management endpoints 503 with a clear
+ `multi-user not enabled` message pointing at `ai-memory init`,
+ and the existing `bearer_token`-only flow keeps authenticating
+ exactly as before.
- **`memory_query { global: true }` — cross-project global search** that
reaches every project in every workspace in one call, with each hit
annotated by its workspace + project so the agent can tell where it
diff --git a/README.md b/README.md
index fbdf6625..ea9f0bf6 100644
--- a/README.md
+++ b/README.md
@@ -288,6 +288,17 @@ Bearer auth protects `/mcp`, `/hook`, `/handoff`, `/admin/*`, and
as the password. Non-loopback binds should also set
`AI_MEMORY_ALLOWED_HOSTS` to guard against DNS rebinding.
+**Multi-user attribution (v0.8, optional).** When more than one human
+shares a server, ai-memory can attribute each write to a named user.
+The bearer token continues to authenticate at the wire level; users
+created via `ai-memory user add` get their own tokens that resolve to
+their identity in audit logs (and, in subsequent milestones, page
+frontmatter + the web UI). Data stays single-tenant — there is no
+RBAC. Existing single-user installs are not affected unless you opt
+in by setting `[auth].token_pepper` (auto-generated for new installs
+by `ai-memory init`). See [`docs/users.md`](docs/users.md) for the
+full walkthrough and the four-rung auth ladder.
+
See [`docs/deploy.md`](docs/deploy.md) for the full homelab pattern
with bearer auth, host allowlisting, and TLS/reverse-proxy options.
@@ -445,6 +456,7 @@ diagram, crate breakdown, schema notes, and invariants.
| [`docs/windows.md`](docs/windows.md) | Windows install modes: full WSL2, native Windows with Docker Desktop, native source builds, and current hook/MCP harness caveats. |
| [`docs/mcp-install.md`](docs/mcp-install.md) | Per-client MCP and lifecycle notes (Cursor, Claude Desktop, Gemini CLI, Antigravity CLI, OpenClaw, OMP). |
| [`docs/deploy.md`](docs/deploy.md) | Homelab deploy: bin/deploy, bearer-token auth, TLS via cloudflared. |
+| [`docs/users.md`](docs/users.md) | **Multi-user attribution (v0.8).** Four-rung auth ladder, `ai-memory user add/list/expire/revive/rotate-token` walkthrough, backward-compat migration for pre-v0.8 installs, token storage rationale. |
| [`docs/lifecycle-ops.md`](docs/lifecycle-ops.md) | **Read before running purge / rename / backup / restore / reset.** Safety matrix for the state-touching commands, per-project disk layout (how isolation actually works), and operator workflows for "fresh start", "snapshot before risky op", "drop one project". |
| [`docs/llm-provider-comparison.md`](docs/llm-provider-comparison.md) | Empirical notes behind the recommended LLM defaults. |
| [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) | Operational summary: data flow, crate layout, cross-cutting invariants, schema. |
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 7ba84cb9..d47cb3dc 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -101,6 +101,108 @@ pub enum Command {
Uninstall(UninstallArgs),
/// Manage optional upstream LLM provider authentication.
Auth(AuthArgs),
+ /// Manage registered users for multi-user attribution. Each user
+ /// has a stable username, optional name + email, and one current
+ /// token. All subcommands require the root bearer token; non-root
+ /// requests get 403. Existing single-user installs unaffected —
+ /// these endpoints 503 until `[auth].token_pepper` is set
+ /// (auto-generated by `ai-memory init`).
+ User(UserArgs),
+}
+
+/// Arguments for `user`.
+#[derive(Debug, Args)]
+pub struct UserArgs {
+ /// User-management action to run.
+ #[command(subcommand)]
+ pub command: UserCommand,
+}
+
+/// Subcommands for `user`.
+#[derive(Debug, Subcommand)]
+pub enum UserCommand {
+ /// Create a new user and issue their initial token. The token is
+ /// printed to stdout exactly once — store it now; only its SHA-256
+ /// digest is kept in the DB.
+ Add(UserAddArgs),
+ /// List every registered user. Tokens are NEVER surfaced (the row
+ /// only stores the hash); the `expired` column shows whether the
+ /// user's token currently authenticates.
+ List(UserListArgs),
+ /// Expire the user's current token. Auth requests with that token
+ /// start returning 401 immediately. The user row stays put so
+ /// historical attribution references survive.
+ Expire(UserExpireArgs),
+ /// Re-activate a previously-expired token. No-op when the user's
+ /// token is already active.
+ Revive(UserReviveArgs),
+ /// Issue a fresh token, replacing the existing one. Implicitly
+ /// revives an expired user — rotating a token makes it usable
+ /// again. The new plaintext is printed exactly once.
+ RotateToken(UserRotateTokenArgs),
+}
+
+/// Arguments for `user add`.
+#[derive(Debug, Args)]
+pub struct UserAddArgs {
+ /// Stable username. Required. Validation rejects empty, internal
+ /// whitespace, control chars, and the path/quoting separators
+ /// `/ \ : ; , " ' \``. UTF-8 letters and emails-as-usernames
+ /// (alice@home) are allowed.
+ #[arg(long)]
+ pub username: String,
+ /// Display name (e.g. `"Alice Smith"`). Surfaced in the web UI +
+ /// `/api/v1` responses alongside the username. Internal whitespace
+ /// is fine — only the edges are trimmed.
+ #[arg(long)]
+ pub name: Option<String>,
+ /// Email. Basic validation: exactly one `@`, both sides non-empty,
+ /// no whitespace. Intranet-style addresses (`alice@home`) are
+ /// accepted. Lowercased before storage; case-insensitive unique.
+ #[arg(long)]
+ pub email: Option<String>,
+ /// Emit the response as JSON instead of human-readable text. The
+ /// token field is included in either case.
+ #[arg(long)]
+ pub json: bool,
+}
+
+/// Arguments for `user list`.
+#[derive(Debug, Args)]
+pub struct UserListArgs {
+ /// Emit the response as JSON instead of a human-readable table.
+ #[arg(long)]
+ pub json: bool,
+}
+
+/// Arguments for `user expire`.
+#[derive(Debug, Args)]
+pub struct UserExpireArgs {
+ /// Username to expire.
+ pub username: String,
+ /// Skip the interactive confirmation prompt.
+ #[arg(long)]
+ pub yes: bool,
+}
+
+/// Arguments for `user revive`.
+#[derive(Debug, Args)]
+pub struct UserReviveArgs {
+ /// Username to revive.
+ pub username: String,
+}
+
+/// Arguments for `user rotate-token`.
+#[derive(Debug, Args)]
+pub struct UserRotateTokenArgs {
+ /// Username to rotate.
+ pub username: String,
+ /// Skip the interactive confirmation prompt.
+ #[arg(long)]
+ pub yes: bool,
+ /// Emit the response as JSON instead of human-readable text.
+ #[arg(long)]
+ pub json: bool,
}
/// Arguments for `auth`.
diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rs
index 289cced8..dd85d022 100644
--- a/crates/ai-memory-cli/src/commands/mod.rs
+++ b/crates/ai-memory-cli/src/commands/mod.rs
@@ -32,6 +32,7 @@ pub mod serve;
pub mod setup_agent;
pub mod status;
pub mod uninstall;
+pub mod user;
pub mod write_page;
/// Resolve the effective project name for a client command.
diff --git a/crates/ai-memory-cli/src/commands/user.rs b/crates/ai-memory-cli/src/commands/user.rs
new file mode 100644
index 00000000..9200da03
--- /dev/null
+++ b/crates/ai-memory-cli/src/commands/user.rs
@@ -0,0 +1,339 @@
+//! `ai-memory user` — manage registered users for multi-user attribution.
+//!
+//! Thin HTTP client over the admin endpoints in
+//! `ai-memory-mcp::admin::handle_{create,list,expire,revive,
+//! rotate_token}_user`. Per invariant #16 (CLI is always a thin HTTP
+//! client) the CLI never opens the store; everything routes through
+//! `/admin/users/*`. The caller's bearer token must authenticate as
+//! root or the server returns 403 (User tier) / 401 (Anonymous).
+//!
+//! Backward compatibility: every install that predates v0.8 lacks the
+//! `[auth].token_pepper` field. The server's user-management routes
+//! 503 in that case with `multi-user not enabled (set
+//! [auth].token_pepper in config or run `ai-memory init`)`. Existing
+//! single-user installs see that error only if they actively try to
+//! use these subcommands — the rest of the CLI keeps working.
+
+use std::io::{self, BufRead, Write};
+
+use anyhow::{Context, Result, bail};
+use serde::{Deserialize, Serialize};
+
+use crate::cli::{
+ UserAddArgs, UserArgs, UserCommand, UserExpireArgs, UserListArgs, UserReviveArgs,
+ UserRotateTokenArgs,
+};
+use crate::config::Config;
+use crate::http_client::{ServerEndpoint, get_json, post_json};
+
+/// Mirrors `ai_memory_core::User` on the server side. Repeated here
+/// rather than imported to keep the CLI <-> server contract explicit
+/// at the deserialisation boundary (the CLI tolerates a future server
+/// that adds fields without a recompile).
+#[derive(Debug, Deserialize, Serialize)]
+struct UserRow {
+ id: String,
+ username: String,
+ #[serde(default)]
+ name: Option<String>,
+ #[serde(default)]
+ email: Option<String>,
+ created_at: i64,
+ #[serde(default)]
+ last_seen_at: Option<i64>,
+ #[serde(default)]
+ token_expired_at: Option<i64>,
+}
+
+impl UserRow {
+ fn is_token_active(&self) -> bool {
+ self.token_expired_at.is_none()
+ }
+}
+
+#[derive(Debug, Deserialize)]
+struct UserWithToken {
+ user: UserRow,
+ token: String,
+}
+
+#[derive(Debug, Deserialize)]
+struct UserList {
+ users: Vec<UserRow>,
+}
+
+/// Dispatch entry point for `ai-memory user <subcommand>`.
+///
+/// # Errors
+/// Returns an error if the HTTP call fails, the server returns non-2xx,
+/// or the response body can't be deserialised.
+pub async fn run(config: &Config, args: UserArgs) -> Result<()> {
+ let ep = ServerEndpoint::from_config(config);
+ match args.command {
+ UserCommand::Add(args) => add(&ep, args).await,
+ UserCommand::List(args) => list(&ep, args).await,
+ UserCommand::Expire(args) => expire(&ep, args).await,
+ UserCommand::Revive(args) => revive(&ep, args).await,
+ UserCommand::RotateToken(args) => rotate_token(&ep, args).await,
+ }
+}
+
+#[derive(Debug, Serialize)]
+struct CreateUserBody<'a> {
+ username: &'a str,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ name: Option<&'a str>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ email: Option<&'a str>,
+}
+
+async fn add(ep: &ServerEndpoint, args: UserAddArgs) -> Result<()> {
+ let body = CreateUserBody {
+ username: args.username.trim(),
+ name: args
+ .name
+ .as_deref()
+ .map(str::trim)
+ .filter(|s| !s.is_empty()),
+ email: args
+ .email
+ .as_deref()
+ .map(str::trim)
+ .filter(|s| !s.is_empty()),
+ };
+ let resp: UserWithToken = post_json(ep, "/admin/users", &body)
+ .await
+ .context("creating user")?;
+ if args.json {
+ println!(
+ "{}",
+ serde_json::to_string_pretty(&serde_json::json!({
+ "user": &resp.user,
+ "token": &resp.token
+ }))?
+ );
+ } else {
+ let mut stderr = io::stderr().lock();
+ let _ = writeln!(stderr, "✓ created user '{}'", resp.user.username);
+ if let Some(name) = &resp.user.name {
+ let _ = writeln!(stderr, " name: {name}");
+ }
+ if let Some(email) = &resp.user.email {
+ let _ = writeln!(stderr, " email: {email}");
+ }
+ let _ = writeln!(
+ stderr,
+ " id: {}\n\n\
+ Store this token now — it will NOT be shown again. \
+ Only its SHA-256 digest is kept in the DB.",
+ resp.user.id
+ );
+ // Token on stdout so it can be piped (`> ~/.config/...`) without
+ // the surrounding human chrome.
+ println!("{}", resp.token);
+ }
+ Ok(())
+}
+
+async fn list(ep: &ServerEndpoint, args: UserListArgs) -> Result<()> {
+ let resp: UserList = get_json(ep, "/admin/users", &[])
+ .await
+ .context("listing users")?;
+ if args.json {
+ println!("{}", serde_json::to_string_pretty(&resp.users)?);
+ return Ok(());
+ }
+ if resp.users.is_empty() {
+ println!("(no registered users)");
+ return Ok(());
+ }
+ // Fixed-width table — usernames are validated ≤ 64 chars in core,
+ // but most are short, so right-pad to the longest in this batch.
+ let user_w = resp
+ .users
+ .iter()
+ .map(|u| u.username.len())
+ .max()
+ .unwrap_or(8)
+ .max(8);
+ let name_w = resp
+ .users
+ .iter()
+ .filter_map(|u| u.name.as_ref().map(String::len))
+ .max()
+ .unwrap_or(4)
+ .max(4);
+ let email_w = resp
+ .users
+ .iter()
+ .filter_map(|u| u.email.as_ref().map(String::len))
+ .max()
+ .unwrap_or(5)
+ .max(5);
+
+ println!(
+ "{:<user_w$} {:<name_w$} {:<email_w$} {:<8}",
+ "USERNAME",
+ "NAME",
+ "EMAIL",
+ "STATUS",
+ user_w = user_w,
+ name_w = name_w,
+ email_w = email_w,
+ );
+ for u in &resp.users {
+ let status = if u.is_token_active() {
+ "active"
+ } else {
+ "expired"
+ };
+ println!(
+ "{:<user_w$} {:<name_w$} {:<email_w$} {:<8}",
+ u.username,
+ u.name.as_deref().unwrap_or("-"),
+ u.email.as_deref().unwrap_or("-"),
+ status,
+ user_w = user_w,
+ name_w = name_w,
+ email_w = email_w,
+ );
+ }
+ Ok(())
+}
+
+async fn expire(ep: &ServerEndpoint, args: UserExpireArgs) -> Result<()> {
+ if !args.yes {
+ confirm(&format!(
+ "Expire token for user '{}'? Their token stops authenticating immediately. (y/N) ",
+ args.username
+ ))?;
+ }
+ let path = format!("/admin/users/{}/expire", url_encode(&args.username));
+ // The server returns `{ user: UserRow }` but the CLI only needs to
+ // confirm a 2xx; ignore the payload.
+ let _: serde_json::Value = post_json(ep, &path, &serde_json::json!({}))
+ .await
+ .context("expiring user")?;
+ println!("✓ expired token for user '{}'", args.username);
+ Ok(())
+}
+
+async fn revive(ep: &ServerEndpoint, args: UserReviveArgs) -> Result<()> {
+ let path = format!("/admin/users/{}/revive", url_encode(&args.username));
+ let _: serde_json::Value = post_json(ep, &path, &serde_json::json!({}))
+ .await
+ .context("reviving user")?;
+ println!("✓ revived token for user '{}'", args.username);
+ Ok(())
+}
+
+async fn rotate_token(ep: &ServerEndpoint, args: UserRotateTokenArgs) -> Result<()> {
+ if !args.yes {
+ confirm(&format!(
+ "Rotate token for user '{}'? Any existing client using the old token will \
+ start getting 401 immediately. (y/N) ",
+ args.username
+ ))?;
+ }
+ let path = format!("/admin/users/{}/rotate-token", url_encode(&args.username));
+ let resp: UserWithToken = post_json(ep, &path, &serde_json::json!({}))
+ .await
+ .context("rotating user token")?;
+ if args.json {
+ println!(
+ "{}",
+ serde_json::to_string_pretty(&serde_json::json!({
+ "user": &resp.user,
+ "token": &resp.token
+ }))?
+ );
+ } else {
+ let mut stderr = io::stderr().lock();
+ let _ = writeln!(
+ stderr,
+ "✓ rotated token for user '{}'\n\n\
+ Store this token now — it will NOT be shown again.",
+ resp.user.username
+ );
+ println!("{}", resp.token);
+ }
+ Ok(())
+}
+
+/// Lightweight interactive y/N prompt. Reads from stdin; an empty
+/// reply, EOF, or anything starting with `n`/`N` aborts.
+fn confirm(prompt: &str) -> Result<()> {
+ let mut stderr = io::stderr().lock();
+ let _ = write!(stderr, "{prompt}");
+ let _ = stderr.flush();
+ drop(stderr);
+
+ let mut buf = String::new();
+ let n = io::stdin().lock().read_line(&mut buf)?;
+ if n == 0 {
+ bail!("aborted (no input)");
+ }
+ let trimmed = buf.trim();
+ if !trimmed.eq_ignore_ascii_case("y") && !trimmed.eq_ignore_ascii_case("yes") {
+ bail!("aborted");
+ }
+ Ok(())
+}
+
+/// Percent-encode a username for URL-path use. The validation in
+/// `core::user::validate_username` already excludes whitespace and the
+/// common path separators (`/ \ : ; ,`), and emails-as-usernames
+/// (`alice@home`) carry `@` which is reserved in paths. Conservative
+/// encode: anything that isn't alphanumeric / `-_.` becomes `%XX`.
+fn url_encode(s: &str) -> String {
+ let mut out = String::with_capacity(s.len());
+ for &b in s.as_bytes() {
+ if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.') {
+ out.push(b as char);
+ } else {
+ out.push_str(&format!("%{b:02X}"));
+ }
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn url_encode_passes_safe_chars_through() {
+ assert_eq!(url_encode("alice"), "alice");
+ assert_eq!(url_encode("user_1"), "user_1");
+ assert_eq!(url_encode("a.b-c"), "a.b-c");
+ }
+
+ #[test]
+ fn url_encode_percent_encodes_at_and_other_specials() {
+ assert_eq!(url_encode("alice@home"), "alice%40home");
+ // Validation forbids these but the encoder must still be safe
+ // if a future relaxation lets them through.
+ assert_eq!(url_encode("a/b"), "a%2Fb");
+ assert_eq!(url_encode("a b"), "a%20b");
+ }
+
+ #[test]
+ fn user_row_active_status_reflects_token_expired_at() {
+ let active = UserRow {
+ id: "x".into(),
+ username: "alice".into(),
+ name: None,
+ email: None,
+ created_at: 0,
+ last_seen_at: None,
+ token_expired_at: None,
+ };
+ assert!(active.is_token_active());
+
+ let expired = UserRow {
+ token_expired_at: Some(123),
+ ..active
+ };
+ assert!(!expired.is_token_active());
+ }
+}
diff --git a/crates/ai-memory-cli/src/main.rs b/crates/ai-memory-cli/src/main.rs
index 10c33823..865e0fe2 100644
--- a/crates/ai-memory-cli/src/main.rs
+++ b/crates/ai-memory-cli/src/main.rs
@@ -65,5 +65,6 @@ async fn main() -> Result<()> {
Command::RenameProject(args) => commands::rename_project::run(&config, args).await,
Command::Uninstall(args) => commands::uninstall::run(&config, args),
Command::Auth(args) => commands::auth::run(&config, args).await,
+ Command::User(args) => commands::user::run(&config, args).await,
}
}
diff --git a/docs/users.md b/docs/users.md
new file mode 100644
index 00000000..17056515
--- /dev/null
+++ b/docs/users.md
@@ -0,0 +1,254 @@
+# Multi-user attribution
+
+> **Status:** v0.8 (rolling out across Phase 1 milestones P1.1–P1.8).
+> This page documents what's already merged today; per-page
+> attribution + frontmatter `last_modified_by` (P1.6) and `/api/v1`
+> author surfacing (P1.7) ship in subsequent milestones.
+
+ai-memory is **single-tenant data** with **optional multi-user
+attribution**. Every authenticated request sees the same wiki pages —
+there is no RBAC, no per-user scoping, no group permissions. What
+multi-user mode adds is *who-did-this*: every write attributes to a
+named user, audit-log rows carry that identity, and the web UI can
+show "Last edited by Alice Smith" instead of the anonymous default.
+
+If you run ai-memory alone, you can skip this page — your install
+keeps working unchanged.
+
+## When to enable it
+
+You probably want multi-user mode when:
+
+- More than one human shares a single ai-memory server (a household,
+ a small team's homelab).
+- You want the audit log to record *who* made each write (e.g. to
+ trace `Codex` writes vs `Claude Code` writes vs hand-rolled CLI
+ calls).
+- You're planning to use the (deferred) admission webhook chain —
+ webhooks receive the actor identity in their payload.
+
+You probably **don't** need it when:
+
+- You're the sole human user of your install. Single-user mode
+ (`[auth].bearer_token` set, no `[auth].token_pepper`) is what
+ the project has shipped since v0.1 and continues to work
+ identically.
+- You need permissions / access control. v1 of ai-memory does
+ not implement RBAC by design (see
+ [`design-decisions.md`](design-decisions.md) §13). Attribution
+ records *who* did a write; it does not gate *whether* they
+ could.
+
+## The four resolution rungs
+
+Every HTTP request is resolved to one of four authentication tiers:
+
+| Rung | Trigger | What the request gets |
+|---|---|---|
+| **0 — Anonymous** | No `[auth].bearer_token` set. | Allowed, no identity. Same as pre-multi-user defaults. |
+| **1 — Root** | Bearer matches `[auth].bearer_token`. | Allowed as **root**. When `[auth].root_username` is set, writes attribute to that name; otherwise attribution stays anonymous. |
+| **2 — DB user** | Bearer doesn't match root, matches a `users.token_hash` row (via SHA-256 of token + `[auth].token_pepper`). | Allowed as **that user**. The audit log records the username/email/name. |
+| **3 — 401** | Bearer present but matches nothing. | Rejected. Closes the bypass — unknown bearers can't slip through as anonymous. |
+
+The rungs are sticky: a request is matched at the lowest tier that
+applies, never escalates. Root token always wins over any users-row
+collision; the two namespaces are intentionally distinct.
+
+## Quick start
+
+> Prerequisite: a fresh `ai-memory init`. Pre-v0.8 installs need
+> the [migration step](#migrating-an-existing-single-user-install)
+> below before any of these commands work.
+
+### 1. Set the root identity
+
+Edit your `config.toml` (typically `<data_dir>/config.toml` or
+`/etc/ai-memory/config.toml`) and uncomment the `root_*` lines in
+the `[auth]` block:
+
+```toml
+[auth]
+bearer_token = "<your-existing-token-or-a-fresh-one>"
+token_pepper = "<auto-generated-by-ai-memory-init>"
+
+root_username = "boss" # required for root attribution
+root_email = "[email protected]" # optional, surfaced in UIs
+root_name = "Boss" # optional, surfaced in UIs
+```
+
+`token_pepper` was auto-generated by `ai-memory init`; **do not
+change it after adding users** — rotating the pepper invalidates
+every existing token. The pepper is what makes a stolen `users`
+table useless to an offline attacker; an attacker with both the
+DB and the config has tokens at their disposal anyway, so the
+pepper's job is closed by the file-permission boundary.
+
+Restart `ai-memory serve` for the changes to take effect.
+
+### 2. Add another user
+
+Each `ai-memory user add` issues one token, printed **exactly
+once**. Only its SHA-256 digest is kept in the DB.
+
+```console
+$ AI_MEMORY_AUTH_TOKEN=<root-token> \
+ ai-memory user add --username alice --email alice@home --name "Alice Smith"
+
+✓ created user 'alice'
+ name: Alice Smith
+ email: alice@home
+ id: 01935a82-6f7a-7d22-b8c0-...
+
+Store this token now — it will NOT be shown again. Only its
+SHA-256 digest is kept in the DB.
+
+mYi3pq...<43-chars>...wKp2Ze
+```
+
+stderr carries the human chrome, stdout carries the bare token
+so you can pipe it (`> ~/.config/ai-memory/alice.token`).
+
+### 3. List users
+
+```console
+$ AI_MEMORY_AUTH_TOKEN=<root-token> ai-memory user list
+
+USERNAME NAME EMAIL STATUS
+alice Alice Smith alice@home active
+bob - bob@home active
+carol - - expired
+```
+
+The list never surfaces tokens — only their hashes are in the DB.
+
+### 4. Disable a token (without losing attribution history)
+
+`ai-memory user expire <username>` stamps `token_expired_at = now()`
+on the row. The user's bearer stops authenticating immediately, but
+the row stays put so historical `author_id` references in
+`audit_log` (and, after P1.6, in `pages`) keep resolving to their
+real names.
+
+```console
+$ ai-memory user expire alice
+Expire token for user 'alice'? Their token stops authenticating immediately. (y/N) y
+✓ expired token for user 'alice'
+```
+
+Pass `--yes` to skip the prompt (CI / scripts).
+
+To re-enable later: `ai-memory user revive alice`.
+
+### 5. Rotate a leaked / lost token
+
+```console
+$ ai-memory user rotate-token alice
+Rotate token for user 'alice'? Any existing client using the old token will start getting 401 immediately. (y/N) y
+✓ rotated token for user 'alice'
+
+Store this token now — it will NOT be shown again.
+
+XGqsBp...<43-chars>...zRm0Vt
+```
+
+Rotation implicitly revives an expired token — you can recover an
+offboarded user without first running `revive`.
+
+## Backward compatibility
+
+If you're upgrading from a pre-v0.8 ai-memory:
+
+- **No action is required.** Your existing
+ `[auth].bearer_token`-only setup continues to authenticate
+ exactly as before. The auth middleware just stamps an anonymous
+ `ActorContext` and your audit log records the same shape it did
+ before.
+- The `users` table is added by migration V14 and stays empty
+ until you actively run `ai-memory user add`. SQL queries against
+ it return no rows; the rest of the schema is unchanged.
+- Multi-user mode requires `[auth].token_pepper`. Without it, the
+ user-management endpoints return **503** with a clear
+ `multi-user not enabled` message. Existing installs never trip
+ this because they never call `user add`.
+
+### Migrating an existing single-user install
+
+`ai-memory init` is idempotent and won't overwrite a config it
+finds. To populate `token_pepper` without losing your current
+config:
+
+1. **Back up the existing config** (`cp config.toml config.toml.bak`).
+2. **Generate a pepper**: `ai-memory generate-auth-token 32` — this
+ prints a hex string of the same shape `init` would have
+ generated.
+3. **Add the `[auth]` block** to your `config.toml`:
+
+ ```toml
+ [auth]
+ # ... your existing settings (bearer_token, etc.) ...
+ token_pepper = "<paste-the-generated-pepper-here>"
+ root_username = "boss" # optional; enables root-token attribution
+ root_email = "boss@..." # optional
+ root_name = "Boss" # optional
+ ```
+
+4. Restart `ai-memory serve`. The new fields are picked up; existing
+ behaviour is unchanged.
+
+You can defer steps 3-4 indefinitely — `bearer_token` alone keeps
+working as it always has.
+
+## How tokens are stored
+
+- 32 bytes of OS CSPRNG, URL-safe-base64-encoded → 43-character
+ string.
+- DB column `users.token_hash` stores `SHA-256(token || ":" ||
+ token_pepper)`, never the plaintext.
+- The per-server `token_pepper` makes a DB-only theft (e.g. a
+ copied SQLite file) useless to an offline attacker: the search
+ space for the unpeppered hash is `(token, pepper)` jointly.
+- Constant-time comparison (`subtle::ConstantTimeEq`) on the hash
+ side-steps timing attacks against the lookup path.
+
+We deliberately **don't** use argon2id here even though it would be
+the textbook choice. Tokens are 256-bit CSPRNG, so brute force is
+infeasible regardless of hash strength; argon2id's per-hash salt
+would force O(N) scans on every auth request, where SHA-256 +
+`UNIQUE` index gives us the O(1) lookup the hot path needs.
+See `crates/ai-memory-store/src/users.rs` for the full rationale.
+
+## Where attribution shows up (today and soon)
+
+| Surface | Status |
+|---|---|
+| Auth middleware injects `Extension<ActorContext>` on every request | ✓ shipping in P1.3 |
+| Admin user-management routes gate on `Extension<AuthLevel>::Root` | ✓ shipping in P1.4 |
+| `ai-memory user add/list/expire/revive/rotate-token` CLI | ✓ shipping in P1.5 |
+| `audit_log.author_id` populated on every write | ⏳ lands in P1.6 |
+| `pages.author_id` populated, frontmatter `last_modified_by` block | ⏳ lands in P1.6 |
+| `/api/v1` page responses include `author: { username, name?, email? }` | ⏳ lands in P1.7 |
+| Web UI shows author on page view + list views | ⏳ lands in P1.7 |
+| `install-hooks --as-user <name>` stamps per-user token into hook scripts | ⏳ lands in P1.8 |
+
+This page is updated as each milestone merges; commit ids are
+recorded in `CHANGELOG.md`.
+
+## Limitations
+
+- **No RBAC.** Every authenticated user sees every page in the
+ workspace. If you need data isolation, run separate ai-memory
+ servers (per-user data dirs) and front them with a reverse
+ proxy.
+- **One token per user.** Rotation issues a new token and
+ invalidates the old in the same transaction. There's no
+ notion of multiple device-bound tokens per user.
+- **Root token is single.** `[auth].bearer_token` is a single
+ scalar. If you want multiple "admin"-class users, add them via
+ `user add` and accept that they currently have the same
+ capabilities as the root token for everything *except*
+ user-management endpoints, which stay root-only.
+- **No federation / OIDC / OAuth.** Per
+ [`design-decisions.md`](design-decisions.md) §13, ai-memory v1
+ stays self-contained. If you need SSO, terminate it at a
+ reverse proxy and configure the proxy to inject
+ `Authorization: Bearer <root-token>`.