Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(install-hooks): P1.8 --as-user metadata + finalised docs
AkitaOnRailsdffa96155f44
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex d47cb3dc..a611ac09 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -756,6 +756,27 @@ pub struct InstallHooksArgs {/// is set there. Generate one with `ai-memory generate-auth-token`.#[arg(long, hide_env_values = true)]pub auth_token: Option<String>,+ /// **Multi-user attribution (P1.8)**: stamp the installed hooks+ /// with this username so the operator + the hook scripts both+ /// know which registered user (from `ai-memory user add`) the+ /// install is for. This flag is metadata — the actual token+ /// stamped into the hook env block is whatever you pass via+ /// `--auth-token`. Recommended workflow:+ ///+ /// ```bash+ /// # 1. create the user (prints the token once)+ /// ai-memory user add --username alice --email alice@home+ ///+ /// # 2. wire alice's token into the agent's hooks+ /// ai-memory install-hooks --apply --agent claude-code \+ /// --as-user alice --auth-token <alice-token>+ /// ```+ ///+ /// Without this flag, hooks are installed anonymously (same as+ /// pre-v0.8 behaviour) — every write attributed to "anonymous"+ /// or to `[auth].root_username` when the root token is reused.+ #[arg(long)]+ pub as_user: Option<String>,/// **Mutate** the selected agent's hook config in place instead of/// printing the snippet/plugin. Idempotent — replaces the ai-memory/// hook entries or generated plugin and preserves unrelated configdiff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex 1f377d7d..31b9e634 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -108,6 +108,18 @@ pub fn run(config: &Config, args: InstallHooksArgs) -> Result<()> {.or_else(|| config.auth.bearer_token.clone()).or_else(|| inferred.as_ref().and_then(|mcp| mcp.auth_token.clone()));let auth = auth_token_owned.as_deref();+ // P1.8 multi-user attribution: `--as-user` is metadata only — the+ // token stamped into the hook env block is whatever the operator+ // passed via `--auth-token` (typically the per-user token from+ // `ai-memory user add`). We surface the username to stderr so the+ // operator can confirm which identity their writes will attribute+ // to. Mismatch between `--as-user` and the actual token's owner is+ // the operator's concern; we don't reach back to the server to+ // verify (keeps install-hooks offline-capable).+ validate_as_user(args.as_user.as_deref(), auth)?;+ if let Some(user) = args.as_user.as_deref().filter(|s| !s.trim().is_empty()) {+ eprintln!("[ai-memory] hooks installing for user: {user}");+ }if args.apply {return match args.agent {AgentChoice::OpenCode => apply_to_opencode_plugin(&server_url, auth, &args),@@ -171,6 +183,30 @@ struct InferredMcpConfig {auth_token: Option<String>,}+/// Reject `--as-user X` without a usable `--auth-token`. P1.8+/// metadata flag — without a token, the hook scripts would still+/// authenticate anonymously (or as root if the operator reused the+/// config bearer), so the `--as-user X` label would be misleading.+/// Trims whitespace; empty / whitespace-only `--as-user` is treated+/// as not-set so an accidental `--as-user ""` doesn't bail.+///+/// # Errors+/// Returns an error when `as_user` is set but `auth_token` is `None`+/// (or whitespace-only). The error message names the user so+/// operators see which arg they meant to pair with `--auth-token`.+fn validate_as_user(as_user: Option<&str>, auth_token: Option<&str>) -> Result<()> {+ let Some(user) = as_user.map(str::trim).filter(|s| !s.is_empty()) else {+ return Ok(());+ };+ if auth_token.map(str::trim).is_none_or(str::is_empty) {+ anyhow::bail!(+ "--as-user '{user}' requires --auth-token \+ (the token printed by `ai-memory user add --username {user}`)"+ );+ }+ Ok(())+}+fn effective_hook_server_url(config: &Config,args: &InstallHooksArgs,@@ -1588,11 +1624,53 @@ mod tests {hooks_dir: None,server_url: DEFAULT_SERVER_URL.into(),auth_token: None,+ as_user: None,apply: true,config_file: None,}}+ // ── P1.8 validate_as_user ────────────────────────────────────────++ /// No `--as-user` at all → always OK.+ #[test]+ fn validate_as_user_passes_when_not_set() {+ assert!(validate_as_user(None, None).is_ok());+ assert!(validate_as_user(None, Some("tok")).is_ok());+ }++ /// Empty / whitespace-only `--as-user` is treated as not-set.+ /// Defensive: an accidental `--as-user ""` shouldn't bail.+ #[test]+ fn validate_as_user_treats_blank_as_unset() {+ assert!(validate_as_user(Some(""), None).is_ok());+ assert!(validate_as_user(Some(" "), None).is_ok());+ }++ /// `--as-user` with no `--auth-token` is the error case the v0.8+ /// docs warn about — without a token the hook scripts authenticate+ /// anonymously / as root, making the `--as-user X` label misleading.+ #[test]+ fn validate_as_user_bails_without_auth_token() {+ let err = validate_as_user(Some("alice"), None).unwrap_err();+ let msg = format!("{err:#}");+ assert!(+ msg.contains("--as-user 'alice'") && msg.contains("--auth-token"),+ "error must name both flags: {msg}"+ );+ // Empty auth token is treated the same as missing.+ assert!(validate_as_user(Some("alice"), Some("")).is_err());+ assert!(validate_as_user(Some("alice"), Some(" ")).is_err());+ }++ /// `--as-user X --auth-token <something>` passes — the install+ /// proceeds with X as metadata and the supplied token as the+ /// bearer.+ #[test]+ fn validate_as_user_passes_with_both_flags() {+ assert!(validate_as_user(Some("alice"), Some("some-token")).is_ok());+ }+#[test]fn hook_server_url_defaults_to_configured_server_url() {let config = Config {@@ -2097,6 +2175,7 @@ model = "gpt-5"hooks_dir: None,server_url: "http://127.0.0.1:49374".into(),auth_token: None,+ as_user: None,apply: true,config_file: Some(tmp.path().join("extensions").join("ai-memory.ts")),};diff --git a/docs/users.md b/docs/users.mdindex 17056515..28e59a41 100644--- a/docs/users.md+++ b/docs/users.md@@ -217,21 +217,54 @@ 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)+## Where attribution shows up| 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`.+| Auth middleware injects `Extension<ActorContext>` on every request | ✓ P1.3 |+| Admin user-management routes gate on `Extension<AuthLevel>::Root` | ✓ P1.4 |+| `ai-memory user add/list/expire/revive/rotate-token` CLI | ✓ P1.5 |+| `pages.author_id` populated, frontmatter `last_modified_by` block | ✓ P1.6 |+| `/api/v1` page responses include `author: { username, name?, email? }` | ✓ P1.7 |+| ETag invalidation on author change (so caches refresh attribution) | ✓ P1.7 |+| `install-hooks --as-user <name>` metadata + flag validation | ✓ P1.8 |+| Web UI shows author on page view + list views | ⏳ follow-up commit (data is already on `/api/v1`) |+| `audit_log.author_id` populated on every write | ⏳ deferred (touches many ops; planned for next round) |++Commit ids for each milestone are recorded in `CHANGELOG.md`.++## Wiring agent hooks to a specific user++After `ai-memory user add` prints a user's token, point that user's+agent install at it via `install-hooks`:++```console+$ ai-memory user add --username alice --email alice@home --name "Alice Smith"+✓ created user 'alice'+ name: Alice Smith+ email: alice@home+ ...++XGq...<43-chars>...zRm # the token, stdout only++$ ai-memory install-hooks --apply --agent claude-code \+ --as-user alice --auth-token XGq...<43-chars>...zRm+[ai-memory] hooks installing for user: alice+✓ staged 5 hook script(s) → ...+```++`--as-user` is **metadata only**: it labels the install for the+operator's records and prints a confirmation line so you can verify+which identity the next session's writes will attribute to. The+actual token wired into the hook env block is whatever you pass via+`--auth-token`. Mismatching the two (e.g. `--as-user alice+--auth-token <bob's token>`) is permitted at the CLI layer; the+server will resolve to bob at runtime. The flag is there to keep the+operator honest, not to enforce.++Without `--as-user`, hooks install the same way they always have —+the bearer authenticates, attribution flows from the token's owner+(root user or DB user) at write time.## Limitations