Skip to content

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

Rust

feat(cli): scope diagnostic presentation to release/3.1

SrDouglaxa7414f7ab853
diff --cc CHANGELOG.md
index 4a936f50,d5073cea..2817dd13
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -11,208 -11,16 +11,211 @@@ version in [`docs/changelog/`](docs/cha
## [Unreleased]
+### Added
++- Grouped interactive `status` and `doctor` reports into sections with semantic
++ colors, retaining every diagnostic field and remedy. Redirected, `NO_COLOR`,
++ `TERM=dumb` and JSON reports kept their existing stdout format. (#1313)
+- Added opt-in session inspection and owned-session purging for signed-in
+ browser users, enabled at runtime with `serve --enable-session-management`
+ (`AI_MEMORY_ENABLE_SESSION_MANAGEMENT`). A user can purge only a session they
+ own in a project they may write; an Admin can purge any. Requested in #1231.
+ (#1267)
+- Added opt-in self-service `aim_` API keys for signed-in browser users,
+ enabled at runtime with `serve --enable-self-service-keys`
+ (`AI_MEMORY_ENABLE_SELF_SERVICE_KEYS`). Labels must be 1 to 128 characters
+ and a user may hold at most 20 active keys. A self-issued key survives a
+ password reset or account disable and must be revoked separately. Requested
+ in #1231. (#1268)
+- Added `ai-memory search --global`, which searches the wiki pages of every
+ project from the terminal instead of only the current one. Each hit shows
+ its `workspace/project` in the text output and carries `workspace` and
+ `project` fields in `--json`. The flag cannot be combined with
+ `--workspace` or `--project`, and a search without it still resolves its
+ scope from the current directory. The server side is `GET /admin/search`
+ with no `workspace`/`project`: its hits now include `workspace` and
+ `project` next to the fields they already had, and the route stays
+ root-only on a multi-user server. Global search covers wiki pages only;
+ raw observations and a search limited to one workspace are not part of
+ this change. (#1253)
+- Added kind and tier filters to the web search. The search page in `/web`
+ has "Kind" and "Tier" selects, and `/web/search` accepts `kind` and `tier`
+ for both a project search and a cross-project one. Every retrieval stream
+ applies the filter in its own query, so other kinds cannot crowd out a rare
+ one, a filtered search asks the streams for no more candidates than an
+ unfiltered one, and the reranker scores only pages the filter keeps. Kind
+ and tier both ignore case, a nonstandard kind is flagged on an empty
+ result, and "Search all projects" keeps the filters. An unknown `tier` is
+ a 400. (#1248)
+- Added `ai-memory setup --plan`, which prints the plan and changes nothing,
+ and `--plan --json`, which prints it as a JSON document with a `format`
+ version for a script or front end to render. The plan now says what each
+ detected agent was found by (its session store, its MCP config, or Muse's
+ directory), numbers the agents, and lists the other agents `--agent`
+ accepts. At the prompt you can type the numbers of the agents to wire
+ instead of `y`; a number outside the plan changes nothing. (#1270)
+- Added a native Windows path to the two-command install. `install.ps1`,
+ published with each release next to its own `.sha256`, checks the release
+ zip against that checksum, refuses archive entries that are absolute or
+ hold `..`, unpacks it under `%LOCALAPPDATA%\Programs\ai-memory` and adds
+ that directory to the user `PATH` (`AI_MEMORY_NO_MODIFY_PATH=1` skips it),
+ with no administrator rights. `ai-memory setup` now has a service step on
+ Windows: it writes an `ai-memory` value under the per-user `Run` key that
+ starts a hidden `ai-memory service-host` at logon, and starts it right away.
+ The value is written and read through the registry API, not by running
+ `reg.exe`: an unsigned binary running `reg.exe add` on the `Run` key is a
+ common persistence signal, and Bitdefender's behavioral engine quarantined
+ `ai-memory.exe` for it (#1280). Its paths are written plainly, without the
+ `\\?\` prefix a canonical path carries. Stopping the host does not run
+ `taskkill` either: `setup` and `uninstall` leave a stop request in the data
+ dir, and the host kills the server it started and exits. `taskkill` is
+ only the fallback for a host that does not answer within ten seconds (one
+ started by an older binary, or a hung one) or a server whose host already
+ died.
+ The host runs the server with no console window and restarts it after a
+ failure, giving up after five failures within ten seconds of starting.
+ `ai-memory uninstall --apply` stops the host and removes the value when it
+ still has the shape `setup` writes and names this install's data dir, so an
+ uninstall against another data dir (a second install, a test's temporary
+ one) leaves the entry alone. `ai-memory doctor` and `ai-memory status`
+ warn (`logon_binary_missing`, also in their `--json` output and when
+ `status` cannot reach the server) when that entry names an
+ `ai-memory.exe` that no longer exists, which is what an antivirus
+ quarantine leaves behind, and say how to restore the binary or remove the
+ entry. (#1271, #1280, #1300, #1311)
+- Added `ai-memory setup --web`, which shows the setup plan as a page in
+ your browser and applies the agents you tick there by running `ai-memory
+ setup --yes --agent ...` and streaming its output to the page. The page is
+ served on `127.0.0.1` behind a one-time address printed in the terminal
+ (opened in the browser unless `--no-open` or there is no desktop), refuses
+ requests with another `Host`, without the address's secret, or, for a
+ change, without the page's own `Origin` and CSRF token, and holds no token.
+ It stops on Finish, after 15 minutes without a request, or on Ctrl-C. (#1272)
+- Added a desktop installer preview, `companions/ai-memory-desktop`: a Tauri
+ app that uses an existing `ai-memory` install or copies its bundled one into
+ the same per-user location as `install.sh` and `install.ps1`, then shows the
+ `ai-memory setup --web` page in its own window. CI builds unsigned Linux,
+ macOS and Windows installers on manual dispatch; they are not attached to
+ releases until the project signs them. `setup --web` gained a hidden
+ `--stop-on-stdin-eof` flag so the page stops when the app does. (#1273)
+- A prompt that starts with `reload context` (for example `reload context
+ after last compaction, then …`) now puts the stretch of the session that
+ its last compaction dropped back in front of the agent: the prompts typed
+ between the latest two compactions, verbatim; the last captured reply (with
+ the assistant-capture opt-in); and the project's open handoffs, listed
+ without claiming them. The new read-only `GET /recap` route builds it from
+ captured observations. Claude Code and Codex receive it with that prompt
+ through `UserPromptSubmit` `additionalContext`, OpenCode V1/V2 through the
+ plugin's system/context hook, and Grok Build on the next `PostToolUse`.
+ Serving the recap writes nothing, so a reload never consumes a baton (#1230).
+- Added first-party CodeBuddy Code (Tencent) support. `codebuddy` is an
+ `AgentKind` (migration V81), so hook events are attributed to it and a
+ Claude Code-shaped tool payload (`tool_name`, `tool_input`, `tool_response`)
+ is stored as a closed tool observation instead of an empty `other` capture.
+ `install-hooks --agent codebuddy` (alias `code-buddy`) merges native
+ `ai-memory hook --event … --agent codebuddy` commands for seven events
+ (`SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`,
+ `PreCompact`, `Stop`, `SessionEnd`) into the `hooks` key of
+ `~/.codebuddy/settings.json`, keeps sibling settings and your own hooks,
+ and changes nothing on a re-run. There is no script bundle. The
+ `SessionStart` hook delivers the pending handoff through
+ `hookSpecificOutput.additionalContext`, and a capture-only `SessionStart` or
+ `UserPromptSubmit` prints nothing, since CodeBuddy appends that output to
+ the session. A `SessionStart` without `cwd` falls back to
+ `CODEBUDDY_PROJECT_DIR`. `setup` wires CodeBuddy when
+ `~/.codebuddy` exists, `setup-agent --agent codebuddy` prints the hook
+ block, and `uninstall` removes the entries. Transcript backfill and
+ headless `codebuddy -p` session close are not part of this change.
+ Requested in #1299. (#1312)
+- Added the `memory_restore_page` MCP tool: without `rev` it lists the git
+ checkpoints that changed a page, and with `rev` it writes that version back
+ through the wiki write path (sanitizer, admission, slots and supersession
+ apply), keeping the checkpoint's frontmatter. Restoring can bring back text
+ a root deleted or purged, so both listing and restoring need the same admin
+ authority as `/admin/restore-page`. The MCP surface is now 24 tools. (#1307)
+
+### Changed
+- `ai-memory setup` now ends by naming the agents to restart and the question
+ to ask one of them, "What do you remember about this project?", instead of
+ a generic restart line. `install.sh` names the link's full path in its
+ `next:` line when `~/.local/bin` is not on `PATH`, so the suggested command
+ no longer fails with "command not found". The AUR install and upgrade
+ messages, and the README Fedora, Arch and macOS app steps, point to
+ `ai-memory setup` instead of the manual `init`, `systemctl` and
+ `install-*` commands. (#1270)
+- Changed how the opt-in session-start brief (`[briefing]
+ inject_on_session_start`) spends `max_chars`. Every pinned, `_rules/` and
+ `_slots/` page now gets a short excerpt first, taken from its frontmatter
+ `abstract:` or `summary:`, or else from the prose it opens with (read on
+ into its first list items). The budget left deepens pages to a longer
+ excerpt and then the whole body: pinned and `_slots/` pages first, then
+ pages a few bytes short of whole, then the cheapest bodies. Before, the
+ brief printed whole bodies in order, so one long `_rules/` page was cut with
+ a `[truncated by ...]` note and every page after it became an "omitted"
+ path. Bodies are no longer cut: a body that does not fit whole shows its
+ excerpt. Four or more unpinned excerpts from one folder share a heading,
+ and the omitted list and the closing note point at `memory_read_page`.
+ Small wikis whose pages fit still get every body whole. A project with many
+ standing pages now sees all of them, fewer in full: pin a page, or give it
+ an `abstract:`, to control what it shows. The change adds no marker key
+ and no migration. (#1264)
+
### 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 a hook claiming a handoff from the wrong project when an event named
+ no directory. A `SessionStart` (or Kimi Code's `UserPromptSubmit`, or Grok's
+ first `PostToolUse`) whose payload carried no `cwd` sent `GET /handoff` with
+ no scope, so the server resolved its default project or the caller's last
+ active one, and the hook consumed that project's handoff. The native hook,
+ the shell and PowerShell hook bundles, and the generated OpenCode, OpenCode 2,
+ OMP and Pi integrations now fetch no handoff without a directory, for every
+ agent; the native hook says so on stderr at session start. The handoff stays
+ open for `memory_handoff_accept`. Devin still falls back to
+ `DEVIN_PROJECT_DIR`, then the hook's own directory. (#1312)
+- Fixed `ai-memory setup` reporting "ai-memory is set up" after it installed
+ Codex hooks that Codex had not trusted yet. Codex skips an untrusted hook,
+ so Codex sessions went uncaptured. When Codex was wired, `setup` now asks
+ Codex for the hooks' trust state, the way `doctor` does, and when any are
+ untrusted or modified it names them and says to open Codex, run `/hooks`,
+ and trust them. It still exits 0. (#1313)
+- Fixed `install-instructions` treating a line that is exactly `@AGENTS.md` as
+ proof that Claude Code loads the `AGENTS.md` being written. Claude Code
+ resolves `@path` from the file that contains the import, including in the
+ middle of a sentence, expands `~/` from the home directory, and ignores
+ imports inside code spans and fenced blocks. `@AGENTS.md` in
+ `.claude/CLAUDE.md` loads `.claude/AGENTS.md`, a fenced `@AGENTS.md` loads
+ nothing, and `@AGENTS.md` in a parent directory loads that directory's file.
+ The note now compares the resolved path with the file being written and
+ names the import that reaches it. (#1298)
+- Fixed Antigravity CLI posting a session start and claiming a handoff on every
+ user turn: `invocationNum` restarts at 0 each turn, so only the first turn of
+ a conversation (keyed by `conversationId`) now maps to SessionStart, in the
+ native, shell and PowerShell hooks. Payloads without a `conversationId` keep
+ the previous per-turn behavior. A conversation resumed in a new process does
+ not start a new session, so a handoff left meanwhile is read with
+ `memory_handoff_list` rather than injected. (#1306)
+- Fixed `llm-test --provider anthropic-oauth` reporting Anthropic's refusal of a
+ `claude setup-token` token as a plain rate limit: that 429 now carries a hint
+ that it is not a real rate limit and names the alternatives, which
+ `docs/llm-providers.md` already describes. (#1170)
+- Fixed the curator report treating a per-user focus slot
+ (`_slots/<operator>/current-focus.md`) as an ordinary slot. It only
+ recognised the shared `_slots/current-focus.md`, so with per-user slots the
+ focus slot got the 30-day stale threshold instead of the 7-day one and was
+ reported three weeks late. (#1314)
+- Fixed multi-page consolidation losing every page of a batch when the
+ model gave one page a path that cannot be repaired: a leading slash, a
+ `..` or `.` segment, or an empty segment. Path validation failed the whole
+ session's consolidation, so the valid pages in the same answer were never
+ written. That page is now skipped with a warning and the others are
+ written, as already happened for paths that fail the portability check.
+ (#1315)
+- Fixed auto-improve patches losing track of a page's sections after a code
+ block that contains a different fence. A line of three backticks inside a
+ `~~~` block (or a shorter run inside a longer fence) ended the block early,
+ so the headings after it were missed, and a `replace_section` on the
+ section before them replaced those sections too. Profile harvesting had the
+ same flaw: the code after such a line was read as prose and could be
+ harvested as a preference. A fence now closes only on a run of the same
+ character that is at least as long. (#1316)
- Fixed the thin-client commands ignoring a custom `bind`, which could write
into 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` (and
diff --cc crates/ai-memory-cli/src/commands/doctor.rs
index ca4cda9e,b2b96406..308a6ac1
--- a/crates/ai-memory-cli/src/commands/doctor.rs
+++ b/crates/ai-memory-cli/src/commands/doctor.rs
@@@ -23,9 -23,12 +23,11 @@@
//! 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, BTreeSet};
++mod presentation;
+
-mod summary;
+use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime};
-pub(crate) use summary::setup_diagnostics;
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
@@@ -689,7 -680,24 +691,10 @@@ pub async fn run(config: &Config, args
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
- )
++ presentation::render(
++ &report,
++ &crate::terminal::Terminal::stdout(&config.runtime_env),
+ );
}
Ok(())
}
@@@ -1085,146 -1072,289 +1090,6 @@@ fn render_project_coordinate(coordinate
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);
- }
-
- if let Some(problem) = &report.windows_logon {
- println!("{}", problem.render_human());
- 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 \
-- invalid. Fix the TOML and re-run `ai-memory doctor` to confirm.\n",
-- problem.classification
-- );
-- }
--
-- 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 \
-- `ai-memory install-hooks` reports the selected install path, not the active one.\n"
-- );
-- }
--
-- 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)]
mod tests {
use super::*;
diff --cc crates/ai-memory-cli/src/commands/doctor/presentation.rs
index 00000000,00000000..1f871a29
new file mode 100644
--- /dev/null
+++ b/crates/ai-memory-cli/src/commands/doctor/presentation.rs
@@@ -1,0 -1,0 +1,156 @@@
++//! Human report formatting; collection and diagnostic verdicts stay in the command.
++
++use super::*;
++
++pub(super) fn render(report: &DoctorReport, terminal: &crate::terminal::Terminal) {
++ terminal.header("DOCTOR / capture coverage");
++ terminal.section("Connection");
++ terminal.line(format_args!(
++ "Capture coverage for {}/{} (server {})",
++ report.workspace, report.project, report.server
++ ));
++ if let Some(identity) = &report.identity {
++ terminal.line(format_args!(
++ " identity: {} ({}, server {})",
++ identity.operator.as_deref().unwrap_or("anonymous"),
++ identity.level,
++ identity.version
++ ));
++ } else {
++ terminal.line(format_args!(" identity: unavailable"));
++ }
++ if let Some(posture) = report.auth_posture {
++ terminal.line(format_args!(" auth: {}", posture.line()));
++ }
++ if report.capture_owner_active {
++ terminal.line(format_args!(
++ " 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 {
++ terminal.text(&render_project_coordinate(coordinate));
++ }
++ if let Some(problem) = &report.capture_coverage_problem {
++ terminal.line(format_args!(
++ " capture coverage: unavailable ({})",
++ problem.reason
++ ));
++ }
++ terminal.section("Capture health");
++ terminal.text(&render_capture_health(report));
++ terminal.text(&render_plugins(&report.plugins));
++ terminal.text(&render_muse(report.muse.as_ref()));
++ terminal.text(&super::super::agentmemory_residue::render(
++ &report.agentmemory_residue,
++ ));
++ if report.since_days == 0 {
++ terminal.line(format_args!(" recent window: all on-disk sessions\n"));
++ } else {
++ terminal.line(format_args!(
++ " recent window: last {} days\n",
++ report.since_days
++ ));
++ }
++
++ if let Some(problem) = &report.windows_logon {
++ terminal.line(format_args!("{}", problem.render_human()));
++ }
++
++ if let Some(problem) = &report.marker_capture_problem {
++ terminal.line(format_args!(
++ "⚠ {}: 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 \
++ invalid. Fix the TOML and re-run `ai-memory doctor` to confirm.\n",
++ problem.classification
++ ));
++ }
++
++ if !report.native_memory.is_empty() {
++ terminal.line(format_args!(
++ "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 \
++ `ai-memory install-hooks` reports the selected install path, not the active one.\n"
++ ));
++ }
++
++ if report.rows.is_empty() {
++ if report.capture_coverage_problem.is_some() {
++ terminal.line(format_args!(
++ " No local harness sessions found for this project; server capture counts are unavailable."
++ ));
++ } else {
++ terminal.line(format_args!(
++ " No local harness sessions found for this project and nothing captured yet."
++ ));
++ }
++ return;
++ }
++
++ terminal.section("Agent coverage");
++ for row in &report.rows {
++ let mark = match row.uncaptured {
++ Some(true) => "⚠",
++ Some(false) => "✓",
++ None => "?",
++ };
++ let captured = row
++ .captured
++ .map_or_else(|| "unavailable".to_owned(), |count| count.to_string());
++ terminal.line(format_args!(
++ " {mark} {:<14} {:>4} local ({} recent) → {:>11} captured",
++ row.agent, row.local_total, row.local_recent, captured
++ ));
++ if row.uncaptured == Some(true) {
++ if report.capture_owner_active {
++ terminal.line(format_args!(
++ " No captured session: check the external producer and repository policy."
++ ));
++ } else {
++ terminal.line(format_args!(
++ " └ ran here but nothing was captured — install its hook:\n \
++ ai-memory install-hooks --agent {} --apply",
++ row.agent
++ ));
++ }
++ }
++ if let Some(count) = row.mixed_capture_sessions.filter(|count| *count > 0) {
++ terminal.line(format_args!(
++ " {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) {
++ terminal.line(format_args!(
++ " native memory: {} ({} file{})",
++ memory.path,
++ memory.file_count,
++ if memory.file_count == 1 { "" } else { "s" }
++ ));
++ terminal.line(format_args!(" capture: {}", memory.status));
++ }
++ }
++
++ if report.capture_coverage_problem.is_some() {
++ terminal.line(format_args!(
++ "\nCapture verdict unavailable: server capture counts could not be resolved."
++ ));
++ } else if report.uncaptured.is_empty() {
++ terminal.line(format_args!(
++ "\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."
++ };
++ terminal.line(format_args!(
++ "\n⚠ {} harness(es) ran here recently with no captured sessions: {}.\n {remedy}",
++ report.uncaptured.len(),
++ report.uncaptured.join(", ")
++ ));
++ }
++}
diff --cc crates/ai-memory-cli/src/commands/status.rs
index 5c9d4dfa,eca356c3..0f4ddb5a
--- a/crates/ai-memory-cli/src/commands/status.rs
+++ b/crates/ai-memory-cli/src/commands/status.rs
@@@ -292,184 -280,22 +294,21 @@@ pub async fn run(config: &Config, args
))?
);
} 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());
- if let Some(problem) = &windows_logon {
- print!("{}", problem.render_human());
- }
- 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)
++ presentation::render(
++ &crate::terminal::Terminal::stdout(&config.runtime_env),
++ presentation::View {
++ report: &report,
++ ep: &ep,
++ spool: &spool,
++ journal_pending,
++ journal_degraded,
++ journal_finish_failed,
++ journal_error: journal_error.as_deref(),
++ capture_mode,
++ auth_posture,
++ windows_logon: windows_logon.as_ref(),
++ },
);
- 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(())
}
diff --cc crates/ai-memory-cli/src/commands/status/presentation.rs
index 00000000,22550f89..fcdeb515
mode 000000,100644..100644
--- a/crates/ai-memory-cli/src/commands/status/presentation.rs
+++ b/crates/ai-memory-cli/src/commands/status/presentation.rs
@@@ -1,0 -1,127 +1,224 @@@
-//! Runtime overview; complete counters remain available through status --json.
++//! Human report formatting; every diagnostic field and remedy is retained.
+
+ 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
- ),
++pub(super) struct View<'a> {
++ pub report: &'a Report,
++ pub ep: &'a ServerEndpoint,
++ pub spool: &'a SpoolHealth,
++ pub journal_pending: usize,
++ pub journal_degraded: usize,
++ pub journal_finish_failed: usize,
++ pub journal_error: Option<&'a str>,
++ pub capture_mode: &'a str,
++ pub auth_posture: crate::local_auth::AuthPosture,
++ pub windows_logon: Option<&'a super::super::user_service::MissingLogonBinary>,
++}
++
++pub(super) fn render(terminal: &crate::terminal::Terminal, view: View<'_>) {
++ let View {
++ report,
++ ep,
++ spool,
++ journal_pending,
++ journal_degraded,
++ journal_finish_failed,
++ journal_error,
++ capture_mode,
++ auth_posture,
++ windows_logon,
++ } = view;
++ terminal.header("STATUS / memory & capture");
++ terminal.line(format_args!("ai-memory {} (server)", report.version));
++ terminal.section("Connection");
++ terminal.line(format_args!(" server: {}", ep.url));
++ terminal.line(format_args!(" data-dir: {}", report.data_dir));
++ terminal.line(format_args!(" db: {}", report.db_path));
++ terminal.line(format_args!(" bind: {}", report.bind));
++ terminal.line(format_args!(" auth: {}", auth_posture.line()));
++ if let Some(problem) = &windows_logon {
++ terminal.text(&problem.render_human());
++ }
++ terminal.section("Memory");
++ terminal.line(format_args!(
++ " pages: {} (all versions: {})",
++ report.counts.pages_latest, report.counts.pages_all
++ ));
++ terminal.line(format_args!(" sessions: {}", report.counts.sessions));
++ terminal.line(format_args!(
++ " observations: {}",
++ report.counts.observations
++ ));
++ terminal.section("Search index");
++ terminal.line(format_args!(
++ " fts: pages {}/{}; observations {}/{}",
++ report.derived.pages_fts_rows,
++ report.derived.pages_rows,
++ report.derived.observations_fts_rows,
++ report.derived.observations_rows
++ ));
++ terminal.line(format_args!(
++ " embeddings: {} rows; {} latest pages missing",
++ report.derived.embedding_rows, report.derived.latest_pages_missing_embeddings
++ ));
++ if report.derived.latest_pages_unembeddable > 0 {
++ terminal.line(format_args!(
++ " unembeddable: {} (empty body; no embedder can cover these)",
++ report.derived.latest_pages_unembeddable
+ ));
- } 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",
++ }
++ for triple in &report.derived.embedding_triples {
++ terminal.line(format_args!(
++ " {}/{} dim {}: {} rows",
++ triple.provider, triple.model, triple.dim, triple.count
+ ));
+ }
- if report.counts.pages_all > report.counts.pages_latest {
- out.push_str(&terminal.field("Page versions", &report.counts.pages_all.to_string()));
++ // 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 {
++ terminal.line(format_args!(
++ " embed failures: {} unresolved ({} recovered since)",
++ report.derived.embed_failures_unresolved, report.derived.embed_failures_recovered
++ ));
+ }
- 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;
++ terminal.section("Storage & links");
++ // 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;
++ terminal.line(format_args!(
++ " storage: {} on disk, {} reclaimable ({pct:.1}%)",
++ super::super::compact::human_bytes(report.storage.database_bytes),
++ super::super::compact::human_bytes(report.storage.reclaimable_bytes),
++ ));
++ if let Some(free) = report.storage.data_dir_free_bytes {
++ terminal.line(format_args!(
++ " filesystem free: {}",
++ super::super::compact::human_bytes(free)
++ ));
+ }
- if key == "embeddings"
- && report.derived.embedding_rows == 0
- && report.derived.latest_pages_missing_embeddings == 0
- {
- continue;
++ if fix_lines::reclaim_advised(
++ report.storage.reclaimable_bytes,
++ report.storage.database_bytes,
++ ) {
++ terminal.line(format_args!(
++ " `{}` would return it (blocks writes while it runs)",
++ fix_lines::COMPACT
++ ));
+ }
- 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;
++ }
++ terminal.line(format_args!(
++ " 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();
++ terminal.line(format_args!(" 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)) => terminal.line(format_args!(
++ " wiki format: {migrated}; pre-migration backup still on disk: \
++ {path} ({})",
++ super::super::compact::human_bytes(bytes)
++ )),
++ _ => terminal.line(format_args!(" wiki format: {migrated}")),
+ }
- if quiet_delivery
- && [
- "spool",
- "pending",
- "oldest",
- "retries",
- "ingest (server, this process)",
- "accepted",
- "dropped",
- "outcomes",
- "drops",
- "shed",
- "last write",
- ]
- .contains(&key)
- {
- continue;
++ }
++ terminal.section("Capture & delivery");
++ if let Some((queued, capacity)) = report.write_queue {
++ // A queue pinned near capacity is the wedged-writer signal.
++ if queued > 0 {
++ terminal.line(format_args!(" write queue: {queued}/{capacity}"));
+ }
- 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;
++ }
++ terminal.line(format_args!(" spool:"));
++ terminal.line(format_args!(" pending: {}", spool.pending));
++ terminal.line(format_args!(
++ " oldest: {}",
++ spool_age_line(spool.oldest_age_ms)
++ ));
++ terminal.line(format_args!(" retries: {}", spool.retries_total));
++ if journal_pending > 0 || journal_error.is_some() {
++ terminal.line(format_args!(" recovery:"));
++ terminal.line(format_args!(
++ " journal: {journal_pending} pending ({journal_degraded} degraded, {journal_finish_failed} finish-failed)"
++ ));
++ if let Some(error) = &journal_error {
++ terminal.line(format_args!(" error: {error}"));
++ }
++ terminal.line(format_args!(" action: run `{}`", fix_lines::RECOVER));
++ }
++ if let Some(ingest) = &report.ingest {
++ terminal.line(format_args!(" ingest (server, this process):"));
++ terminal.line(format_args!(" accepted: {}", ingest.accepted));
++ terminal.line(format_args!(
++ " dropped: {} (capture policy)",
++ ingest.dropped_by_policy
++ ));
++ terminal.line(format_args!(
++ " outcomes: {} stored, {} replayed, {} resumed, {} ignored end, {} failed",
++ ingest.stored, ingest.replayed, ingest.resumed, ingest.ignored_end, ingest.failed
++ ));
++ terminal.line(format_args!(
++ " drops: {} unauthorized, {} collision, {} invalid",
++ ingest.dropped_unauthorized, ingest.dropped_collision, ingest.dropped_invalid
++ ));
++ terminal.line(format_args!(
++ " shed: {} saturated, {} rate-limited",
++ ingest.shed_saturated, ingest.shed_rate_limited
++ ));
++ terminal.line(format_args!(
++ " 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" {
++ terminal.line(format_args!(
++ " capture mode: allowlist — repositories without a \
++ .ai-memory.toml marker send nothing"
++ ));
++ }
++ terminal.section("Optional models");
++ terminal.line(format_args!(" providers:"));
++ terminal.line(format_args!(
++ " llm: {}",
++ provider_health_line(&report.providers.llm)
++ ));
++ terminal.line(format_args!(
++ " embedding: {}",
++ provider_health_line(&report.providers.embedding)
++ ));
++ if report.providers.llm.status == ProviderHealthStatus::Error
++ && let Some(hint) = &report.providers.llm.retry_hint
++ {
++ terminal.line(format_args!(" 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() {
++ terminal.line(format_args!(" fallback chain:"));
++ for candidate in &report.providers.llm_candidates {
++ terminal.line(format_args!(" {}", fallback_candidate_line(candidate)));
+ }
- 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 --cc crates/ai-memory-cli/src/terminal.rs
index 00000000,7e27ab64..b744223c
mode 000000,100644..100644
--- a/crates/ai-memory-cli/src/terminal.rs
+++ b/crates/ai-memory-cli/src/terminal.rs
@@@ -1,0 -1,243 +1,135 @@@
-//! A shared terminal vocabulary: quiet structure, semantic color and bounded motion.
-
-mod progress;
++//! Explicit formatting for human diagnostic reports. Never intercepts output.
+
++use std::fmt::Arguments;
+ 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,
-}
++use crate::config::RuntimeEnv;
+
+ 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
++ Self::new(std::io::stdout().is_terminal(), env)
+ }
+
- fn new(tty: bool, no_color: bool, dumb: bool) -> Self {
++ fn new(tty: bool, env: &RuntimeEnv) -> Self {
+ Self {
- color: tty && !no_color && !dumb,
- motion: tty && !no_color && !dumb,
- width: 80,
- home: None,
++ color: tty
++ && env.var_os("NO_COLOR").is_none()
++ && env.var_os("TERM").is_none_or(|term| term != "dumb"),
+ }
+ }
+
- 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) {
++ if self.color {
++ println!(
++ "\n {}\n {}\n {}\n",
++ "◈ ai-memory".cyan().bold(),
++ command,
++ "────────────────────────────────────────────────".dark_grey(),
++ );
+ }
+ }
+
- 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)
- }
- ));
++ pub(crate) fn section(&self, title: &str) {
++ if self.color {
++ println!("\n {}", title.to_uppercase().cyan().bold());
+ }
- 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 line(&self, args: Arguments<'_>) {
++ println!("{}", self.paint(&args.to_string()));
+ }
+
- 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")
++ pub(crate) fn text(&self, text: &str) {
++ print!("{}", self.paint(text));
+ }
+
- /// 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")));
- }
- }
- }
++ /// Decoration never drops, reorders, wraps or truncates report content.
++ fn paint(&self, text: &str) -> String {
++ if !self.color {
++ return text.to_owned();
+ }
- 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,
++ let value = line.trim_end_matches('\n');
++ let trimmed = value.trim_start();
++ let color = if trimmed.starts_with(['⚠', '!', '?']) {
++ Some(Color::Yellow)
++ } else if trimmed.starts_with('✓') {
++ Some(Color::Green)
++ } else if ["pages:", "sessions:", "observations:"]
++ .iter()
++ .any(|key| trimmed.starts_with(key))
++ {
++ Some(Color::Cyan)
++ } else {
++ None
+ };
- tone.map_or_else(
- || line.to_owned(),
- |tone| {
- format!(
- "{}{}",
- self.ink(content, tone),
- if line.ends_with('\n') { "\n" } else { "" }
- )
- },
++ let decorated = if let Some(color) = color {
++ value.with(color).bold().to_string()
++ } else if value.starts_with(' ')
++ && let Some((label, rest)) = value.split_once(':')
++ && label.trim().len() <= 22
++ {
++ format!("{}:{rest}", label.dark_grey())
++ } else {
++ value.to_owned()
++ };
++ format!(
++ "{decorated}{}",
++ 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()];
++#[cfg(test)]
++mod tests {
++ use super::*;
++
++ #[test]
++ fn redirects_no_color_and_dumb_terminals_keep_exact_report_text() {
++ let text = " pages: 12\n⚠ Review hooks\n ai-memory install-hooks --agent codex --apply\n db: C:\\memory dir\\db.sqlite\n";
++ for (tty, pairs) in [
++ (false, vec![]),
++ (true, vec![("NO_COLOR", "")]),
++ (true, vec![("NO_COLOR", "1")]),
++ (true, vec![("TERM", "dumb")]),
++ ] {
++ let terminal = Terminal::new(tty, &RuntimeEnv::with_process_env_for_tests(&pairs));
++ assert!(!terminal.color);
++ assert_eq!(terminal.paint(text), text);
++ }
+ }
- 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;
++
++ #[test]
++ fn styled_reports_preserve_every_character_including_unknown_fields() {
++ let terminal = Terminal::new(
++ true,
++ &RuntimeEnv::with_process_env_for_tests(&[("TERM", "xterm-256color")]),
++ );
++ let text = " pages: 42\n future field: /a/path with spaces\n✓ Agent captured\n⚠ Unknown warning; keep this remedy\n? Capture unknown\n";
++ let decorated = terminal.paint(text);
++ assert!(decorated.contains('\u{1b}'));
++ let mut plain = String::new();
++ let mut chars = decorated.chars();
++ while let Some(ch) = chars.next() {
++ if ch == '\u{1b}' {
++ for code in chars.by_ref() {
++ if code == 'm' {
++ break;
++ }
++ }
+ } else {
- lines.push(std::mem::take(&mut current));
++ plain.push(ch);
+ }
+ }
++ assert_eq!(plain, text);
+ }
- if !current.is_empty() {
- lines.push(current);
- }
- lines
+ }
-
-#[cfg(test)]
-mod tests;
diff --cc docs/diagnostics.md
index 00000000,00000000..86ef9de0
new file mode 100644
--- /dev/null
+++ b/docs/diagnostics.md
@@@ -1,0 -1,0 +1,10 @@@
++# Diagnostic report presentation
++
++On an interactive terminal, `ai-memory status` and `ai-memory doctor` group
++their human reports into sections and use colors for counts and verdicts.
++All diagnostic fields, warnings and remediation commands remain visible.
++
++Redirecting stdout, setting `NO_COLOR` (including an empty value), or setting
++`TERM=dumb` preserves the original plain report on stdout. JSON output is
++unchanged. These presentation controls apply to the reports on stdout;
++tracing on stderr continues to use the existing logging configuration.