Skip to content

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

Rust
20.2 KB
Raw Blame
//! `ai-memory profile` — inspect and curate the cross-project profile
//! (`docs/cross-project-profile.md`).
//!
//! Thin HTTP client: `status`, `list`, `review` and `apply` read
//! `/admin/profile/*` and `rebuild` posts to it; `show` and `forget` resolve
//! the profile's scope through `status` and then use the ordinary
//! `/admin/read-page` and `/admin/delete-page`, so a profile entry is read and
//! removed exactly like any other page. `apply` is the only command that
//! writes a local file: the managed block of the repository's rules file.

use std::path::{Path, PathBuf};

use anyhow::{Context, Result, bail};
use serde::Deserialize;

use super::apply_shared::{PrivateBackup, apply_atomic_with_backup, checkout_backup_stem};
use crate::cli::{ProfileApplyArgs, ProfileArgs, ProfileCommand, ProfileScopeArgs};
use crate::config::Config;
use crate::http_client::{ServerEndpoint, get_json, post_json};

/// Dispatch a `profile` subcommand.
///
/// # Errors
/// Transport failures, a non-root token on a multi-user server, or an entry
/// that does not exist.
pub async fn run(config: &Config, args: ProfileArgs) -> Result<()> {
    let ep = ServerEndpoint::from_config_resolving_auth(config).await;
    match args.command {
        ProfileCommand::Status(scope) => status(&ep, &scope).await,
        ProfileCommand::List(scope) => list(&ep, &scope).await,
        ProfileCommand::Show { path, scope } => show(&ep, &scope, &path).await,
        ProfileCommand::Forget { path, scope } => forget(&ep, &scope, &path).await,
        ProfileCommand::Review(scope) => review(&ep, &scope).await,
        ProfileCommand::Rebuild => rebuild(&ep).await,
        ProfileCommand::Apply(args) => apply(&ep, config, &args).await,
    }
}

#[derive(Debug, Deserialize)]
struct ScopeNames {
    workspace: String,
    project: String,
}

#[derive(Debug, Deserialize)]
struct StatusResponse {
    enabled: String,
    share: String,
    effective_share: Option<String>,
    distinguishes_operators: bool,
    min_projects: u32,
    inject_on_session_start: bool,
    digest_max_bytes: usize,
    baseline_max_bytes: usize,
    apply_max_lines: usize,
    llm: bool,
    scope: Option<ScopeNames>,
    entries: usize,
    digest_bytes: usize,
    contribute_opt_outs: Vec<ScopeNames>,
}

fn scope_query(scope: &ProfileScopeArgs) -> Vec<(&'static str, &str)> {
    let mut query = vec![("workspace", scope.workspace.as_str())];
    if let Some(user) = scope.user.as_deref() {
        query.push(("user", user));
    }
    query
}

async fn fetch_status(ep: &ServerEndpoint, scope: &ProfileScopeArgs) -> Result<StatusResponse> {
    get_json(ep, "/admin/profile/status", &scope_query(scope))
        .await
        .context("reading the profile status")
}

async fn status(ep: &ServerEndpoint, scope: &ProfileScopeArgs) -> Result<()> {
    let s = fetch_status(ep, scope).await?;
    let deployment = if s.distinguishes_operators {
        "multi-user"
    } else {
        "single-user"
    };
    match s.effective_share.as_deref() {
        Some(share) => println!("Profile: on ({share}; {deployment} server)"),
        None => println!("Profile: off ({deployment} server)"),
    }
    println!("  enabled = {}, share = {}", s.enabled, s.share);
    match &s.scope {
        Some(names) => println!(
            "  scope: {}/{} — {} entr{}, digest {} of {} bytes",
            names.workspace,
            names.project,
            s.entries,
            if s.entries == 1 { "y" } else { "ies" },
            s.digest_bytes,
            s.digest_max_bytes
        ),
        None if s.effective_share.as_deref() == Some("user") && scope.user.is_none() => {
            println!("  scope: one private profile per user; pass --user <name> to inspect one");
        }
        None if s.effective_share.is_some() => {
            println!("  scope: no profile entries yet");
        }
        None => {}
    }
    println!(
        "  digest at session start: {} (baseline for new projects: {} bytes)",
        if s.inject_on_session_start {
            "on"
        } else {
            "off"
        },
        s.baseline_max_bytes
    );
    println!(
        "  min_projects = {}, apply_max_lines = {}, llm = {}",
        s.min_projects, s.apply_max_lines, s.llm
    );
    if s.contribute_opt_outs.is_empty() {
        println!("  every project contributes");
    } else {
        println!("  projects that opted out ([profile] contribute = false):");
        for p in &s.contribute_opt_outs {
            println!("    {}/{}", p.workspace, p.project);
        }
    }
    Ok(())
}

