Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(cli): clarify first-run readiness and improve terminal presentation
SrDouglax476fb60c150e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 53f77b46..d5073cea 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,15 @@ version in [`docs/changelog/`](docs/changelog/):## [Unreleased]### Fixed+- Clarified first-run setup and capture diagnostics: separated installation+ from hook approval and first-capture verification, stopped recommending+ reinstalling detected Codex/Claude Code hooks, and kept inactive agents+ neutral. Summarized skill installation, reduced routine console tracing,+ and added terminal-aware status colors with `NO_COLOR` support. Added+ consistent headers, grouped status details, clearer installer results, and+ a single in-place indicator during setup waits. Grouped setup integration+ reports while retaining file paths, backups, policy details and agent-specific+ instructions; standalone installer and JSON output stayed unchanged. (#1313)- Fixed the thin-client commands ignoring a custom `bind`, which could writeinto the wrong store. `server_url` defaulted to `http://127.0.0.1:49374`and was never derived from `bind`, so `ai-memory --data-dir X status` (anddiff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.mdindex ac8a1a5e..9b612a88 100644--- a/INSTALL_FOR_AGENTS.md+++ b/INSTALL_FOR_AGENTS.md@@ -47,3 +47,6 @@ Afterwards:no service step there.Full reference: [`docs/install.md`](docs/install.md#one-step-native-install-installsh--ai-memory-setup).++For the final summary, hook approval, first-capture checks, and terminal output,+see [First-run checks](docs/first-run.md).diff --git a/crates/ai-memory-cli/src/commands/doctor.rs b/crates/ai-memory-cli/src/commands/doctor.rsindex 4fadd4d2..b2b96406 100644--- a/crates/ai-memory-cli/src/commands/doctor.rs+++ b/crates/ai-memory-cli/src/commands/doctor.rs@@ -23,9 +23,12 @@//! or a guideline block in a rules file) with the line to fix by hand; see//! [`super::agentmemory_residue`]. That check only reads.-use std::collections::BTreeMap;+use std::collections::{BTreeMap, BTreeSet};++mod summary;use std::path::{Path, PathBuf};use std::time::{Duration, SystemTime};+pub(crate) use summary::setup_diagnostics;use anyhow::{Context, Result};use serde::{Deserialize, Serialize};@@ -156,6 +159,8 @@ struct DoctorReport {server: String,since_days: u32,rows: Vec<CoverageRow>,+ #[serde(skip)]+ installed_hooks: BTreeSet<String>,capture_coverage_problem: Option<CaptureCoverageProblem>,/// The agent kinds (kebab form) flagged as uncaptured, for quick scripting.uncaptured: Vec<String>,@@ -498,13 +503,7 @@ async fn project_coordinate_report(}}-/// Run the capture-coverage doctor.-///-/// # Errors-/// Returns an error when the current scope cannot be resolved, the working-/// directory is unreadable, or the server cannot be reached / its response-/// cannot be parsed.-pub async fn run(config: &Config, args: crate::cli::DoctorArgs) -> Result<()> {+async fn collect(config: &Config, args: &crate::cli::DoctorArgs) -> Result<DoctorReport> {let (identity_cwd, lookup_cwd) = super::scope_directories(config).ok_or_else(|| anyhow::anyhow!("resolving the current working directory"))?;let explicit_scope = args@@ -661,6 +660,7 @@ pub async fn run(config: &Config, args: crate::cli::DoctorArgs) -> Result<()> {project,server: ep.url.clone(),since_days: args.since_days,+ installed_hooks: installed_hooks(&home, &cwd, &config.runtime_env),rows,capture_coverage_problem,uncaptured,@@ -677,10 +677,27 @@ pub async fn run(config: &Config, args: crate::cli::DoctorArgs) -> Result<()> {muse,};+ Ok(report)+}++/// Run the capture-coverage doctor.+///+/// # Errors+/// Returns an error when the current scope cannot be resolved, the working+/// directory is unreadable, or the server cannot be reached / its response+/// cannot be parsed.+pub async fn run(config: &Config, args: crate::cli::DoctorArgs) -> Result<()> {+ let report = collect(config, &args).await?;if args.json {println!("{}", serde_json::to_string_pretty(&report)?);} else {- render_human(&report);+ print!(+ "{}",+ render_terminal(+ &crate::terminal::Terminal::stdout(&config.runtime_env),+ &report+ )+ );}Ok(())}@@ -965,28 +982,7 @@ fn uninstall_line(harness: super::agent_plugins::PluginHarness) -> String {/// Human lines for the spool, the server and the Codex hook trust; empty/// when there is nothing to warn about.fn render_capture_health(report: &DoctorReport) -> String {- let mut out = String::new();- if report.server_unreachable {- out.push_str(&format!(- "⚠ The server at {} did not answer. Hook events are being spooled locally.\n",- report.server- ));- }- let spool = &report.spool;- if spool.evicting() {- out.push_str(&format!(- "⚠ The hook spool is full ({} events, oldest {}): each new event evicts the \- oldest undelivered one, which is lost until the server is back.\n",- spool.pending,- spool_age(spool.oldest_age_ms),- ));- } else if spool.pending > 0 {- out.push_str(&format!(- " hook spool: {} event(s) waiting for the server (oldest {}).\n",- spool.pending,- spool_age(spool.oldest_age_ms),- ));- }+ let mut out = render_transport_health(report);if let Some(trust) = &report.codex_hooks&& !trust.skipped.is_empty(){@@ -1076,51 +1072,58 @@ fn render_project_coordinate(coordinate: &ProjectCoordinateReport) -> String {output}-fn render_human(report: &DoctorReport) {- println!(+fn render_human(report: &DoctorReport) -> String {+ use std::fmt::Write as _;+ let mut out = String::new();+ let _ = writeln!(+ out,"Capture coverage for {}/{} (server {})",report.workspace, report.project, report.server);if let Some(identity) = &report.identity {- println!(+ let _ = writeln!(+ out," identity: {} ({}, server {})",identity.operator.as_deref().unwrap_or("anonymous"),identity.level,identity.version);} else {- println!(" identity: unavailable");+ let _ = writeln!(out, " identity: unavailable");}if let Some(posture) = report.auth_posture {- println!(" auth: {}", posture.line());+ let _ = writeln!(out, " auth: {}", posture.line());}if report.capture_owner_active {- println!(+ let _ = writeln!(+ out," AI_MEMORY_CAPTURE_OWNER is active: native capture is suppressed in this process.\n \Confirm the external producer is delivering events.");}if let Some(coordinate) = &report.project_coordinate {- print!("{}", render_project_coordinate(coordinate));+ let _ = write!(out, "{}", render_project_coordinate(coordinate));}if let Some(problem) = &report.capture_coverage_problem {- println!(" capture coverage: unavailable ({})", problem.reason);+ let _ = writeln!(out, " capture coverage: unavailable ({})", problem.reason);}- print!("{}", render_capture_health(report));- print!("{}", render_plugins(&report.plugins));- print!("{}", render_muse(report.muse.as_ref()));- print!(+ let _ = write!(out, "{}", render_capture_health(report));+ let _ = write!(out, "{}", render_plugins(&report.plugins));+ let _ = write!(out, "{}", render_muse(report.muse.as_ref()));+ let _ = write!(+ out,"{}",- super::agentmemory_residue::render(&report.agentmemory_residue)+ crate::commands::agentmemory_residue::render(&report.agentmemory_residue));if report.since_days == 0 {- println!(" recent window: all on-disk sessions\n");+ let _ = writeln!(out, " recent window: all on-disk sessions\n");} else {- println!(" recent window: last {} days\n", report.since_days);+ let _ = writeln!(out, " recent window: last {} days\n", report.since_days);}if let Some(problem) = &report.marker_capture_problem {- println!(+ let _ = writeln!(+ out,"⚠ {}: the settings marker has an invalid `[capture]` section.\n \It fails closed — file and shell tool content is reduced to metadata there, \nothing leaks — but its `ignore_paths` exclusions are NOT applying while it stays \@@ -1130,7 +1133,8 @@ fn render_human(report: &DoctorReport) {}if !report.native_memory.is_empty() {- println!(+ let _ = writeln!(+ out,"Note: a shell/PowerShell hook install (the Docker-wrapper default) does not \enforce capture-policy v1 — \"excluded\" below only holds on a native hook \install or a generated integration. Check the configured hook command; a dry-run \@@ -1140,76 +1144,215 @@ fn render_human(report: &DoctorReport) {if report.rows.is_empty() {if report.capture_coverage_problem.is_some() {- println!(+ let _ = writeln!(+ out," No local harness sessions found for this project; server capture counts are unavailable.");} else {- println!(+ let _ = writeln!(+ out," No local harness sessions found for this project and nothing captured yet.");}- return;+ return out;}for row in &report.rows {- let mark = match row.uncaptured {- Some(true) => "⚠",- Some(false) => "✓",- None => "?",+ let mark = if hooks_need_approval(report, &row.agent) {+ "!"+ } else {+ match row.uncaptured {+ Some(true) => "⚠",+ Some(false) if row.captured.is_some_and(|count| count > 0) => "✓",+ Some(false) => "·",+ None => "?",+ }};let captured = row.captured.map_or_else(|| "unavailable".to_owned(), |count| count.to_string());- println!(+ let _ = writeln!(+ out," {mark} {:<14} {:>4} local ({} recent) → {:>11} captured",row.agent, row.local_total, row.local_recent, captured);- if row.uncaptured == Some(true) {+ if hooks_need_approval(report, &row.agent) {+ let _ = writeln!(+ out,+ " Action required: open Codex, run /hooks, and approve the ai-memory hooks."+ );+ } else if row.uncaptured == Some(true) {if report.capture_owner_active {- println!(+ let _ = writeln!(+ out," No captured session: check the external producer and repository policy.");+ } else if report.installed_hooks.contains(&row.agent)+ || enabled_plugin(report, &row.agent)+ {+ let _ = writeln!(+ out,+ " Hooks installed; capture not yet verified. Restart the agent and start a session in this project."+ );+ let _ = writeln!(+ out,+ " If a new session is still missing, check hook delivery and repository policy."+ );} else {- println!(- " └ ran here but nothing was captured — install its hook:\n \- ai-memory install-hooks --agent {} --apply",+ let _ = writeln!(+ out,+ " └ ran here but nothing was captured — check its hook registration:\n ai-memory install-hooks --agent {} --apply",row.agent);}+ } else if row.captured == Some(0) {+ let _ = writeln!(+ out,+ " No recent activity; capture has not been verified."+ );}if let Some(count) = row.mixed_capture_sessions.filter(|count| *count > 0) {- println!(+ let _ = writeln!(+ out," {count} session(s) contain events from multiple capture sources.\n \Backfill can also mix source metadata; this does not prove duplicate capture.");}if let Some(memory) = report.native_memory.iter().find(|m| m.agent == row.agent) {- println!(+ let _ = writeln!(+ out," native memory: {} ({} file{})",memory.path,memory.file_count,if memory.file_count == 1 { "" } else { "s" });- println!(" capture: {}", memory.status);+ let _ = writeln!(out, " capture: {}", memory.status);}}if report.capture_coverage_problem.is_some() {- println!("\nCapture verdict unavailable: server capture counts could not be resolved.");- } else if report.uncaptured.is_empty() {- println!("\n✓ Every harness that ran in this project recently is captured on the server.");- } else {- let remedy = if report.capture_owner_active {- "Check the external producer and repository policy, then re-run `ai-memory doctor`."- } else {- "Install the hook(s) above, then re-run `ai-memory doctor` to confirm."- };- println!(- "\n⚠ {} harness(es) ran here recently with no captured sessions: {}.\n {remedy}",- report.uncaptured.len(),+ let _ = writeln!(+ out,+ "\nCapture verdict unavailable: server capture counts could not be resolved."+ );+ } else if report+ .rows+ .iter()+ .any(|row| hooks_need_approval(report, &row.agent))+ {+ let _ = writeln!(+ out,+ "\nAction required: approve Codex hooks, then start a new session and re-run `ai-memory doctor`."+ );+ } else if !report.uncaptured.is_empty() {+ let _ = writeln!(+ out,+ "\nCapture not yet verified for: {}. Follow the steps above, then re-run `ai-memory doctor`.",report.uncaptured.join(", "));+ } else if report+ .rows+ .iter()+ .all(|row| row.captured.is_some_and(|count| count > 0))+ {+ let _ = writeln!(+ out,+ "\n✓ Captured sessions found for every listed agent. This does not verify current hook delivery."+ );+ } else {+ let _ = writeln!(+ out,+ "\nNo capture confirmed for inactive agents. Start a session to verify delivery."+ );+ }+ out+}++fn installed_hooks(home: &Path, cwd: &Path, env: &crate::config::RuntimeEnv) -> BTreeSet<String> {+ let lookup = |name: &str| env.var_os(name);+ let claude = crate::commands::agent_plugins::claude_root(home, &lookup).join("settings.json");+ let project = crate::commands::install_hooks::project_claude_settings_local(cwd);+ let mut installed = BTreeSet::new();+ if [claude, project]+ .iter()+ .any(|path| crate::commands::install_hooks::settings_file_carries_ai_memory_hooks(path))+ {+ installed.insert("claude-code".to_owned());+ }+ if crate::commands::install_hooks::codex_hooks_path(env).is_ok_and(|path| {+ crate::commands::install_hooks::settings_file_carries_ai_memory_hooks(&path)+ }) {+ installed.insert("codex".to_owned());+ }+ installed+}++fn render_transport_health(report: &DoctorReport) -> String {+ let mut out = String::new();+ if report.server_unreachable {+ out.push_str(&format!(+ "⚠ The server at {} did not answer. Hook events are being spooled locally.\n",+ report.server+ ));+ }+ let spool = &report.spool;+ if spool.evicting() {+ out.push_str(&format!(+ "⚠ The hook spool is full ({} events, oldest {}): each new event evicts the \+ oldest undelivered one, which is lost until the server is back.\n",+ spool.pending,+ spool_age(spool.oldest_age_ms),+ ));+ } else if spool.pending > 0 {+ out.push_str(&format!(+ " hook spool: {} event(s) waiting for the server (oldest {}).\n",+ spool.pending,+ spool_age(spool.oldest_age_ms),+ ));}+ out+}++fn render_terminal(terminal: &crate::terminal::Terminal, report: &DoctorReport) -> String {+ let mut out = terminal.header("DOCTOR / capture diagnostics", env!("CARGO_PKG_VERSION"));+ out.push_str(&terminal.field(+ "Project",+ &format!("{}/{}", report.workspace, report.project),+ ));+ let body = render_human(report);+ out.push_str(&terminal.section("Coverage & readiness"));+ out.push_str(+ &terminal.document(+ body.split_once('\n')+ .map_or(body.as_str(), |(_, body)| body),+ ),+ );+ out+}++fn enabled_plugin(report: &DoctorReport, agent: &str) -> bool {+ report.plugins.iter().any(|plugin| {+ plugin.plugin.enabled+ && match plugin.plugin.harness {+ crate::commands::agent_plugins::PluginHarness::Codex => agent == "codex",+ crate::commands::agent_plugins::PluginHarness::ClaudeCode => agent == "claude-code",+ }+ })+}++fn hooks_need_approval(report: &DoctorReport, agent: &str) -> bool {+ agent == "codex"+ && (report+ .codex_hooks+ .as_ref()+ .is_some_and(|trust| !trust.skipped.is_empty())+ || report.plugins.iter().any(|plugin| {+ plugin.plugin.enabled+ && plugin+ .hook_trust+ .as_ref()+ .is_some_and(|trust| !trust.skipped.is_empty())+ }))}#[cfg(test)]@@ -1227,6 +1370,7 @@ mod tests {server: "http://192.0.2.1:49374".into(),since_days: 7,rows: Vec::new(),+ installed_hooks: BTreeSet::new(),capture_coverage_problem: None,uncaptured: Vec::new(),marker_capture_problem: None,@@ -1916,4 +2060,78 @@ mod tests {let claude = find_claude_report(&reports);assert_eq!(claude.file_count, 1);}++ #[test]+ fn installed_hooks_without_capture_need_a_first_session_not_reinstallation() {+ let mut report = health_report(+ crate::commands::hook_spool::SpoolHealth::default(),+ false,+ None,+ );+ report.rows = build_rows(+ &[LocalScan {+ agent: AgentKind::ClaudeCode,+ total: 4,+ recent: 4,+ }],+ &BTreeMap::new(),+ );+ report.uncaptured = vec!["claude-code".into()];+ report.installed_hooks.insert("claude-code".into());+ let text = render_human(&report);+ assert!(+ text.contains("Hooks installed; capture not yet verified"),+ "{text}"+ );+ assert!(!text.contains("install-hooks"), "{text}");+ assert!(!text.contains("Every harness"), "{text}");+ }++ #[test]+ fn untrusted_hooks_override_historical_capture_success() {+ let mut report = health_report(+ crate::commands::hook_spool::SpoolHealth::default(),+ false,+ Some(crate::commands::codex_hook_trust::CodexHookTrust {+ trusted: Vec::new(),+ skipped: vec![("sessionStart".into(), "untrusted".into())],+ }),+ );+ report.rows = build_rows(+ &[LocalScan {+ agent: AgentKind::Codex,+ total: 4,+ recent: 4,+ }],+ &BTreeMap::from([("codex".into(), 1)]),+ );+ let text = render_human(&report);+ assert!(+ text.contains("Action required: approve Codex hooks"),+ "{text}"+ );+ assert!(!text.contains("install-hooks"), "{text}");+ assert!(!text.contains("✓ codex"), "{text}");+ }++ #[test]+ fn inactive_uncaptured_agents_are_neutral() {+ let mut report = health_report(+ crate::commands::hook_spool::SpoolHealth::default(),+ false,+ None,+ );+ report.rows = build_rows(+ &[LocalScan {+ agent: AgentKind::Codex,+ total: 1,+ recent: 0,+ }],+ &BTreeMap::new(),+ );+ let text = render_human(&report);+ assert!(text.contains("· codex"), "{text}");+ assert!(text.contains("No recent activity"), "{text}");+ assert!(!text.contains("Every harness"), "{text}");+ }}diff --git a/crates/ai-memory-cli/src/commands/doctor/summary.rs b/crates/ai-memory-cli/src/commands/doctor/summary.rsnew file mode 100644index 00000000..7e9436ba--- /dev/null+++ b/crates/ai-memory-cli/src/commands/doctor/summary.rs@@ -0,0 +1,77 @@+//! Bounded installation checks shared with the setup summary.++use super::*;++pub(crate) struct SetupDiagnostics {+ pub(crate) text: String,+ pub(crate) action_required: bool,+}++pub(crate) async fn setup_diagnostics(+ config: &Config,+ agents: &[&str],+) -> Result<SetupDiagnostics> {+ use std::fmt::Write as _;+ let report = collect(+ config,+ &crate::cli::DoctorArgs {+ workspace: None,+ project: None,+ since_days: 30,+ json: false,+ },+ )+ .await?;+ let mut text = String::new();+ let mut action_required = false;+ for agent in agents {+ if hooks_need_approval(&report, agent) {+ action_required = true;+ let _ = writeln!(text, " ! {agent:<14} Hook approval required");+ let _ = writeln!(+ text,+ " Open Codex, run /hooks, and approve the ai-memory hooks."+ );+ } else {+ let _ = writeln!(+ text,+ " · {agent:<14} Restart required; capture not yet verified"+ );+ }+ if *agent == "codex"+ && report.codex_hooks.is_none()+ && !report+ .plugins+ .iter()+ .any(|plugin| plugin.hook_trust.is_some())+ {+ text.push_str(" Hook approval status unavailable; review /hooks in Codex.\n");+ }+ }+ if report.marker_capture_problem.is_some() {+ action_required = true;+ text.push_str(" ! Invalid capture settings. Fix the marker and run ai-memory doctor.\n");+ }+ if let Some(problem) = &report.capture_coverage_problem {+ action_required = true;+ let _ = writeln!(text, " ! Capture coverage unavailable: {}", problem.reason);+ }+ if report.capture_owner_active {+ action_required = true;+ text.push_str(+ " ! External capture owner active; check delivery from the external producer.\n",+ );+ }+ // Keep actionable diagnostics from optional integrations visible, without+ // making pre-install session history look like a failed new installation.+ text.push_str(&render_transport_health(&report));+ text.push_str(&render_plugins(&report.plugins));+ text.push_str(&render_muse(report.muse.as_ref()));+ text.push_str(&super::super::agentmemory_residue::render(+ &report.agentmemory_residue,+ ));+ Ok(SetupDiagnostics {+ text,+ action_required,+ })+}diff --git a/crates/ai-memory-cli/src/commands/init.rs b/crates/ai-memory-cli/src/commands/init.rsindex e0067347..21cae70b 100644--- a/crates/ai-memory-cli/src/commands/init.rs+++ b/crates/ai-memory-cli/src/commands/init.rs@@ -80,7 +80,11 @@ bearer_token_file = {}/// another way gets a new token at `auth-tokens/default`./// - Anything else, an existing install above all, records nothing and keeps/// the loopback no-auth behaviour it had (`ai-memory auth enable` opts in).-fn root_bearer_for_new_config(config: &Config, fresh: bool) -> Result<Option<RecordedBearer>> {+fn root_bearer_for_new_config(+ config: &Config,+ fresh: bool,+ announce: bool,+) -> Result<Option<RecordedBearer>> {if let Some(raw) = config.auth.bearer_token_file@@ -104,11 +108,13 @@ fn root_bearer_for_new_config(config: &Config, fresh: bool) -> Result<Option<Reclet minted =crate::local_auth::provision_root_token(&crate::server_profiles::root_token_path(root))?;crate::local_auth::seed_hook_credential(root, &minted.token)?;- println!(- "Generated a root bearer token in {} (owner-only). The server requires it on every \+ if announce {+ println!(+ "Generated a root bearer token in {} (owner-only). The server requires it on every \route but /healthz; hooks, the CLI and `ai-memory mcp-bridge` read it from there.",- minted.path.display()- );+ minted.path.display()+ );+ }Ok(Some(RecordedBearer {raw: crate::server_profiles::ROOT_TOKEN_RELATIVE.to_owned(),token: Some(minted),@@ -149,7 +155,7 @@ pub(crate) struct InitOutcome {/// Returns an error if directories cannot be created or the config file/// cannot be written.pub fn run(config: &Config, args: InitArgs, config_path: Option<&Path>) -> Result<()> {- initialize(config, &args, config_path).map(|_| ())+ initialize(config, &args, config_path, true).map(|_| ())}/// [`run`], reporting what it did.@@ -160,6 +166,7 @@ pub(crate) fn initialize(config: &Config,args: &InitArgs,config_path: Option<&Path>,+ announce: bool,) -> Result<InitOutcome> {let root = &config.data_dir;let cfg_path = init_config_path(root, config_path);@@ -198,7 +205,7 @@ pub(crate) fn initialize(// (anyhow's `with_context` would conflict), so map manually.let pepper = generate_token_hex(TOKEN_PEPPER_BYTES).map_err(|e| anyhow::anyhow!("generating auth token_pepper: {e}"))?;- let recorded = root_bearer_for_new_config(config, fresh)?;+ let recorded = root_bearer_for_new_config(config, fresh, announce)?;let bearer_line = recorded.as_ref().map(|bearer| render_bearer_token_file_line(&bearer.raw))diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex c8aea8de..8da08f09 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -14,6 +14,8 @@//! idempotent — a second `--apply` with unchanged content is a no-op//! and produces no backup.+use super::install_output::{eprintln, print, println};+use std::fs;use std::io::Write;use std::path::{Path, PathBuf};@@ -766,15 +768,7 @@ pub(crate) fn run_with_opencode_dialect_and_mcp_path(| AgentChoice::Pi| AgentChoice::Openclaw);- if generated || local_hook_policy_v1_supported() {- eprintln!(- "[ai-memory] capture-policy capability v1 enforced by this selected integration; re-run --apply to refresh existing installs."- );- } else {- eprintln!(- "[ai-memory] selected shell/PowerShell compatibility path does not enforce capture-policy v1; use a native platform selection or generated integration."- );- }+ super::install_output::capture_policy_capability(generated || local_hook_policy_v1_supported());// Assistant capture requires a native client-side sanitizer. No// silent fallback: bail so an operator on a script-fallback platform or a// different agent is told the flag has no effect instead of installing a@@ -2742,12 +2736,7 @@ fn apply_to_codex_settings_with_payload(// hooks on startup; users must explicitly trust them before// they fire.if !matches!(outcome, ApplyOutcome::NoOp) {- println!();- println!("Codex requires explicit trust for new hooks. Next time you start `codex`:");- println!(" → the TUI will surface 'Hooks need review' for each new event");- println!(" → choose 'Trust all and continue' (or trust individually)");- println!("To bypass the prompt for automated installs, start with");- println!("`codex --dangerously-bypass-hook-trust` (review hook scripts first).");+ super::install_output::codex_trust_hint();}Ok(())}diff --git a/crates/ai-memory-cli/src/commands/install_mcp.rs b/crates/ai-memory-cli/src/commands/install_mcp.rsindex 2b80ba3b..12360954 100644--- a/crates/ai-memory-cli/src/commands/install_mcp.rs+++ b/crates/ai-memory-cli/src/commands/install_mcp.rs@@ -23,8 +23,10 @@ use jsonc_parser::ParseOptions;use jsonc_parser::cst::{CstInputValue, CstRootNode};use serde_json::json;+use super::install_output::{eprintln, println};+use crate::cli::{InstallMcpArgs, McpClient, SchemaFlavor};-use crate::commands::apply_shared::{ApplyOutcome, apply_atomic, mutate_json, mutate_toml};+use crate::commands::apply_shared::{apply_atomic, mutate_json, mutate_toml};use crate::commands::path_util::{claude_config_dir, home_dir};use crate::commands::render_shared::{bearer_header_value, yaml_single_quote};use crate::config::{Config, DEFAULT_MCP_URL};@@ -970,34 +972,7 @@ fn apply_to_config_file(args: &InstallMcpArgs) -> Result<()> {mutate_json(existing, |root| upsert_json_mcp_entry(root, args))})?,};- println!(- "✓ {} {} ({})",- outcome.verb(),- path.display(),- match outcome {- ApplyOutcome::Created => "new file",- ApplyOutcome::Updated => "backup written next to it",- ApplyOutcome::NoOp => "already up to date",- }- );- if matches!(args.client, McpClient::PrimeAgent)- && (args.auth_token.is_some() || args.token_env_var)- {- println!(- " Prime Agent reads the token from ${PRIME_AGENT_TOKEN_ENV}; export it where you launch prime-agent."- );- }- if matches!(args.client, McpClient::Droid) && (args.auth_token.is_some() || args.token_env_var)- {- println!(- " Droid expands ${{{PRIME_AGENT_TOKEN_ENV}}} in the Authorization header; export it where you launch droid, or the server fails to connect."- );- }- if matches!(args.client, McpClient::Codex) && args.token_env_var {- println!(- " Codex reads the token from ${PRIME_AGENT_TOKEN_ENV}; export it where you launch codex."- );- }+ super::install_output::mcp_applied(args, &path, outcome, PRIME_AGENT_TOKEN_ENV);Ok(())}diff --git a/crates/ai-memory-cli/src/commands/install_output.rs b/crates/ai-memory-cli/src/commands/install_output.rsnew file mode 100644index 00000000..b515c019--- /dev/null+++ b/crates/ai-memory-cli/src/commands/install_output.rs@@ -0,0 +1,160 @@+//! Installer output is unchanged when run directly. Setup collects the same+//! messages during synchronous wiring so it can group them without redirecting+//! process-wide stdout/stderr or changing any installer result.++use std::cell::RefCell;+use std::fmt::Arguments;+use std::path::Path;++use crate::cli::{InstallMcpArgs, McpClient};++use super::apply_shared::ApplyOutcome;++pub(super) struct Message {+ pub text: String,+ pub stderr: bool,+}++thread_local! {+ static MESSAGES: RefCell<Option<Vec<Message>>> = const { RefCell::new(None) };+}++/// Synchronous and thread-local: other commands/threads keep their normal+/// output. Restoring the previous sink on drop also covers errors and panics.+pub(super) fn collect<T>(operation: impl FnOnce() -> T) -> (T, Vec<Message>) {+ struct Restore(Option<Vec<Message>>);+ impl Drop for Restore {+ fn drop(&mut self) {+ MESSAGES.with(|slot| slot.replace(self.0.take()));+ }+ }+ let _restore = Restore(MESSAGES.with(|slot| slot.replace(Some(Vec::new()))));+ let result = operation();+ let messages = MESSAGES.with(|slot| slot.take().unwrap_or_default());+ (result, messages)+}++pub(super) fn emit(stderr: bool, args: Arguments<'_>) {+ MESSAGES.with(|slot| {+ if let Some(messages) = slot.borrow_mut().as_mut() {+ messages.push(Message {+ text: args.to_string(),+ stderr,+ });+ } else if stderr {+ std::eprint!("{args}");+ } else {+ std::print!("{args}");+ }+ });+}++macro_rules! print {+ ($($arg:tt)*) => { $crate::commands::install_output::emit(false, format_args!($($arg)*)) };+}+macro_rules! println {+ () => { $crate::commands::install_output::emit(false, format_args!("\n")) };+ ($($arg:tt)*) => { $crate::commands::install_output::emit(false, format_args!("{}\n", format_args!($($arg)*))) };+}+macro_rules! eprintln {+ ($($arg:tt)*) => { $crate::commands::install_output::emit(true, format_args!("{}\n", format_args!($($arg)*))) };+}+pub(crate) use {eprintln, print, println};++pub(super) fn mcp_applied(+ args: &InstallMcpArgs,+ path: &Path,+ outcome: ApplyOutcome,+ token_env: &str,+) {+ println!(+ "✓ {} {} ({})",+ outcome.verb(),+ path.display(),+ match outcome {+ ApplyOutcome::Created => "new file",+ ApplyOutcome::Updated => "backup written next to it",+ ApplyOutcome::NoOp => "already up to date",+ }+ );+ if matches!(args.client, McpClient::PrimeAgent)+ && (args.auth_token.is_some() || args.token_env_var)+ {+ println!(+ " Prime Agent reads the token from ${token_env}; export it where you launch prime-agent."+ );+ }+ if matches!(args.client, McpClient::Droid) && (args.auth_token.is_some() || args.token_env_var)+ {+ println!(+ " Droid expands ${{{token_env}}} in the Authorization header; export it where you launch droid, or the server fails to connect."+ );+ }+ if matches!(args.client, McpClient::Codex) && args.token_env_var {+ println!(" Codex reads the token from ${token_env}; export it where you launch codex.");+ }+}++pub(super) fn capture_policy_capability(supported: bool) {+ if supported {+ eprintln!(+ "[ai-memory] capture-policy capability v1 enforced by this selected integration; re-run --apply to refresh existing installs."+ );+ } else {+ eprintln!(+ "[ai-memory] selected shell/PowerShell compatibility path does not enforce capture-policy v1; use a native platform selection or generated integration."+ );+ }+}++pub(super) fn codex_trust_hint() {+ println!();+ println!("Codex requires explicit trust for new hooks. Next time you start `codex`:");+ println!(" → the TUI will surface 'Hooks need review' for each new event");+ println!(" → choose 'Trust all and continue' (or trust individually)");+ println!("To bypass the prompt for automated installs, start with");+ println!("`codex --dangerously-bypass-hook-trust` (review hook scripts first).");+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn nested_collection_preserves_channels_and_outer_messages() {+ let (_, outer) = collect(|| {+ println!("outer start");+ let (result, inner) = collect(|| {+ print!("file ");+ println!("updated");+ eprintln!("warning");+ Err::<(), _>("failed")+ });+ assert_eq!(result, Err("failed"));+ assert_eq!(inner[0].text, "file ");+ assert_eq!(inner[1].text, "updated\n");+ assert_eq!(inner[2].text, "warning\n");+ assert!(inner[2].stderr);+ println!("outer end");+ });+ assert_eq!(outer.len(), 2);+ assert_eq!(outer[1].text, "outer end\n");+ assert!(!outer[1].stderr);+ assert!(MESSAGES.with(|slot| slot.borrow().is_none()));+ }++ #[test]+ fn panic_restores_the_previous_sink_and_threads_are_independent() {+ let (_, outer) = collect(|| {+ let panic = std::panic::catch_unwind(|| collect(|| panic!("installer panic")));+ assert!(panic.is_err());+ let other = std::thread::spawn(|| collect(|| println!("other thread")))+ .join()+ .unwrap();+ assert_eq!(other.1.len(), 1);+ println!("restored");+ });+ assert_eq!(outer.len(), 1);+ assert_eq!(outer[0].text, "restored\n");+ }+}diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rsindex 6ea42772..9f0feefc 100644--- a/crates/ai-memory-cli/src/commands/mod.rs+++ b/crates/ai-memory-cli/src/commands/mod.rs@@ -64,6 +64,7 @@ pub mod init;pub mod install_hooks;pub mod install_instructions;pub mod install_mcp;+pub(crate) mod install_output;pub mod install_skills;pub mod lint;pub mod list_projects;diff --git a/crates/ai-memory-cli/src/commands/setup.rs b/crates/ai-memory-cli/src/commands/setup.rsindex d9bf6ce1..f4f2cda7 100644--- a/crates/ai-memory-cli/src/commands/setup.rs+++ b/crates/ai-memory-cli/src/commands/setup.rs@@ -24,6 +24,9 @@//! `--yes` the plan is shown first and confirmed on a terminal; with no//! terminal to ask on, `setup` changes nothing and exits non-zero.+mod connections;+mod presentation;+use std::collections::BTreeSet;use std::ffi::OsString;use std::io::{BufRead as _, IsTerminal as _, Write as _};@@ -38,8 +41,8 @@ use super::{agent_plugins, doctor, init, install_hooks, install_mcp, install_skills, run_autowire,};use crate::cli::{- AgentChoice, DoctorArgs, HookInstallScope, InitArgs, InstallHooksArgs, InstallMcpArgs,- InstallSkillsAgent, InstallSkillsArgs, InstallSkillsScope, McpClient, SetupArgs,+ AgentChoice, HookInstallScope, InitArgs, InstallHooksArgs, InstallMcpArgs, InstallSkillsAgent,+ InstallSkillsArgs, InstallSkillsScope, McpClient, SetupArgs,};use crate::config::Config;use crate::http_client::{ServerEndpoint, ServerProbe, probe_server};@@ -200,7 +203,13 @@ pub async fn run(config: &Config, args: SetupArgs, config_path: Option<&Path>) -detected: args.agents.is_empty(),};- print_plan(&plan);+ print!(+ "{}",+ presentation::plan(+ &plan,+ &crate::terminal::Terminal::stdout(&config.runtime_env)+ )+ );if !args.yes {confirm()?;}@@ -366,63 +375,6 @@ fn plan_service(}}-fn print_plan(plan: &SetupPlan) {- println!("ai-memory setup will:");- if plan.fresh {- println!(- " - create the data dir {} and write {} (with a new root bearer token in \- auth-tokens/default when the data dir is new)",- plan.data_dir.display(),- plan.config_path.display()- );- } else {- println!(- " - keep the existing install at {} ({})",- plan.data_dir.display(),- plan.config_path.display()- );- }- match &plan.service {- ServicePlan::Install(unit) => println!(- " - install and start a {} at {}",- unit.manager.describe(),- unit.path.display()- ),- ServicePlan::Skip(reason) => println!(" - service: {reason}"),- }- if plan.agents.is_empty() {- println!(- " - wire no agent: none {}; name one with --agent <name>",- if plan.detected {- "was detected"- } else {- "was named"- }- );- }- for agent in &plan.agents {- let name = agent.agent.kind().as_str();- if agent.plugin {- println!(- " - leave {name} to its enabled ai-memory plugin ({}), which carries the \- hooks, MCP entry and skills",- agent_plugins::PLUGIN_ID- );- continue;- }- let mcp = if agent.mcp.is_some() {- "MCP + hooks"- } else {- "hooks"- };- println!(- " - wire {name}{}: {mcp} + skills",- if plan.detected { " (detected)" } else { "" }- );- }- println!(" - check /healthz, memory_status and doctor (read-only)");-}-/// Ask on a terminal; refuse without one.fn confirm() -> Result<()> {if !std::io::stdin().is_terminal() {@@ -456,8 +408,9 @@ async fn execute() -> Result<()> {let mut problems: Vec<String> = Vec::new();- println!("\n== init");- let outcome = init::initialize(config, &InitArgs { force: false }, config_path)?;+ let terminal = crate::terminal::Terminal::stdout(&config.runtime_env);+ print!("{}", terminal.section("Installing"));+ let outcome = init::initialize(config, &InitArgs { force: false }, config_path, false)?;let mut config = config.clone();if let Some(token) = outcome.root_token&& config.auth.bearer_token.is_none()@@ -465,31 +418,33 @@ async fn execute(config.auth.adopt_token_file(token.path, token.token);}println!(- "config: {} {}",- if outcome.config_written {- "wrote"- } else {- "kept"- },- outcome.config_path.display()+ "{}",+ terminal.paint(&format!(+ " ✓ Storage {}",+ if outcome.config_written {+ "initialized"+ } else {+ "preserved"+ }+ )));-- println!("\n== service");let mut wait_for_server = false;match &plan.service {- ServicePlan::Skip(reason) => println!("service: {reason}"),+ ServicePlan::Skip(reason) => println!(" · Service: {reason}"),ServicePlan::Install(unit) => match user_service::install(unit, runner) {Ok(change) => {wait_for_server = change != ServiceChange::Unchanged;println!(- "service: {} {}",- match change {- ServiceChange::Installed => "installed and started",- ServiceChange::Updated => "updated and restarted",- ServiceChange::Started => "started",- ServiceChange::Unchanged => "already running from",- },- unit.path.display()+ "{}",+ terminal.paint(&format!(+ " ✓ Background service {}",+ match change {+ ServiceChange::Installed => "installed and started",+ ServiceChange::Updated => "updated and restarted",+ ServiceChange::Started => "started",+ ServiceChange::Unchanged => "already running",+ }+ )));}Err(error) => problems.push(format!(@@ -499,7 +454,14 @@ async fn execute(},}let endpoint = ServerEndpoint::from_config_resolving_auth(&config).await;- if wait_for_server && !wait_until_reachable(&endpoint, ready_timeout).await {+ if wait_for_server+ && !terminal+ .waiting(+ "Waiting for the background service",+ wait_until_reachable(&endpoint, ready_timeout),+ )+ .await+ {problems.push(format!("service: the server did not answer at {} within {}s",endpoint.url,@@ -507,32 +469,72 @@ async fn execute());}- let mut skills_done = BTreeSet::new();- for agent in &plan.agents {- println!("\n== {}", agent.agent.kind().as_str());- for problem in wire_agent(&config, *agent, &mut skills_done) {- problems.push(format!("{}: {problem}", agent.agent.kind().as_str()));- }- }+ problems.extend(connections::run(&config, &plan.agents, &terminal));- println!("\n== self-check");+ print!("{}", terminal.section("Checking connections"));for problem in self_check(&config, &endpoint).await {problems.push(format!("self-check: {problem}"));}- println!();- if config.auth.bearer_token.is_none() {- println!("auth: none (loopback); run `ai-memory auth enable` to require a bearer token");+ let agents: Vec<_> = plan+ .agents+ .iter()+ .map(|agent| agent.agent.kind().as_str())+ .collect();+ let diagnostics = match terminal+ .waiting(+ "Checking agent readiness",+ doctor::setup_diagnostics(&config, &agents),+ )+ .await+ {+ Ok(report) => Some(report),+ Err(error) => {+ problems.push(format!("doctor: {error:#}"));+ None+ }+ };+ let (title, tone) = if !problems.is_empty() {+ ("Installation incomplete", crate::terminal::Tone::Bad)+ } else if diagnostics+ .as_ref()+ .is_some_and(|report| report.action_required)+ || plan.agents.is_empty()+ {+ (+ "Installation complete · Action required",+ crate::terminal::Tone::Warn,+ )} else {- println!("auth: bearer token (owner-only file; never printed)");- }- if let Some(hint) = web_sign_in_hint(&config, &endpoint) {- println!("{hint}");+ (+ "Installation complete · Restart your agents",+ crate::terminal::Tone::Good,+ )+ };+ print!(+ "{}",+ presentation::finish(+ &terminal,+ title,+ tone,+ diagnostics.as_ref().map(|report| report.text.as_str()),+ !problems.is_empty(),+ &config,+ &endpoint,+ &outcome.config_path+ )+ );+ if plan.agents.is_empty() {+ print!(+ "{}",+ terminal.notice(+ crate::terminal::Tone::Warn,+ "NO AGENTS CONNECTED",+ "Re-run setup with --agent <name>."+ )+ );}if problems.is_empty() {- println!(- "ai-memory is set up. Restart your agents so they load the new hooks and MCP entry."- );return Ok(());}for problem in &problems {@@ -547,6 +549,7 @@ async fn execute(/// How a browser signs in to the web UI on a token-file install. With no/// human accounts the server answers `/web` with a Basic challenge, and the/// token file's contents are the password. The token itself is never printed.+#[cfg(test)]fn web_sign_in_hint(config: &Config, endpoint: &ServerEndpoint) -> Option<String> {let file = config.auth.token_file.as_ref().filter(|file| file.loaded)?;Some(format!(@@ -575,24 +578,24 @@ async fn wait_until_reachable(endpoint: &ServerEndpoint, timeout: Duration) -> b/// first so an OpenCode major-version move has one entry before the hook/// installer reads it (the order `ai-memory run` auto-wire uses). Returns the/// failures.-fn wire_agent(config: &Config, plan: AgentPlan, skills_done: &mut BTreeSet<String>) -> Vec<String> {+fn wire_agent(+ config: &Config,+ plan: AgentPlan,+ skills_done: &mut BTreeSet<String>,+ report: &mut connections::AgentReport,+) -> Vec<String> {let mut problems = Vec::new();if plan.plugin {// Writing the settings-file wiring as well would load every skill// twice and register a second MCP server; the hook copies would be// de-duplicated, but nothing would be gained.- println!(- "plugin: {} is enabled; leaving the settings-file hooks, MCP entry and skills \- alone (run `ai-memory install-hooks --agent {} --apply` to add them anyway)",- agent_plugins::PLUGIN_ID,- plan.agent.kind().as_str()- );+ report.plugin(plan.agent);return problems;}let dialect = opencode_dialect(plan.agent);if let Some(client) = plan.mcp {if install_mcp::existing_entry_is_session_aware(client, None, ENTRY_NAME) {- println!("mcp: keeping the existing session-aware entry");+ report.message("MCP", "Keeping the existing session-aware entry".to_owned());} else {let args = InstallMcpArgs {client,@@ -607,7 +610,9 @@ fn wire_agent(config: &Config, plan: AgentPlan, skills_done: &mut BTreeSet<Strinstdio_bridge: false,bridge_data_dir: None,};- if let Err(error) = install_mcp::run_with_opencode_dialect(config, args, dialect) {+ if let Err(error) = report.collect("MCP", || {+ install_mcp::run_with_opencode_dialect(config, args, dialect)+ }) {problems.push(format!("install-mcp: {error:#}"));}}@@ -628,9 +633,9 @@ fn wire_agent(config: &Config, plan: AgentPlan, skills_done: &mut BTreeSet<Strincapture_prompts: false,profile: None,};- if let Err(error) =+ if let Err(error) = report.collect("Hooks", || {install_hooks::run_with_opencode_dialect_and_mcp_path(config, hooks, dialect, None)- {+ }) {problems.push(format!("install-hooks: {error:#}"));}let skills_key = format!("{:?}", plan.skills);@@ -642,8 +647,12 @@ fn wire_agent(config: &Config, plan: AgentPlan, skills_done: &mut BTreeSet<Strinprint: false,force: false,};- if let Err(error) = install_skills::run(config, args) {+ if let Err(error) = install_skills::prepare_install(&args, &config.runtime_env)+ .and_then(install_skills::run_prepared_quiet)+ {problems.push(format!("install-skills: {error:#}"));+ } else {+ report.message("Skills", "installed".to_owned());}}problems@@ -654,13 +663,21 @@ fn wire_agent(config: &Config, plan: AgentPlan, skills_done: &mut BTreeSet<Strinasync fn self_check(config: &Config, endpoint: &ServerEndpoint) -> Vec<String> {let mut problems = Vec::new();let healthz = endpoint.build_url("/healthz");- match reqwest::Client::new()- .get(&healthz)- .timeout(Duration::from_secs(5))- .send()+ let terminal = crate::terminal::Terminal::stdout(&config.runtime_env);+ match terminal+ .waiting(+ "Checking server connection",+ reqwest::Client::new()+ .get(&healthz)+ .timeout(Duration::from_secs(5))+ .send(),+ ).await{- Ok(response) if response.status().is_success() => println!("healthz: ok ({healthz})"),+ Ok(response) if response.status().is_success() => println!(+ "{}",+ crate::terminal::Terminal::stdout(&config.runtime_env).paint(" ✓ Server responding")+ ),Ok(response) => problems.push(format!("{healthz} answered {}", response.status())),Err(error) => {problems.push(format!("{healthz} did not answer: {error}"));@@ -668,19 +685,17 @@ async fn self_check(config: &Config, endpoint: &ServerEndpoint) -> Vec<String> {return problems;}}- match memory_status(config).await {- Ok(()) => println!("memory_status: ok"),+ match terminal+ .waiting("Checking authenticated memory API", memory_status(config))+ .await+ {+ Ok(()) => println!(+ "{}",+ crate::terminal::Terminal::stdout(&config.runtime_env)+ .paint(" ✓ Memory API responding")+ ),Err(error) => problems.push(format!("memory_status: {error:#}")),}- let doctor = DoctorArgs {- workspace: None,- project: None,- since_days: 30,- json: false,- };- if let Err(error) = doctor::run(config, doctor).await {- problems.push(format!("doctor: {error:#}"));- }problems}diff --git a/crates/ai-memory-cli/src/commands/setup/connections.rs b/crates/ai-memory-cli/src/commands/setup/connections.rsnew file mode 100644index 00000000..77b38165--- /dev/null+++ b/crates/ai-memory-cli/src/commands/setup/connections.rs@@ -0,0 +1,279 @@+//! Group the installers' existing reports. Unknown messages are retained in+//! full, and only identical policy reports are combined across agents.++use std::collections::BTreeMap;++use super::*;+use crate::commands::install_output::{self, Message};+use crate::terminal::{Terminal, Tone};++#[derive(Default)]+pub(super) struct AgentReport {+ messages: Vec<(&'static str, Message)>,+}++impl AgentReport {+ pub(super) fn plugin(&mut self, agent: AgentChoice) {+ self.message(+ "Plugin",+ format!(+ "plugin: {} is enabled; leaving the settings-file hooks, MCP entry and skills \+ alone (run `ai-memory install-hooks --agent {} --apply` to add them anyway)",+ agent_plugins::PLUGIN_ID,+ agent.kind().as_str()+ ),+ );+ }++ pub(super) fn collect<T>(&mut self, phase: &'static str, operation: impl FnOnce() -> T) -> T {+ let (result, messages) = install_output::collect(operation);+ self.messages+ .extend(messages.into_iter().map(|message| (phase, message)));+ result+ }++ pub(super) fn message(&mut self, phase: &'static str, text: String) {+ self.messages.push((+ phase,+ Message {+ text,+ stderr: false,+ },+ ));+ }+}++#[derive(Default)]+struct Policies {+ modes: BTreeMap<String, Vec<String>>,+ capabilities: BTreeMap<String, Vec<String>>,+}++impl Policies {+ fn accept(&mut self, text: &str, agent: &str) -> bool {+ let group = if let Some(mode) = text.strip_prefix("capture mode: ") {+ self.modes.entry(mode.to_owned()).or_default()+ } else if let Some(capability) = text.strip_prefix("[ai-memory] capture-policy capability ")+ {+ self.capabilities.entry(capability.to_owned()).or_default()+ } else {+ return false;+ };+ if !group.iter().any(|name| name == agent) {+ group.push(agent.to_owned());+ }+ true+ }++ fn render(&self, terminal: &Terminal) -> String {+ if self.modes.is_empty() && self.capabilities.is_empty() {+ return String::new();+ }+ let mut out = terminal.section("Capture policy");+ for (mode, agents) in &self.modes {+ out.push_str(&terminal.field("Mode", &format!("{mode} · {}", agents.join(" · "))));+ }+ for (capability, agents) in &self.capabilities {+ let text = capability.replace("this selected integration", &agents.join(", "));+ out.push_str(&terminal.document(&format!(" Capture-policy capability {text}\n")));+ }+ out+ }+}++fn name(agent: AgentChoice) -> &'static str {+ match agent {+ AgentChoice::ClaudeCode => "Claude Code",+ AgentChoice::Codex => "Codex",+ AgentChoice::OpenCode => "OpenCode",+ AgentChoice::OpenCode2 => "OpenCode 2",+ AgentChoice::AntigravityCli => "Antigravity CLI",+ _ => agent.kind().as_str(),+ }+}++/// File messages start with a path so the shared terminal can abbreviate the+/// home directory. Preserve the original outcome, backup note and script count.+fn file_detail(text: &str) -> Option<String> {+ let text = text.strip_prefix("✓ ")?;+ if let Some((description, path)) = text.split_once(" → ") {+ return Some(format!("{path} · {description}"));+ }+ let (verb, rest) = text.split_once(' ')?;+ if !matches!(verb, "created" | "updated" | "no-op") {+ return None;+ }+ let (path, note) = rest.rsplit_once(" (")?;+ Some(format!("{path} · {verb} · {}", note.strip_suffix(')')?))+}++fn render_agent(+ terminal: &Terminal,+ plan: AgentPlan,+ report: AgentReport,+ failed: bool,+ policies: &mut Policies,+) -> (String, String) {+ let agent = name(plan.agent);+ let mut details = format!(+ "\n {}\n",+ terminal.ink(+ &format!(+ "{} {agent}{}",+ if failed { "✗" } else { "✓" },+ if failed { " · incomplete" } else { "" }+ ),+ if failed { Tone::Bad } else { Tone::Good },+ )+ );+ let mut notes = String::new();+ // A print! call may emit a partial line; join adjacent chunks from each+ // phase/channel before classifying so no instruction or warning is split.+ let mut chunks: Vec<(&str, bool, String)> = Vec::new();+ for (phase, message) in report.messages {+ if let Some((last_phase, last_stderr, text)) = chunks.last_mut()+ && *last_phase == phase+ && *last_stderr == message.stderr+ {+ text.push_str(&message.text);+ } else {+ chunks.push((phase, message.stderr, message.text));+ }+ }+ for (phase, stderr, text) in chunks {+ for line in text.lines().map(str::trim).filter(|line| !line.is_empty()) {+ if policies.accept(line, agent) {+ continue;+ }+ if let Some(detail) = file_detail(line) {+ let label = if phase == "Hooks" && line.contains("plugin file") {+ "Plugin"+ } else {+ phase+ };+ details.push_str(&terminal.field(label, &detail));+ } else if phase == "Skills"+ || phase == "Plugin"+ || line == "Keeping the existing session-aware entry"+ {+ details.push_str(&terminal.field(phase, line));+ } else if stderr {+ details.push_str(&terminal.notice(Tone::Warn, &format!("{agent} / {phase}"), line));+ } else {+ // Retain unrecognized stdout verbatim as agent guidance.+ notes.push_str(&terminal.document(&format!(" {line}\n")));+ }+ }+ }+ if !notes.is_empty() {+ let (marker, tone) = if plan.agent == AgentChoice::Codex {+ ("!", Tone::Warn)+ } else {+ ("·", Tone::Accent)+ };+ notes = format!(+ "\n {}\n{notes}",+ terminal.ink(&format!("{marker} {agent}"), tone)+ );+ }+ (details, notes)+}++pub(super) fn run(config: &Config, agents: &[AgentPlan], terminal: &Terminal) -> Vec<String> {+ let mut skills_done = BTreeSet::new();+ let mut policies = Policies::default();+ let mut notes = String::new();+ let mut problems = Vec::new();+ if !agents.is_empty() {+ print!("{}", terminal.section("Connect"));+ }+ for plan in agents {+ let mut report = AgentReport::default();+ let errors = wire_agent(config, *plan, &mut skills_done, &mut report);+ let (details, guidance) =+ render_agent(terminal, *plan, report, !errors.is_empty(), &mut policies);+ print!("{details}");+ notes.push_str(&guidance);+ problems.extend(+ errors+ .into_iter()+ .map(|error| format!("{}: {error}", plan.agent.kind().as_str())),+ );+ }+ print!("{}", policies.render(terminal));+ if !notes.is_empty() {+ print!("{}{notes}", terminal.section("Agent next steps"));+ }+ problems+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn failures_unknown_warnings_and_future_guidance_remain_visible() {+ let terminal =+ Terminal::stdout(&crate::config::RuntimeEnv::with_process_env_for_tests(&[(+ "NO_COLOR", "1",+ )]));+ let mut report = AgentReport::default();+ report.collect("Hooks", || {+ install_output::eprintln!("[ai-memory] selected shell/PowerShell compatibility path does not enforce capture-policy v1");+ install_output::eprintln!("Future installer warning: preserve this remedy");+ install_output::print!("Future instruction ");+ install_output::println!("with an important command");+ });+ let (details, notes) = render_agent(+ &terminal,+ AgentPlan::new(AgentChoice::Codex),+ report,+ true,+ &mut Policies::default(),+ );+ assert!(details.contains("✗ Codex · incomplete"), "{details}");+ assert!(!details.contains("✓ Codex"), "{details}");+ let warning = details.replace("\n │ ", " ");+ assert!(+ warning.contains("does not enforce capture-policy v1"),+ "{details}"+ );+ assert!(details.contains("preserve this remedy"), "{details}");+ assert!(+ notes.contains("Future instruction with an important command"),+ "{notes}"+ );+ assert!(!format!("{details}{notes}").contains('\u{1b}'));+ }++ #[test]+ fn policy_groups_keep_agent_scope_and_never_hide_unsupported_capture() {+ let mut policies = Policies::default();+ let supported = "[ai-memory] capture-policy capability v1 enforced by this selected integration; re-run --apply to refresh existing installs.";+ assert!(policies.accept(supported, "Codex"));+ assert!(policies.accept(supported, "Claude Code"));+ assert!(policies.accept("capture mode: allowlist", "Codex"));+ assert!(policies.accept("capture mode: denylist", "Claude Code"));+ assert!(!policies.accept("[ai-memory] selected shell/PowerShell compatibility path does not enforce capture-policy v1", "Other"));+ assert_eq!(policies.capabilities.len(), 1);+ assert_eq!(policies.modes["allowlist"], ["Codex"]);+ assert_eq!(policies.modes["denylist"], ["Claude Code"]);+ }++ #[test]+ fn file_details_preserve_backups_noops_and_paths_with_spaces() {+ assert_eq!(+ file_detail("✓ updated /home/a b/config.json (backup written next to it)"),+ Some("/home/a b/config.json · updated · backup written next to it".to_owned())+ );+ assert_eq!(+ file_detail("✓ no-op /home/a/config.json (already up to date)"),+ Some("/home/a/config.json · no-op · already up to date".to_owned())+ );+ assert_eq!(+ file_detail("✓ staged 14 hook script(s) → /home/a/hooks"),+ Some("/home/a/hooks · staged 14 hook script(s)".to_owned())+ );+ assert_eq!(file_detail("Some future installer instruction"), None);+ }+}diff --git a/crates/ai-memory-cli/src/commands/setup/presentation.rs b/crates/ai-memory-cli/src/commands/setup/presentation.rsnew file mode 100644index 00000000..fffbcb0f--- /dev/null+++ b/crates/ai-memory-cli/src/commands/setup/presentation.rs@@ -0,0 +1,116 @@+//! The setup plan and final result share the terminal's visual vocabulary.++use super::*;+use crate::terminal::{Terminal, Tone};++pub(super) fn plan(plan: &SetupPlan, terminal: &Terminal) -> String {+ let mut out = terminal.header(+ "SETUP / connect your coding agents",+ env!("CARGO_PKG_VERSION"),+ );+ let names: Vec<_> = plan+ .agents+ .iter()+ .map(|agent| agent.agent.kind().as_str())+ .collect();+ out.push_str(&terminal.field(+ "Agents",+ &if names.is_empty() {+ "None detected".to_owned()+ } else {+ names.join(" · ")+ },+ ));+ out.push_str(&terminal.field("Storage", &plan.data_dir.display().to_string()));+ out.push_str(&terminal.field("Config", &plan.config_path.display().to_string()));+ out.push_str(&terminal.section("Your plan"));+ out.push_str(&terminal.document(&format!(+ " 01 {}\n",+ if plan.fresh {+ "Initialize storage and protected authentication"+ } else {+ "Keep existing data and configuration"+ }+ )));+ match &plan.service {+ ServicePlan::Install(unit) => out.push_str(&terminal.document(&format!(+ " 02 Install or start a {}\n",+ unit.manager.describe()+ ))),+ ServicePlan::Skip(reason) => {+ out.push_str(&terminal.document(&format!(" 02 Service: {reason}\n")))+ }+ }+ for agent in &plan.agents {+ out.push_str(&terminal.document(&format!(+ " 03 Connect {}{}{}\n",+ agent.agent.kind().as_str(),+ if plan.detected { " (detected)" } else { "" },+ if agent.plugin {+ " through its existing plugin"+ } else {+ " with MCP, hooks and memory skills"+ }+ )));+ }+ out.push_str(&terminal.document(" 04 Verify server and memory API connections\n"));+ if plan.agents.is_empty() {+ out.push_str(&terminal.notice(+ Tone::Warn,+ "NO AGENT DETECTED",+ "Name one with --agent <name>.",+ ));+ }+ out.push_str(&terminal.section("Capture"));+ out.push_str(&terminal.document(" Session hooks record prompts and supported tool activity under your policy.\n No model API key is required in the default mode.\n\n"));+ out+}++#[allow(clippy::too_many_arguments)]+pub(super) fn finish(+ terminal: &Terminal,+ title: &str,+ tone: Tone,+ diagnostics: Option<&str>,+ problems: bool,+ config: &Config,+ endpoint: &ServerEndpoint,+ config_path: &Path,+) -> String {+ let mut out = terminal.notice(+ tone,+ title,+ diagnostics.unwrap_or("Connection checks did not finish. Review the problems below."),+ );+ out.push_str(&terminal.section("Next"));+ if problems {+ out.push_str(+ &terminal.document(" Resolve the problems below, then re-run ai-memory setup.\n"),+ );+ } else {+ out.push_str(&terminal.document(" 1 Restart your selected agents to load the integration.\n 2 Start a session in a project, then run ai-memory doctor there.\n"));+ }+ out.push_str(&terminal.document(" Installation checks do not verify session capture.\n"));+ out.push_str(&terminal.section("Your installation"));+ out.push_str(&terminal.field("Dashboard", &endpoint.build_url("/web")));+ if let Some(file) = config.auth.token_file.as_ref().filter(|file| file.loaded) {+ out.push_str(&terminal.field(+ "Sign in",+ "Any username · use the contents of the token file as your password",+ ));+ out.push_str(&terminal.field("Token file", &file.path.display().to_string()));+ }+ out.push_str(&terminal.field("Diagnostics", "ai-memory doctor"));+ out.push_str(&terminal.field("Data", &config.data_dir.display().to_string()));+ out.push_str(&terminal.field("Config", &config_path.display().to_string()));+ if config.auth.bearer_token.is_none() {+ out.push_str(&terminal.notice(+ Tone::Warn,+ "AUTHENTICATION DISABLED",+ "Run ai-memory auth enable to require a token.",+ ));+ } else {+ out.push_str(&terminal.field("Auth", "Bearer token configured · never printed"));+ }+ out+}diff --git a/crates/ai-memory-cli/src/commands/status.rs b/crates/ai-memory-cli/src/commands/status.rsindex 0b87ea75..eca356c3 100644--- a/crates/ai-memory-cli/src/commands/status.rs+++ b/crates/ai-memory-cli/src/commands/status.rs@@ -4,10 +4,13 @@//! server; renders the response as human text or JSON. Never opens//! the store directly — the server is the source of truth.+mod presentation;+use ai_memory_core::fix_lines;use ai_memory_llm::{ProviderHealthSnapshot, ProviderHealthStatus, ProviderRoleHealthSnapshot};use anyhow::Result;use serde::{Deserialize, Serialize};+use std::fmt::Write as _;use super::hook_spool::{SpoolHealth, spool_dir, spool_health};use crate::cli::StatusArgs;@@ -242,6 +245,14 @@ pub async fn run(config: &Config, args: StatusArgs) -> Result<()> {let report: Report = match get_json::<Report>(&ep, "/admin/status", &[]).await {Ok(report) => report,Err(err) => {+ if !args.json {+ let terminal = crate::terminal::Terminal::stdout(&config.runtime_env);+ eprint!(+ "{}",+ terminal.header("STATUS / connection unavailable", env!("CARGO_PKG_VERSION"))+ );+ eprint!("{}", terminal.notice(crate::terminal::Tone::Bad, "SERVER UNREACHABLE", &format!("No response from {}.\nLocal queue information follows; start the server before retrying.",ep.url)));+ }report_offline_spool(&spool, args.json);report_offline_recovery_hint(config, &spool, args.json);return Err(err);@@ -269,181 +280,22 @@ pub async fn run(config: &Config, args: StatusArgs) -> Result<()> {))?);} else {- println!("ai-memory {} (server)", report.version);- println!(" server: {}", ep.url);- println!(" data-dir: {}", report.data_dir);- println!(" db: {}", report.db_path);- println!(" bind: {}", report.bind);- println!(" auth: {}", auth_posture.line());- println!(- " pages: {} (all versions: {})",- report.counts.pages_latest, report.counts.pages_all- );- println!(" sessions: {}", report.counts.sessions);- println!(" observations: {}", report.counts.observations);- println!(- " fts: pages {}/{}; observations {}/{}",- report.derived.pages_fts_rows,- report.derived.pages_rows,- report.derived.observations_fts_rows,- report.derived.observations_rows- );- println!(- " embeddings: {} rows; {} latest pages missing",- report.derived.embedding_rows, report.derived.latest_pages_missing_embeddings- );- if report.derived.latest_pages_unembeddable > 0 {- println!(- " unembeddable: {} (empty body; no embedder can cover these)",- report.derived.latest_pages_unembeddable- );- }- for triple in &report.derived.embedding_triples {- println!(- " {}/{} dim {}: {} rows",- triple.provider, triple.model, triple.dim, triple.count- );- }- // Only shown when there is something to act on. A recovered count with- // no outstanding failures is history, not a problem.- if report.derived.embed_failures_unresolved > 0 {- println!(- " embed failures: {} unresolved ({} recovered since)",- report.derived.embed_failures_unresolved, report.derived.embed_failures_recovered- );- }- // The figure that makes a `compact` decision possible. Reported- // always, so "should I VACUUM?" has an answer other than a guess; the- // advisory line only appears once it is worth the exclusive lock.- if report.storage.database_bytes > 0 {- let pct = (report.storage.reclaimable_bytes as f64- / report.storage.database_bytes as f64)- * 100.0;- println!(- " storage: {} on disk, {} reclaimable ({pct:.1}%)",- super::compact::human_bytes(report.storage.database_bytes),- super::compact::human_bytes(report.storage.reclaimable_bytes),- );- if let Some(free) = report.storage.data_dir_free_bytes {- println!(" filesystem free: {}", super::compact::human_bytes(free));- }- if fix_lines::reclaim_advised(- report.storage.reclaimable_bytes,- report.storage.database_bytes,- ) {- println!(- " `{}` would return it (blocks writes while it runs)",- fix_lines::COMPACT- );- }- }- println!(- " links: {} latest-page links (unresolved: {}, stale: {})",- report.derived.links_from_latest_pages,- report.derived.unresolved_links_from_latest_pages,- report.derived.stale_links_from_latest_pages- );- if !report.derived.typed_links_from_latest_pages.is_empty() {- let typed: Vec<String> = report- .derived- .typed_links_from_latest_pages- .iter()- .map(|(k, v)| format!("{k}: {v}"))- .collect();- println!(" typed edges: {}", typed.join(", "));- }- if let Some(wiki) = &report.wiki_format {- let migrated = if wiki.okf_migrated {- "OKF v0.2 (migrated)"- } else {- "OKF v0.2 (native, no migration needed)"- };- match (&wiki.backup_archive, wiki.backup_archive_bytes) {- (Some(path), Some(bytes)) => println!(- " wiki format: {migrated}; pre-migration backup still on disk: \- {path} ({})",- super::compact::human_bytes(bytes)- ),- _ => println!(" wiki format: {migrated}"),- }- }- if let Some((queued, capacity)) = report.write_queue {- // A queue pinned near capacity is the wedged-writer signal.- if queued > 0 {- println!(" write queue: {queued}/{capacity}");- }- }- println!(" spool:");- println!(" pending: {}", spool.pending);- println!(" oldest: {}", spool_age_line(spool.oldest_age_ms));- println!(" retries: {}", spool.retries_total);- if journal_pending > 0 || journal_error.is_some() {- println!(" recovery:");- println!(- " journal: {journal_pending} pending ({journal_degraded} degraded, {journal_finish_failed} finish-failed)"- );- if let Some(error) = &journal_error {- println!(" error: {error}");- }- println!(" action: run `{}`", fix_lines::RECOVER);- }- if let Some(ingest) = &report.ingest {- println!(" ingest (server, this process):");- println!(" accepted: {}", ingest.accepted);- println!(- " dropped: {} (capture policy)",- ingest.dropped_by_policy- );- println!(- " outcomes: {} stored, {} replayed, {} resumed, {} ignored end, {} failed",- ingest.stored, ingest.replayed, ingest.resumed, ingest.ignored_end, ingest.failed- );- println!(- " drops: {} unauthorized, {} collision, {} invalid",- ingest.dropped_unauthorized, ingest.dropped_collision, ingest.dropped_invalid- );- println!(- " shed: {} saturated, {} rate-limited",- ingest.shed_saturated, ingest.shed_rate_limited- );- println!(- " last write: {}",- last_write_line(ingest.last_persisted_ms)- );- }- // #446 + #428 interact here: under allowlist mode an unmarked- // repository never sends, so zero counters read exactly like a broken- // install. Deliberately outside the ingest block above: the mode is a- // client-side fact, and an older server returns no ingest section at- // all — which is precisely a case where the operator needs telling.- if capture_mode == "allowlist" {- println!(- " capture mode: allowlist — repositories without a \- .ai-memory.toml marker send nothing"- );- }- println!(" providers:");- println!(- " llm: {}",- provider_health_line(&report.providers.llm)+ let details = details(+ &report,+ &spool,+ journal_pending,+ journal_degraded,+ journal_finish_failed,+ &journal_error,+ capture_mode,+ &ep,+ auth_posture,);- println!(- " embedding: {}",- provider_health_line(&report.providers.embedding)+ let terminal = crate::terminal::Terminal::stdout(&config.runtime_env);+ print!(+ "{}",+ presentation::render(&terminal, &report, &spool, &ep, &details));- if report.providers.llm.status == ProviderHealthStatus::Error- && let Some(hint) = &report.providers.llm.retry_hint- {- println!(" retry: {hint}");- }- // Only present when `llm_fallbacks` is configured — an older server- // or a plain single-provider setup reports an empty list.- if !report.providers.llm_candidates.is_empty() {- println!(" fallback chain:");- for candidate in &report.providers.llm_candidates {- println!(" {}", fallback_candidate_line(candidate));- }- }}Ok(())}@@ -575,6 +427,227 @@ fn error_detail(role: &ProviderRoleHealthSnapshot) -> String {}}+#[allow(clippy::too_many_arguments)]+fn details(+ report: &Report,+ spool: &SpoolHealth,+ journal_pending: usize,+ journal_degraded: usize,+ journal_finish_failed: usize,+ journal_error: &Option<String>,+ capture_mode: &str,+ ep: &ServerEndpoint,+ auth_posture: crate::local_auth::AuthPosture,+) -> String {+ let mut out = String::new();+ let _ = writeln!(out, "ai-memory {} (server)", report.version);+ let _ = writeln!(out, " server: {}", ep.url);+ let _ = writeln!(out, " data-dir: {}", report.data_dir);+ let _ = writeln!(out, " db: {}", report.db_path);+ let _ = writeln!(out, " bind: {}", report.bind);+ let _ = writeln!(out, " auth: {}", auth_posture.line());+ let _ = writeln!(+ out,+ " pages: {} (all versions: {})",+ report.counts.pages_latest, report.counts.pages_all+ );+ let _ = writeln!(out, " sessions: {}", report.counts.sessions);+ let _ = writeln!(out, " observations: {}", report.counts.observations);+ let _ = writeln!(+ out,+ " fts: pages {}/{}; observations {}/{}",+ report.derived.pages_fts_rows,+ report.derived.pages_rows,+ report.derived.observations_fts_rows,+ report.derived.observations_rows+ );+ let _ = writeln!(+ out,+ " embeddings: {} rows; {} latest pages missing",+ report.derived.embedding_rows, report.derived.latest_pages_missing_embeddings+ );+ if report.derived.latest_pages_unembeddable > 0 {+ let _ = writeln!(+ out,+ " unembeddable: {} (empty body; no embedder can cover these)",+ report.derived.latest_pages_unembeddable+ );+ }+ for triple in &report.derived.embedding_triples {+ let _ = writeln!(+ out,+ " {}/{} dim {}: {} rows",+ triple.provider, triple.model, triple.dim, triple.count+ );+ }+ // Only shown when there is something to act on. A recovered count with+ // no outstanding failures is history, not a problem.+ if report.derived.embed_failures_unresolved > 0 {+ let _ = writeln!(+ out,+ " embed failures: {} unresolved ({} recovered since)",+ report.derived.embed_failures_unresolved, report.derived.embed_failures_recovered+ );+ }+ // The figure that makes a `compact` decision possible. Reported+ // always, so "should I VACUUM?" has an answer other than a guess; the+ // advisory line only appears once it is worth the exclusive lock.+ if report.storage.database_bytes > 0 {+ let pct = (report.storage.reclaimable_bytes as f64 / report.storage.database_bytes as f64)+ * 100.0;+ let _ = writeln!(+ out,+ " storage: {} on disk, {} reclaimable ({pct:.1}%)",+ crate::commands::compact::human_bytes(report.storage.database_bytes),+ crate::commands::compact::human_bytes(report.storage.reclaimable_bytes),+ );+ if let Some(free) = report.storage.data_dir_free_bytes {+ let _ = writeln!(+ out,+ " filesystem free: {}",+ crate::commands::compact::human_bytes(free)+ );+ }+ if fix_lines::reclaim_advised(+ report.storage.reclaimable_bytes,+ report.storage.database_bytes,+ ) {+ let _ = writeln!(+ out,+ " `{}` would return it (blocks writes while it runs)",+ fix_lines::COMPACT+ );+ }+ }+ let _ = writeln!(+ out,+ " links: {} latest-page links (unresolved: {}, stale: {})",+ report.derived.links_from_latest_pages,+ report.derived.unresolved_links_from_latest_pages,+ report.derived.stale_links_from_latest_pages+ );+ if !report.derived.typed_links_from_latest_pages.is_empty() {+ let typed: Vec<String> = report+ .derived+ .typed_links_from_latest_pages+ .iter()+ .map(|(k, v)| format!("{k}: {v}"))+ .collect();+ let _ = writeln!(out, " typed edges: {}", typed.join(", "));+ }+ if let Some(wiki) = &report.wiki_format {+ let migrated = if wiki.okf_migrated {+ "OKF v0.2 (migrated)"+ } else {+ "OKF v0.2 (native, no migration needed)"+ };+ match (&wiki.backup_archive, wiki.backup_archive_bytes) {+ (Some(path), Some(bytes)) => {+ let _ = writeln!(+ out,+ " wiki format: {migrated}; pre-migration backup still on disk: \+ {path} ({})",+ crate::commands::compact::human_bytes(bytes)+ );+ }+ _ => {+ let _ = writeln!(out, " wiki format: {migrated}");+ }+ }+ }+ if let Some((queued, capacity)) = report.write_queue {+ // A queue pinned near capacity is the wedged-writer signal.+ if queued > 0 {+ let _ = writeln!(out, " write queue: {queued}/{capacity}");+ }+ }+ let _ = writeln!(out, " spool:");+ let _ = writeln!(out, " pending: {}", spool.pending);+ let _ = writeln!(+ out,+ " oldest: {}",+ spool_age_line(spool.oldest_age_ms)+ );+ let _ = writeln!(out, " retries: {}", spool.retries_total);+ if journal_pending > 0 || journal_error.is_some() {+ let _ = writeln!(out, " recovery:");+ let _ = writeln!(+ out,+ " journal: {journal_pending} pending ({journal_degraded} degraded, {journal_finish_failed} finish-failed)"+ );+ if let Some(error) = &journal_error {+ let _ = writeln!(out, " error: {error}");+ }+ let _ = writeln!(out, " action: run `{}`", fix_lines::RECOVER);+ }+ if let Some(ingest) = &report.ingest {+ let _ = writeln!(out, " ingest (server, this process):");+ let _ = writeln!(out, " accepted: {}", ingest.accepted);+ let _ = writeln!(+ out,+ " dropped: {} (capture policy)",+ ingest.dropped_by_policy+ );+ let _ = writeln!(+ out,+ " outcomes: {} stored, {} replayed, {} resumed, {} ignored end, {} failed",+ ingest.stored, ingest.replayed, ingest.resumed, ingest.ignored_end, ingest.failed+ );+ let _ = writeln!(+ out,+ " drops: {} unauthorized, {} collision, {} invalid",+ ingest.dropped_unauthorized, ingest.dropped_collision, ingest.dropped_invalid+ );+ let _ = writeln!(+ out,+ " shed: {} saturated, {} rate-limited",+ ingest.shed_saturated, ingest.shed_rate_limited+ );+ let _ = writeln!(+ out,+ " last write: {}",+ last_write_line(ingest.last_persisted_ms)+ );+ }+ // #446 + #428 interact here: under allowlist mode an unmarked+ // repository never sends, so zero counters read exactly like a broken+ // install. Deliberately outside the ingest block above: the mode is a+ // client-side fact, and an older server returns no ingest section at+ // all — which is precisely a case where the operator needs telling.+ if capture_mode == "allowlist" {+ let _ = writeln!(+ out,+ " capture mode: allowlist — repositories without a \+ .ai-memory.toml marker send nothing"+ );+ }+ let _ = writeln!(out, " providers:");+ let _ = writeln!(+ out,+ " llm: {}",+ provider_health_line(&report.providers.llm)+ );+ let _ = writeln!(+ out,+ " embedding: {}",+ provider_health_line(&report.providers.embedding)+ );+ if report.providers.llm.status == ProviderHealthStatus::Error+ && let Some(hint) = &report.providers.llm.retry_hint+ {+ let _ = writeln!(out, " retry: {hint}");+ }+ // Only present when `llm_fallbacks` is configured — an older server+ // or a plain single-provider setup reports an empty list.+ if !report.providers.llm_candidates.is_empty() {+ let _ = writeln!(out, " fallback chain:");+ for candidate in &report.providers.llm_candidates {+ let _ = writeln!(out, " {}", fallback_candidate_line(candidate));+ }+ }+ out+}+#[cfg(test)]mod tests {use super::*;@@ -831,4 +904,61 @@ mod tests {assert_eq!(spool_age_line(Some(3_661_000)), "1h 1m");assert_eq!(spool_age_line(Some(172_800_000)), "2d 0h");}++ #[test]+ fn empty_overview_keeps_capture_unverified_and_diagnostics_available() {+ let report: Report = serde_json::from_value(serde_json::json!({+ "version":"3.0.0", "data_dir":"/fixture/data", "bind":"127.0.0.1:49374",+ "db_path":"/fixture/data",+ "counts":{"pages_latest":0,"pages_all":0,"sessions":0,"observations":0}+ }))+ .unwrap();+ let spool = SpoolHealth::default();+ let endpoint = ServerEndpoint::from_pair(Some("http://127.0.0.1:49374".into()), None);+ let terminal = crate::terminal::Terminal::stdout(&Config::default().runtime_env);+ let details = details(+ &report,+ &spool,+ 0,+ 0,+ 0,+ &None,+ "denylist",+ &endpoint,+ crate::local_auth::AuthPosture::NoneLoopback,+ );+ let text = presentation::render(&terminal, &report, &spool, &endpoint, &details);+ assert!(text.contains("WAITING FOR YOUR FIRST SESSION"), "{text}");+ assert!(text.contains("capture has not been verified"), "{text}");+ for field in [+ "/fixture/data",+ "auth:",+ "none (loopback)",+ "OPTIONAL MODELS",+ "fts:",+ "ai-memory status --json",+ ] {+ assert!(text.contains(field), "missing {field}: {text}");+ }+ }++ #[test]+ fn an_evicting_queue_takes_priority_over_the_empty_state() {+ let report: Report = serde_json::from_value(serde_json::json!({+ "version":"3.0.0", "data_dir":"/fixture/data", "bind":"127.0.0.1:49374",+ "db_path":"/fixture/data",+ "counts":{"pages_latest":0,"pages_all":0,"sessions":0,"observations":0}+ }))+ .unwrap();+ let spool = SpoolHealth {+ pending: 4,+ capacity: 3,+ ..SpoolHealth::default()+ };+ let endpoint = ServerEndpoint::from_pair(Some("http://127.0.0.1:49374".into()), None);+ let terminal = crate::terminal::Terminal::stdout(&Config::default().runtime_env);+ let text = presentation::render(&terminal, &report, &spool, &endpoint, "");+ assert!(text.contains("CAPTURE NEEDS ATTENTION"), "{text}");+ assert!(!text.contains("WAITING FOR YOUR FIRST SESSION"), "{text}");+ }}diff --git a/crates/ai-memory-cli/src/commands/status/presentation.rs b/crates/ai-memory-cli/src/commands/status/presentation.rsnew file mode 100644index 00000000..22550f89--- /dev/null+++ b/crates/ai-memory-cli/src/commands/status/presentation.rs@@ -0,0 +1,127 @@+//! Runtime overview; complete counters remain available through status --json.++use super::*;+use crate::terminal::{Terminal, Tone};++pub(super) fn render(+ terminal: &Terminal,+ report: &Report,+ spool: &SpoolHealth,+ ep: &ServerEndpoint,+ details: &str,+) -> String {+ let mut out = terminal.header("STATUS / memory & capture", &report.version);+ out.push_str(&terminal.field("Server", &ep.url));+ out.push_str(&terminal.metrics(&[+ ("pages", report.counts.pages_latest),+ ("sessions", report.counts.sessions),+ ("observations", report.counts.observations),+ ]));+ if spool.evicting()+ || report+ .ingest+ .as_ref()+ .is_some_and(|ingest| ingest.failed > 0)+ {+ out.push_str(&terminal.notice(Tone::Warn,"CAPTURE NEEDS ATTENTION", "Review the queue and ingestion counters below.\nRecorded sessions alone do not verify current hook delivery."));+ } else if spool.pending > 0 {+ out.push_str(&terminal.notice(+ Tone::Warn,+ "EVENTS WAITING FOR DELIVERY",+ &format!(+ "{} events are queued locally. Review delivery below.",+ spool.pending+ ),+ ));+ } else if report.counts.sessions == 0 && report.counts.observations == 0 {+ out.push_str(&terminal.notice(Tone::Accent,"WAITING FOR YOUR FIRST SESSION", "Start your agent in a project, then run ai-memory doctor there.\nThe server is responding; capture has not been verified."));+ } else {+ out.push_str(&terminal.field(+ "Capture",+ "Stored sessions found · check doctor for current hook delivery",+ ));+ }+ if report.counts.pages_all > report.counts.pages_latest {+ out.push_str(&terminal.field("Page versions", &report.counts.pages_all.to_string()));+ }+ let mut section = "";+ let quiet_delivery = spool.pending == 0+ && !details.contains(" recovery:")+ && report.ingest.as_ref().is_none_or(|ingest| {+ ingest.accepted == 0+ && ingest.failed == 0+ && ingest.dropped_by_policy == 0+ && ingest.dropped_unauthorized == 0+ && ingest.dropped_collision == 0+ && ingest.dropped_invalid == 0+ && ingest.shed_saturated == 0+ && ingest.shed_rate_limited == 0+ });+ for line in details.lines().skip(1) {+ let key = line.trim().split(':').next().unwrap_or("");+ if [+ "server",+ "db",+ "bind",+ "filesystem free",+ "wiki format",+ "providers",+ ]+ .contains(&key)+ {+ continue;+ }+ if key == "embeddings"+ && report.derived.embedding_rows == 0+ && report.derived.latest_pages_missing_embeddings == 0+ {+ continue;+ }+ if key == "links"+ && report.derived.links_from_latest_pages == 0+ && report.derived.unresolved_links_from_latest_pages == 0+ && report.derived.stale_links_from_latest_pages == 0+ {+ continue;+ }+ if quiet_delivery+ && [+ "spool",+ "pending",+ "oldest",+ "retries",+ "ingest (server, this process)",+ "accepted",+ "dropped",+ "outcomes",+ "drops",+ "shed",+ "last write",+ ]+ .contains(&key)+ {+ continue;+ }+ let next = match key {+ "server" | "data-dir" | "db" | "bind" | "auth" => "CONNECTION",+ "pages" | "sessions" | "observations" => continue,+ "fts" | "embeddings" => "SEARCH INDEX",+ "storage" | "links" | "wiki format" => "STORAGE & LINKS",+ "write queue"+ | "spool"+ | "recovery"+ | "ingest (server, this process)"+ | "capture mode" => "CAPTURE & DELIVERY",+ "providers" | "llm" | "embedding" => "OPTIONAL MODELS",+ _ => section,+ };+ if next != section {+ out.push_str(&terminal.section(next));+ section = next;+ }+ out.push_str(&terminal.document(line));+ }+ out.push_str(&terminal.section("Inspect"));+ out.push_str(&terminal.field("Full details", "ai-memory status --json"));+ out+}diff --git a/crates/ai-memory-cli/src/lib.rs b/crates/ai-memory-cli/src/lib.rsindex 467a5c8e..073beeda 100644--- a/crates/ai-memory-cli/src/lib.rs+++ b/crates/ai-memory-cli/src/lib.rs@@ -29,6 +29,7 @@ mod logging;mod marker;mod process_guard;mod server_profiles;+mod terminal;use cli::{Cli, Command};use config::Config;@@ -75,7 +76,14 @@ pub async fn run() -> Result<()> {} else {logging::DegradeWarnings::Quiet};- let _logging_guard = logging::init(&config, degrade_warnings)?;+ let _logging_guard = if matches!(+ command,+ Command::Setup(_) | Command::Doctor(_) | Command::Status(_)+ ) {+ logging::init_for_console(&config, degrade_warnings, true)?+ } else {+ logging::init(&config, degrade_warnings)?+ };info!(version = env!("CARGO_PKG_VERSION"),diff --git a/crates/ai-memory-cli/src/logging.rs b/crates/ai-memory-cli/src/logging.rsindex 5449dd41..3df736fd 100644--- a/crates/ai-memory-cli/src/logging.rs+++ b/crates/ai-memory-cli/src/logging.rs@@ -20,10 +20,10 @@ use std::path::{Path, PathBuf};use anyhow::Result;use tracing_appender::non_blocking::WorkerGuard;use tracing_appender::rolling::{RollingFileAppender, Rotation};-use tracing_subscriber::EnvFilter;use tracing_subscriber::filter::LevelFilter;use tracing_subscriber::layer::SubscriberExt;use tracing_subscriber::util::SubscriberInitExt;+use tracing_subscriber::{EnvFilter, Layer as _};use crate::config::Config;@@ -130,6 +130,15 @@ fn default_filter(log_level: &str) -> String {/// I/O problems degrade instead of erroring so a read-only filesystem can/// never take down a command that would otherwise succeed.pub fn init(config: &Config, warnings: DegradeWarnings) -> Result<Option<WorkerGuard>> {+ init_for_console(config, warnings, false)+}++/// Keep routine onboarding logs in the file, while preserving warnings and explicit RUST_LOG.+pub(crate) fn init_for_console(+ config: &Config,+ warnings: DegradeWarnings,+ concise: bool,+) -> Result<Option<WorkerGuard>> {let log_dir = config.data_dir.join("logs");let (file, notices) = resolve_file_appender(&log_dir, &std::env::temp_dir());if warnings == DegradeWarnings::Loud {@@ -143,7 +152,18 @@ pub fn init(config: &Config, warnings: DegradeWarnings) -> Result<Option<WorkerGlet stderr_layer = tracing_subscriber::fmt::layer().with_target(true)- .with_writer(std::io::stderr);+ .with_writer(std::io::stderr)+ .with_ansi(+ std::io::IsTerminal::is_terminal(&std::io::stderr())+ && config.runtime_env.var_os("NO_COLOR").is_none(),+ )+ .with_filter(+ if concise && config.runtime_env.var_os("RUST_LOG").is_none() {+ LevelFilter::WARN+ } else {+ LevelFilter::TRACE+ },+ );let registry = tracing_subscriber::registry().with(env_filter)diff --git a/crates/ai-memory-cli/src/terminal.rs b/crates/ai-memory-cli/src/terminal.rsnew file mode 100644index 00000000..7e27ab64--- /dev/null+++ b/crates/ai-memory-cli/src/terminal.rs@@ -0,0 +1,243 @@+//! A shared terminal vocabulary: quiet structure, semantic color and bounded motion.++mod progress;++use std::io::IsTerminal as _;++use crate::config::RuntimeEnv;+use crossterm::style::{Color, Stylize as _};++#[derive(Clone, Copy)]+pub(crate) enum Tone {+ Accent,+ Good,+ Warn,+ Bad,+ Muted,+}++pub(crate) struct Terminal {+ color: bool,+ motion: bool,+ width: usize,+ home: Option<String>,+}++impl Terminal {+ pub(crate) fn stdout(env: &RuntimeEnv) -> Self {+ let mut terminal = Self::new(+ std::io::stdout().is_terminal(),+ env.var_os("NO_COLOR").is_some(),+ env.var_os("TERM").is_some_and(|term| term == "dumb"),+ );+ terminal.home = env+ .var_os("AI_MEMORY_HOME")+ .or_else(|| env.var_os("HOME"))+ .map(|home| home.to_string_lossy().into_owned());+ terminal.motion = terminal.color && env.var_os("CI").is_none();+ if terminal.color+ && let Ok((width, _)) = crossterm::terminal::size()+ {+ terminal.width = usize::from(width).clamp(24, 80);+ }+ terminal+ }++ fn new(tty: bool, no_color: bool, dumb: bool) -> Self {+ Self {+ color: tty && !no_color && !dumb,+ motion: tty && !no_color && !dumb,+ width: 80,+ home: None,+ }+ }++ pub(crate) fn ink(&self, text: &str, tone: Tone) -> String {+ if !self.color {+ return text.to_owned();+ }+ let color = match tone {+ Tone::Accent => Color::Cyan,+ Tone::Good => Color::Green,+ Tone::Warn => Color::Yellow,+ Tone::Bad => Color::Red,+ Tone::Muted => Color::Grey,+ };+ match tone {+ Tone::Muted => text.with(color).to_string(),+ _ => text.with(color).bold().to_string(),+ }+ }++ pub(crate) fn header(&self, command: &str, version: &str) -> String {+ format!(+ "\n {} {}\n {}\n {}\n\n",+ self.ink("◈ ai-memory", Tone::Accent),+ self.ink(&format!("v{version}"), Tone::Muted),+ wrap(command, self.width.saturating_sub(4).max(8)).join("\n "),+ self.ink(+ &"─".repeat(self.width.saturating_sub(4).min(64)),+ Tone::Muted+ )+ )+ }++ pub(crate) fn section(&self, name: &str) -> String {+ format!("\n {}\n", self.ink(&name.to_uppercase(), Tone::Accent))+ }++ pub(crate) fn field(&self, name: &str, value: &str) -> String {+ let short = self+ .home+ .as_ref()+ .and_then(|home| value.strip_prefix(home))+ .filter(|tail| tail.is_empty() || tail.starts_with('/'))+ .map(|tail| format!("~{tail}"));+ let value = short.as_deref().unwrap_or(value);+ let mut label = format!("{name:<14}");+ if name.chars().count() >= 14 {+ label.push(' ');+ }+ let indent = label.chars().count();+ let mut out = String::new();+ for (index, line) in wrap(value, self.width.saturating_sub(indent + 2).max(8))+ .iter()+ .enumerate()+ {+ out.push_str(&format!(+ " {}{line}\n",+ if index == 0 {+ self.ink(&label, Tone::Muted)+ } else {+ " ".repeat(indent)+ }+ ));+ }+ out+ }++ pub(crate) fn notice(&self, tone: Tone, title: &str, body: &str) -> String {+ let titles = wrap(title, self.width.saturating_sub(6).max(8));+ let mut out = String::from("\n");+ for (index, title) in titles.iter().enumerate() {+ out.push_str(&format!(+ " {} {}\n",+ self.ink(if index == 0 { "╭─" } else { "│ " }, tone),+ self.ink(title, tone)+ ));+ }+ for paragraph in body.lines() {+ for line in wrap(paragraph, self.width.saturating_sub(6).max(8)) {+ out.push_str(&format!(" {} {line}\n", self.ink("│", tone)));+ }+ }+ out.push_str(&format!(" {}\n", self.ink("╰─", tone)));+ out+ }++ pub(crate) fn metrics(&self, metrics: &[(&str, u64)]) -> String {+ if self.width < 56 {+ return metrics+ .iter()+ .map(|(name, value)| self.field(name, &value.to_string()))+ .collect();+ }+ let mut values = String::from(" ");+ let mut labels = String::from(" ");+ for (name, value) in metrics {+ values.push_str(&self.ink(&format!("{:<20}", value), Tone::Accent));+ labels.push_str(&self.ink(&format!("{name:<20}"), Tone::Muted));+ }+ format!("{values}\n{labels}\n")+ }++ /// Group existing diagnostics without discarding their fields or remedies.+ pub(crate) fn document(&self, text: &str) -> String {+ let mut out = String::new();+ for line in text.lines() {+ let content = line.trim();+ if let Some((key, value)) = content.split_once(':')+ && !value.trim().is_empty()+ && key.len() <= 18+ && !content.starts_with(['!', '⚠'])+ {+ out.push_str(&self.field(&format!("{key}:"), value.trim()));+ } else {+ if !self.color {+ out.push_str(line);+ out.push('\n');+ } else {+ let indent = line.len() - line.trim_start().len();+ let prefix = " ".repeat(indent);+ for part in wrap(+ line.trim_start(),+ self.width.saturating_sub(indent + 2).max(8),+ ) {+ out.push_str(&self.paint(&format!("{prefix}{part}\n")));+ }+ }+ }+ }+ out+ }++ pub(crate) fn paint(&self, text: &str) -> String {+ text.split_inclusive('\n')+ .map(|line| {+ let content = line.trim_end_matches('\n');+ let tone = match content.trim_start() {+ s if s.starts_with('✓') => Some(Tone::Good),+ s if s.starts_with('!')+ || s.starts_with('⚠')+ || s.starts_with("Action required") =>+ {+ Some(Tone::Warn)+ }+ s if s.starts_with('✗') || s.starts_with("problem:") => Some(Tone::Bad),+ s if s.starts_with("ai-memory ") => Some(Tone::Accent),+ _ => None,+ };+ tone.map_or_else(+ || line.to_owned(),+ |tone| {+ format!(+ "{}{}",+ self.ink(content, tone),+ if line.ends_with('\n') { "\n" } else { "" }+ )+ },+ )+ })+ .collect()+ }+}++/// Wrap without truncating paths, commands or recovery instructions.+fn wrap(text: &str, width: usize) -> Vec<String> {+ if text.is_empty() {+ return vec![String::new()];+ }+ let mut lines = Vec::new();+ let mut current = String::new();+ for ch in text.chars() {+ current.push(ch);+ if current.chars().count() >= width {+ if let Some(space) = current.rfind(' ')+ && space > current.len() / 2+ {+ let remainder = current[space + 1..].to_owned();+ lines.push(current[..space].to_owned());+ current = remainder;+ } else {+ lines.push(std::mem::take(&mut current));+ }+ }+ }+ if !current.is_empty() {+ lines.push(current);+ }+ lines+}++#[cfg(test)]+mod tests;diff --git a/crates/ai-memory-cli/src/terminal/progress.rs b/crates/ai-memory-cli/src/terminal/progress.rsnew file mode 100644index 00000000..511f0c41--- /dev/null+++ b/crates/ai-memory-cli/src/terminal/progress.rs@@ -0,0 +1,38 @@+//! One in-place indicator, scoped to a real future and cleared on cancellation.++use super::{Terminal, Tone};+use std::future::Future;+use std::io::{Write as _, stdout};+use std::time::Duration;++struct Line;+impl Drop for Line {+ fn drop(&mut self) {+ print!("\r\x1b[2K");+ let _ = stdout().flush();+ }+}++impl Terminal {+ pub(crate) async fn waiting<T>(&self, label: &str, future: impl Future<Output = T>) -> T {+ if !self.motion {+ return future.await;+ }+ let _line = Line;+ let mut tick = tokio::time::interval(Duration::from_millis(140));+ let frames = ["● · ·", "· ● ·", "· · ●", "· ● ·"];+ let mut index = 0;+ let label: String = label.chars().take(self.width.saturating_sub(9)).collect();+ tokio::pin!(future);+ loop {+ tokio::select! {+ biased;+ result = &mut future => return result,+ _ = tick.tick() => {+ print!("\r\x1b[2K {} {}", self.ink(frames[index % frames.len()], Tone::Accent), label);+ let _ = stdout().flush(); index += 1;+ }+ }+ }+ }+}diff --git a/crates/ai-memory-cli/src/terminal/tests.rs b/crates/ai-memory-cli/src/terminal/tests.rsnew file mode 100644index 00000000..29e56a65--- /dev/null+++ b/crates/ai-memory-cli/src/terminal/tests.rs@@ -0,0 +1,46 @@+use super::*;++#[test]+fn styles_and_motion_are_opted_out_together() {+ for (tty, no_color, dumb) in [+ (false, false, false),+ (true, true, false),+ (true, false, true),+ ] {+ let term = Terminal::new(tty, no_color, dumb);+ let output = term.header("Setup", "3.0.0")+ + &term.notice(Tone::Warn, "Action required", "Run /hooks");+ assert!(!output.contains('\u{1b}'));+ assert!(!term.motion);+ assert!(output.contains("Run /hooks"));+ }+ assert!(+ Terminal::new(true, false, false)+ .header("Status", "3.0.0")+ .contains('\u{1b}')+ );+}++#[test]+fn narrow_layout_wraps_instead_of_losing_instructions() {+ let mut term = Terminal::new(false, false, false);+ term.width = 32;+ let output = term.field("Storage", "/long/path/with/essential/information")+ + &term.notice(+ Tone::Warn,+ "Pending",+ "Open Codex, run /hooks, and approve the hooks.",+ );+ assert!(+ output.lines().all(|line| line.chars().count() <= 32),+ "{output}"+ );+ assert!(output.contains("/hooks"));+ assert!(term.metrics(&[("sessions", 12)]).contains("12"));+}++#[tokio::test]+async fn plain_progress_returns_the_actual_result_without_controls() {+ let term = Terminal::new(false, false, false);+ assert_eq!(term.waiting("Checking", async { 42 }).await, 42);+}diff --git a/crates/ai-memory-cli/tests/suite/setup_e2e.rs b/crates/ai-memory-cli/tests/suite/setup_e2e.rsindex 7f9abff8..b1bff218 100644--- a/crates/ai-memory-cli/tests/suite/setup_e2e.rs+++ b/crates/ai-memory-cli/tests/suite/setup_e2e.rs@@ -112,9 +112,9 @@ fn setup_without_yes_and_without_a_terminal_changes_nothing() {let out = sandbox.cmd(Some(port)).arg("setup").output().unwrap();assert!(!out.status.success(), "{}", text(&out));let stdout = String::from_utf8_lossy(&out.stdout);- assert!(stdout.contains("ai-memory setup will:"), "{}", text(&out));+ assert!(stdout.contains("SETUP / connect"), "{}", text(&out));assert!(- stdout.contains("wire claude-code (detected)"),+ stdout.contains("Connect claude-code (detected)"),"{}",text(&out));@@ -268,8 +268,8 @@ esaclet first = setup(&sandbox, &service, port, &["--yes"]);assert!(first.status.success(), "{}", text(&first));let stdout = String::from_utf8_lossy(&first.stdout);- assert!(stdout.contains("healthz: ok"), "{}", text(&first));- assert!(stdout.contains("memory_status: ok"), "{}", text(&first));+ assert!(stdout.contains("Server responding"), "{}", text(&first));+ assert!(stdout.contains("Memory API responding"), "{}", text(&first));let data_dir = sandbox.data_dir();let token = std::fs::read_to_string(data_dir.join("auth-tokens/default"))@@ -470,4 +470,5 @@ esacassert_eq!(std::fs::read_to_string(&unit_path).unwrap(), foreign);assert!(service.calls().is_empty(), "{:?}", service.calls());}+ include!("setup_e2e/first_run.rs");}diff --git a/crates/ai-memory-cli/tests/suite/setup_e2e/first_run.rs b/crates/ai-memory-cli/tests/suite/setup_e2e/first_run.rsnew file mode 100644index 00000000..7268f5db--- /dev/null+++ b/crates/ai-memory-cli/tests/suite/setup_e2e/first_run.rs@@ -0,0 +1,80 @@+/// The native hook-trust protocol is simulated; storage, MCP and HTTP run+/// through the real executable. The operator's Codex is never started.+#[tokio::test]+async fn setup_names_pending_codex_trust_and_keeps_the_first_run_neutral() {+ use std::os::unix::fs::PermissionsExt as _;+ let sandbox = Sandbox::new();+ let service = Service::new(&sandbox.root);+ let hooks = sandbox.home.join(".codex/hooks.json");+ let reply = json!({"jsonrpc":"2.0", "id":2, "result":{"data":[{"hooks":[{+ "eventName":"sessionStart", "trustStatus":"untrusted", "sourcePath":hooks,+ "command":"ai-memory hook --event session-start --agent codex"+ }]}]}}).to_string();+ let fake = service.bin.join("codex");+ std::fs::write(&fake, format!(+ "#!/bin/sh\nwhile IFS= read -r line; do\ncase \"$line\" in\n*'\"id\":2'*) printf '%s\\n' '{}' ;;\nesac\ndone\n", reply+ )).unwrap();+ std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();+ let port = crate::e2e_support::free_port();+ let out = setup(&sandbox, &service, port, &["--yes", "--agent", "codex", "--agent", "claude-code"]);+ assert!(out.status.success(), "{}", text(&out));+ let stdout = String::from_utf8_lossy(&out.stdout);+ assert!(stdout.contains("Installation complete · Action required"), "{stdout}");+ assert!(stdout.contains("Hook approval required"), "{stdout}");+ assert!(stdout.contains("run /hooks"), "{stdout}");+ assert!(!stdout.contains("install-hooks --agent codex --apply"), "{stdout}");+ assert!(!stdout.contains("ran here but nothing was captured"), "{stdout}");+ assert!(!stdout.contains("Every harness"), "{stdout}");+ assert!(!stdout.contains("\u{1b}["), "piped setup must be plain text");+}++#[test]+fn failed_connection_never_claims_installation_complete() {+ let sandbox = Sandbox::new();+ let port = crate::e2e_support::free_port();+ let out = sandbox.cmd(Some(port)).args(["setup", "--yes", "--no-service", "--agent", "claude-code"]).output().unwrap();+ assert!(!out.status.success(), "{}", text(&out));+ let stdout = String::from_utf8_lossy(&out.stdout);+ assert!(stdout.contains("Installation incomplete"), "{stdout}");+ assert!(stdout.contains("Resolve the problems below"), "{stdout}");+ assert!(!stdout.contains("Installation complete"), "{stdout}");+}++#[test]+fn setup_keeps_files_backups_and_actions_in_grouped_agent_reports() {+ use std::os::unix::fs::PermissionsExt as _;+ let sandbox = Sandbox::new();+ let service = Service::new(&sandbox.root);+ let fake = service.bin.join("codex");+ std::fs::write(&fake, "#!/bin/sh\nexit 1\n").unwrap();+ std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();+ let existing = [".claude.json", ".claude/settings.json", ".codex/hooks.json", ".gemini/config/mcp_config.json"];+ for file in existing {+ let path = sandbox.home.join(file);+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();+ std::fs::write(path, "{}").unwrap();+ }+ std::fs::write(sandbox.home.join(".codex/config.toml"), "").unwrap();+ let port = crate::e2e_support::free_port();+ let out = setup(&sandbox, &service, port, &["--yes", "--agent", "claude-code", "--agent", "codex", "--agent", "open-code", "--agent", "antigravity-cli"]);+ assert!(out.status.success(), "{}", text(&out));+ let stdout = String::from_utf8_lossy(&out.stdout);+ let compact = stdout.split_whitespace().collect::<Vec<_>>().join(" ");+ for file in existing.into_iter().chain([".codex/config.toml", ".config/opencode/opencode.json", ".config/opencode/plugins/ai-memory.ts", ".gemini/config/hooks.json"]) {+ assert!(stdout.contains(&format!("~/{file}")), "{file}: {}", text(&out));+ assert!(sandbox.home.join(file).exists(), "{file}");+ }+ assert_eq!(compact.matches("backup written next to it").count(), 5, "{stdout}");+ assert_eq!(stdout.matches("capture-policy capability").count(), 0, "{stdout}");+ assert_eq!(stdout.matches("Capture-policy capability").count(), 1, "{stdout}");+ for information in ["denylist", "staged 18 hook script(s)", "staged 14 hook script(s)", "staged 8 hook script(s)", "$AI_MEMORY_AUTH_TOKEN", "Hooks need review", "Trust all and continue", "trust individually", "codex --dangerously-bypass-hook-trust", "review hook scripts first", "OpenCode auto-loads plugins", "one execution loop, not the conversation", "ai-memory finalize-session --agent antigravity-cli", "final summary and handoff", "opt-in SessionEnd consolidation"] {+ assert!(compact.contains(information), "{information}: {}", text(&out));+ }+ assert!(stdout.contains("AGENT NEXT STEPS"), "{stdout}");+ assert!(!stdout.contains('\u{1b}'), "redirected setup must remain plain: {stdout}");+ let stderr = String::from_utf8_lossy(&out.stderr);+ assert!(!stderr.contains("hook script(s)"), "{stderr}");+ assert!(!stderr.contains("capture-policy capability"), "{stderr}");+ let token = std::fs::read_to_string(sandbox.data_dir().join("auth-tokens/default")).unwrap();+ assert!(!text(&out).contains(token.trim()));+}diff --git a/docs/first-run.md b/docs/first-run.mdnew file mode 100644index 00000000..cac2eae0--- /dev/null+++ b/docs/first-run.md@@ -0,0 +1,35 @@+# First-run checks++`ai-memory setup` checks installation, server connectivity and the memory API.+These checks do not verify that an agent is delivering session events.++- **Hook approval required:** open Codex, run `/hooks`, and approve the+ ai-memory hooks. Setup does not bypass this approval.+- **Restart required:** restart the selected agent to load its integration.+- **Capture not yet verified:** start a session in a project, then run+ `ai-memory doctor` from that project. Existing local sessions may predate+ installation; zero captured sessions alone does not identify the cause.+- **Installation incomplete:** resolve the reported problems and re-run setup.++Doctor checks the current Codex approval state even when the server contains+older captured sessions. Detected Codex and Claude Code hooks with no captures+get restart and delivery checks rather than a reinstallation instruction.+Inactive agents with no captures have a neutral status.++Setup and doctor use status colors on interactive terminals. `NO_COLOR` or+`TERM=dumb` disables colors. Redirected output and `doctor --json` stay plain.+Routine startup traces stay in the log file for setup, doctor and status;+`RUST_LOG=info` or `RUST_LOG=debug` also shows tracing on stderr. Installer+warnings and failures remain visible.++Setup groups changed files, backup notices and script counts by agent, combines+identical capture-policy messages with their agent names, and keeps token,+hook-trust, restart and finalization instructions in an agent next-steps section.+Standalone `install-mcp` and `install-hooks` keep their detailed output.++The installer, setup, status and doctor share section headings, status colors,+and a compact header. Status highlights memory counts and only expands quiet+queues when there is activity; `status --json` keeps all diagnostic fields.+Setup shows a single moving indicator while awaiting the service or network+checks. It never adds a delay or invents a completion percentage. Redirected+output, `NO_COLOR`, and `TERM=dumb` disable motion; CI also uses static progress.diff --git a/install.sh b/install.shindex 9b9dfa2a..d664a82e 100755--- a/install.sh+++ b/install.sh@@ -31,12 +31,35 @@ set -euDEFAULT_RELEASE_BASE="https://github.com/akitaonrails/ai-memory/releases"+# Color is presentation only: redirected output and NO_COLOR stay plain.+install_color=0+ui_init() {+ if [ -t 1 ] && [ "${TERM:-}" != dumb ] && [ -z "${NO_COLOR+x}" ]; then+ install_color=1+ printf '\n \033[1;36m◈ ai-memory\033[0m\n INSTALL / native release\n'+ printf ' \033[90m────────────────────────────────────────\033[0m\n\n'+ fi+}+say() {- printf 'ai-memory install: %s\n' "$*"+ if [ "$install_color" = 0 ]; then+ printf 'ai-memory install: %s\n' "$*"+ return+ fi+ case "$*" in+ downloading*) printf ' \033[1;36m↓\033[0m %s\n' "$*" ;;+ next:*) printf '\n \033[1;36mNEXT\033[0m\n %s\n\n' "${*#next: }" ;;+ *'not on PATH'*) printf ' \033[1;33m!\033[0m %s\n' "$*" ;;+ *) printf ' \033[1;32m✓\033[0m %s\n' "$*" ;;+ esac}die() {- printf 'ai-memory install: error: %s\n' "$*" >&2+ if [ "$install_color" = 1 ] && [ -t 2 ]; then+ printf '\n \033[1;31mINSTALLATION STOPPED\033[0m\n %s\n\n' "$*" >&2+ else+ printf 'ai-memory install: error: %s\n' "$*" >&2+ fiexit 1}@@ -146,6 +169,7 @@ check_members() {}main() {+ ui_inithome="${HOME:-}"[ -n "$home" ] || die "HOME is not set"bin_dir="${AI_MEMORY_BIN_DIR:-$home/.local/bin}"