#[derive(Debug, Deserialize)]
struct ListEntry {
    path: String,
    statement: String,
    applies_to: Vec<String>,
    enforced_by: bool,
}

#[derive(Debug, Deserialize)]
struct ListResponse {
    scope: Option<ScopeNames>,
    entries: Vec<ListEntry>,
}

async fn list(ep: &ServerEndpoint, scope: &ProfileScopeArgs) -> Result<()> {
    let resp: ListResponse = get_json(ep, "/admin/profile/list", &scope_query(scope))
        .await
        .context("listing the profile")?;
    let Some(names) = resp.scope else {
        println!("No profile entries yet.");
        return Ok(());
    };
    println!("{}/{}:", names.workspace, names.project);
    for entry in &resp.entries {
        let applies = if entry.applies_to.is_empty() {
            String::new()
        } else {
            format!(" [{}]", entry.applies_to.join(", "))
        };
        let enforced = if entry.enforced_by {
            " (enforced elsewhere; not in the digest)"
        } else {
            ""
        };
        println!("  {}{applies}{enforced}", entry.path);
        println!("      {}", entry.statement);
    }
    Ok(())
}

/// A profile path as the user may type it: with or without `profile/`.
fn profile_path(raw: &str) -> String {
    let raw = raw.trim().trim_start_matches('/');
    if raw.starts_with(ai_memory_core::profile::PROFILE_PATH_PREFIX) {
        raw.to_owned()
    } else {
        format!("{}{raw}", ai_memory_core::profile::PROFILE_PATH_PREFIX)
    }
}

async fn profile_scope(ep: &ServerEndpoint, scope: &ProfileScopeArgs) -> Result<ScopeNames> {
    let s = fetch_status(ep, scope).await?;
    match s.scope {
        Some(names) => Ok(names),
        None if s.effective_share.is_none() => bail!("the profile is off on this server"),
        None if s.effective_share.as_deref() == Some("user") && scope.user.is_none() => {
            bail!("this server keeps one profile per user; pass --user <name>")
        }
        None => bail!("there are no profile entries yet"),
    }
}

#[derive(Debug, Deserialize)]
struct PageContent {
    path: String,
    body: String,
}

async fn show(ep: &ServerEndpoint, scope: &ProfileScopeArgs, path: &str) -> Result<()> {
    let names = profile_scope(ep, scope).await?;
    let path = profile_path(path);
    let page: PageContent = get_json(
        ep,
        "/admin/read-page",
        &[
            ("workspace", names.workspace.as_str()),
            ("project", names.project.as_str()),
            ("path", path.as_str()),
        ],
    )
    .await
    .with_context(|| format!("reading {path}"))?;
    println!("# {} ({}/{})\n", page.path, names.workspace, names.project);
    println!("{}", page.body);
    Ok(())
}

#[derive(Debug, Deserialize)]
struct DeleteResponse {
    path: String,
    deleted: bool,
}

async fn forget(ep: &ServerEndpoint, scope: &ProfileScopeArgs, path: &str) -> Result<()> {
    let names = profile_scope(ep, scope).await?;
    let path = profile_path(path);
    let resp: DeleteResponse = post_json(
        ep,
        "/admin/delete-page",
        &serde_json::json!({
            "workspace": names.workspace,
            "project": names.project,
            "path": path,
        }),
    )
    .await
    .with_context(|| format!("forgetting {path}"))?;
    if resp.deleted {
        println!("Forgot {} (the git history keeps it).", resp.path);
    } else {
        println!("{} was not in the profile; nothing changed.", resp.path);
    }
    Ok(())
}

#[derive(Debug, Deserialize)]
struct ReviewEntry {
    path: String,
    statement: String,
    projects: Option<u64>,
    confidence: Option<f64>,
    last_seen: Option<String>,
    managed: bool,
    #[serde(default)]
    evidence: serde_json::Value,
}

#[derive(Debug, Deserialize)]
struct WaitingGroup {
    statement: String,
    projects: usize,
    needs: usize,
    #[serde(default)]
    contributors_needed: usize,
}

#[derive(Debug, Deserialize)]
struct ReviewResponse {
    share: Option<String>,
    entries: Vec<ReviewEntry>,
    waiting: Vec<WaitingGroup>,
    pending_updates: Vec<String>,
    hand_edited: Vec<String>,
    forgotten: Vec<String>,
}

async fn review(ep: &ServerEndpoint, scope: &ProfileScopeArgs) -> Result<()> {
    let r: ReviewResponse = get_json(ep, "/admin/profile/review", &scope_query(scope))
        .await
        .context("reviewing the profile")?;
    let Some(share) = r.share else {
        println!("The profile is off on this server.");
        return Ok(());
    };
    println!(
        "Profile ({share}): {} entr{}",
        r.entries.len(),
        if r.entries.len() == 1 { "y" } else { "ies" }
    );
    for entry in &r.entries {
        let mut facts = Vec::new();
        if let Some(n) = entry.projects {
            facts.push(format!("{n} project{}", if n == 1 { "" } else { "s" }));
        }
        if let Some(c) = entry.confidence {
            facts.push(format!("confidence {c:.2}"));
        }
        if let Some(seen) = &entry.last_seen {
            facts.push(format!("last seen {seen}"));
        }
        facts.push(if entry.managed {
            "harvested".into()
        } else {
            "yours (never rewritten)".into()
        });
        println!("  {}  [{}]", entry.path, facts.join(", "));
        println!("      {}", entry.statement);
        if let Some(items) = entry.evidence.as_array() {
            for item in items.iter().take(3) {
                let quote = item
                    .get("quote")
                    .and_then(serde_json::Value::as_str)
                    .unwrap_or("");
                let project = item
                    .get("project")
                    .and_then(serde_json::Value::as_str)
                    .unwrap_or("");
                println!("        \"{quote}\" ({project})");
            }
        }
    }
    if !r.pending_updates.is_empty() {
        println!("Next pass will update: {}", r.pending_updates.join(", "));
    }
    if !r.waiting.is_empty() {
        println!("Not in the profile yet (needs more projects, or say it as a general rule):");
        for group in &r.waiting {
            let people = if group.contributors_needed > 0 {
                format!(
                    ", {} more operator{} needed for a team profile",
                    group.contributors_needed,
                    if group.contributors_needed == 1 {
                        ""
                    } else {
                        "s"
                    }
                )
            } else {
                String::new()
            };
            println!(
                "  {} ({} project{}, {} more needed{people})",
                group.statement,
                group.projects,
                if group.projects == 1 { "" } else { "s" },
                group.needs
            );
        }
    }
    if !r.hand_edited.is_empty() {
        println!("Edited by hand, left alone: {}", r.hand_edited.join(", "));
    }
    if !r.forgotten.is_empty() {
        println!(
            "Forgotten, stays out until you say it again: {}",
            r.forgotten.join(", ")
        );
    }
    println!(
        "Fix a wrong entry: `ai-memory profile forget <path>`; reword it by editing the page (it then stays yours)."
    );
    Ok(())
}

#[derive(Debug, Deserialize)]
struct RebuildReport {
    share: Option<String>,
    projects_harvested: usize,
    candidates_added: usize,
    entries_written: usize,
    entries_unchanged: usize,
    skipped_manual: Vec<String>,
    llm_calls: usize,
    llm_fallbacks: usize,
    errors: Vec<String>,
}

async fn rebuild(ep: &ServerEndpoint) -> Result<()> {
    let r: RebuildReport = post_json(ep, "/admin/profile/rebuild", &serde_json::json!({}))
        .await
        .context("rebuilding the profile")?;
    println!(
        "Rebuilt the {} profile: read {} project{}, {} new candidate{}, {} entr{} written, {} unchanged.",
        r.share.as_deref().unwrap_or("?"),
        r.projects_harvested,
        if r.projects_harvested == 1 { "" } else { "s" },
        r.candidates_added,
        if r.candidates_added == 1 { "" } else { "s" },
        r.entries_written,
        if r.entries_written == 1 { "y" } else { "ies" },
        r.entries_unchanged
    );
    if r.llm_calls > 0 || r.llm_fallbacks > 0 {
        println!(
            "  LLM calls: {} ({} fell back to the zero-LLM path)",
            r.llm_calls, r.llm_fallbacks
        );
    }
    if !r.skipped_manual.is_empty() {
        println!(
            "  left alone (edited by hand): {}",
            r.skipped_manual.join(", ")
        );
    }
    for error in &r.errors {
        println!("  error: {error}");
    }
    Ok(())
}

#[derive(Debug, Deserialize)]
struct ApplyResponse {
    consume: bool,
    lines: Vec<String>,
    omitted: usize,
}

/// `profile apply`: write (or `--remove`) the managed profile block in the
/// current repository's rules file.
async fn apply(ep: &ServerEndpoint, config: &Config, args: &ProfileApplyArgs) -> Result<()> {
    let cwd = std::env::current_dir().context("reading the current directory")?;
    let root = repository_root(&cwd);
    let target = choose_target(&root, args.target.as_deref());
    let backup = PrivateBackup {
        dir: config.data_dir.join("backups").join("profile-apply"),
        stem: checkout_backup_stem(&root),
    };
    if args.remove {
        return remove_block(&target, &backup);
    }
    if let Some(marker) = crate::marker::find_settings_marker(&cwd.to_string_lossy())
        && crate::marker::parse_toml_flag(&marker, "consume")
            .is_some_and(|v| crate::marker::is_falsy(&v))
    {
        bail!(
            "{} sets `[profile] consume = false`, so this project does not take the profile",
            marker.display()
        );
    }
    let (workspace, project) = super::resolve_scope(config, None, None)?;
    let mut query = vec![
        ("workspace", workspace.as_str()),
        ("project", project.as_str()),
    ];
    if let Some(user) = args.user.as_deref() {
        query.push(("user", user));
    }
    let resp: ApplyResponse = get_json(ep, "/admin/profile/apply", &query)
        .await
        .context("reading the profile entries for this project")?;
    if !resp.consume {
        bail!(
            "{workspace}/{project} sets `[profile] consume = false`, so it does not take the profile"
        );
    }
    if resp.lines.is_empty() {
        println!("No profile entries apply to {workspace}/{project}; nothing written.");
        return Ok(());
    }
    let block = ai_memory_core::profile::render_profile_block(&resp.lines, resp.omitted);
    if args.dry_run {
        println!("Would write to {}:\n\n{block}", target.display());
        return Ok(());
    }
    let outcome = apply_atomic_with_backup(&target, Some(&backup), |existing| {
        Ok(ai_memory_core::profile::merge_profile_block(
            existing, &block,
        ))
    })?;
    println!(
        "{}: {} ({} entr{}{})",
        target.display(),
        outcome.verb(),
        resp.lines.len(),
        if resp.lines.len() == 1 { "y" } else { "ies" },
        if resp.omitted > 0 {
            format!(", {} more over apply_max_lines", resp.omitted)
        } else {
            String::new()
        }
    );
    Ok(())
}

fn remove_block(target: &Path, backup: &PrivateBackup) -> Result<()> {
    let existing = match std::fs::read_to_string(target) {
        Ok(text) => text,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            println!("{} does not exist; nothing to remove.", target.display());
            return Ok(());
        }
        Err(error) => {
            return Err(error).with_context(|| format!("reading {}", target.display()));
        }
    };
    let Some(remaining) = ai_memory_core::profile::remove_profile_block(&existing) else {
        println!(
            "{} has no profile block; nothing to remove.",
            target.display()
        );
        return Ok(());
    };
    if remaining.is_empty() {
        // The file held nothing but the block `apply` created it for.
        std::fs::remove_file(target).with_context(|| format!("removing {}", target.display()))?;
        println!(
            "{}: removed (it held only the profile block)",
            target.display()
        );
        return Ok(());
    }
    let outcome = apply_atomic_with_backup(target, Some(backup), |_| Ok(remaining))?;
    println!(
        "{}: profile block removed ({})",
        target.display(),
        outcome.verb()
    );
    Ok(())
}

/// The checkout `cwd` is in: the nearest ancestor holding `.git` (a directory,
/// or the file a linked worktree has), else `cwd` itself.
fn repository_root(cwd: &Path) -> PathBuf {
    cwd.ancestors()
        .find(|dir| dir.join(".git").exists())
        .unwrap_or(cwd)
        .to_path_buf()
}

/// The rules file `apply` writes: `--target` (relative to `root`), else an
/// existing `AGENTS.md`, else an existing `CLAUDE.md` unless it only imports
/// `AGENTS.md` (writing there would be a no-op for every other harness), else
/// a new `AGENTS.md`.
fn choose_target(root: &Path, explicit: Option<&Path>) -> PathBuf {
    if let Some(explicit) = explicit {
        return if explicit.is_absolute() {
            explicit.to_path_buf()
        } else {
            root.join(explicit)
        };
    }
    let agents = root.join("AGENTS.md");
    if agents.exists() {
        return agents;
    }
    let claude = root.join("CLAUDE.md");
    match std::fs::read_to_string(&claude) {
        Ok(text) if !only_imports_agents(&text) => claude,
        _ => agents,
    }
}

/// A `CLAUDE.md` whose every non-blank line is an `@AGENTS.md` import.
fn only_imports_agents(text: &str) -> bool {
    let mut lines = text.lines().map(str::trim).filter(|l| !l.is_empty());
    lines.clone().next().is_some() && lines.all(|line| line == "@AGENTS.md")
}

#[cfg(test)]
mod tests {
    use super::{choose_target, only_imports_agents, profile_path, repository_root};

    #[test]
    fn profile_paths_gain_the_prefix_once() {
        assert_eq!(profile_path("tools/pnpm.md"), "profile/tools/pnpm.md");
        assert_eq!(
            profile_path("profile/tools/pnpm.md"),
            "profile/tools/pnpm.md"
        );
        assert_eq!(profile_path(" /tools/pnpm.md "), "profile/tools/pnpm.md");
    }

    #[test]
    fn the_target_prefers_agents_then_a_real_claude_md() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        assert_eq!(
            choose_target(root, None),
            root.join("AGENTS.md"),
            "new AGENTS.md"
        );

        std::fs::write(root.join("CLAUDE.md"), "@AGENTS.md\n").unwrap();
        assert_eq!(
            choose_target(root, None),
            root.join("AGENTS.md"),
            "an import-only CLAUDE.md points at AGENTS.md"
        );
        std::fs::write(root.join("CLAUDE.md"), "# Rules\nUse tabs.\n").unwrap();
        assert_eq!(choose_target(root, None), root.join("CLAUDE.md"));

        std::fs::write(root.join("AGENTS.md"), "# Agents\n").unwrap();
        assert_eq!(choose_target(root, None), root.join("AGENTS.md"));
        assert_eq!(
            choose_target(root, Some(std::path::Path::new("docs/RULES.md"))),
            root.join("docs/RULES.md")
        );
    }

    #[test]
    fn import_only_detection() {
        assert!(only_imports_agents("@AGENTS.md\n"));
        assert!(only_imports_agents("\n  @AGENTS.md  \n\n"));
        assert!(!only_imports_agents(""));
        assert!(!only_imports_agents("@AGENTS.md\nAlso: use tabs.\n"));
    }

    #[test]
    fn the_root_is_the_nearest_checkout() {
        let dir = tempfile::tempdir().unwrap();
        let repo = dir.path().join("repo");
        let nested = repo.join("crates").join("x");
        std::fs::create_dir_all(&nested).unwrap();
        std::fs::create_dir(repo.join(".git")).unwrap();
        assert_eq!(repository_root(&nested), repo);
        let loose = dir.path().join("loose");
        std::fs::create_dir(&loose).unwrap();
        assert_eq!(repository_root(&loose), loose);
    }
}