use serde_json::{json, Value as Json};
use crate::clients::{self, Checked, Registration, Scope};
use crate::init;
use crate::launch;
use crate::tools;
#[derive(Debug)]
struct ClientReport {
id: String,
display: String,
docs: String,
verified: String,
cli: Option<(String, bool)>,
registration: Registration,
checked: Checked,
installed: bool,
user_path: Option<String>,
project_path: Option<String>,
}
impl ClientReport {
fn needs_init(&self) -> bool {
self.installed
&& matches!(
self.registration,
Registration::No | Registration::Stale { .. }
)
}
}
pub const DURABILITY_NOTE: &str = "\
Memory is written to the data directory below and survives restarts. Several \
clients can share it: the first one that needs the store starts a daemon that \
owns it, and the rest connect to that. The daemon exits once nothing has \
needed it for a while, and `memfork stop` ends it now. A client run with \
--ephemeral keeps nothing and shares nothing.";
fn gather(home: Option<&str>) -> Vec<ClientReport> {
let launch = launch::resolve();
clients::all()
.into_iter()
.map(|c| {
let cli = c
.cli
.as_ref()
.map(|cli| (cli.binary.clone(), init::which(&cli.binary).is_some()));
let path_for = |scope| {
home.and_then(|h| c.file.as_ref().and_then(|f| f.path_here(scope, h)))
.map(|p| p.display().to_string())
};
let user_path = path_for(Scope::User);
let project_path = path_for(Scope::Project);
let (registration, checked) = match home {
Some(h) => clients::registration(&c, Scope::User, h, &launch),
None => (
Registration::Unknown("no home directory".to_owned()),
Checked::Nothing,
),
};
ClientReport {
installed: home.is_some_and(|h| init::is_installed(&c, h)),
id: c.id.clone(),
display: c.display.clone(),
docs: c.docs.clone(),
verified: c.verified.clone(),
cli,
registration,
checked,
user_path,
project_path,
}
})
.collect()
}
#[derive(Debug)]
struct Storage {
path: Option<std::path::PathBuf>,
source: Option<crate::persist::Source>,
why: Option<String>,
owner: Option<crate::persist::Endpoint>,
}
impl Storage {
fn describe_dir(&self) -> String {
match (&self.path, self.source) {
(Some(path), Some(source)) => {
let why = match source {
crate::persist::Source::Environment => "from MEMFORK_DATA_DIR",
crate::persist::Source::Project => "this project's own",
crate::persist::Source::PerUser => "per-user",
};
format!("{} ({why})", path.display())
}
_ => match &self.why {
Some(why) => format!("(none: {})", why.lines().next().unwrap_or(why)),
None => "(cannot be determined)".to_owned(),
},
}
}
fn describe_lock(&self) -> String {
match &self.owner {
Some(owner) => format!("held by process {}", owner.pid),
None => "free".to_owned(),
}
}
fn describe_daemon(&self) -> String {
match &self.owner {
None => "not running (one starts when a client needs it)".to_owned(),
Some(owner) => match owner.port {
None => format!(
"not running; process {} holds the directory without serving",
owner.pid
),
Some(port) => {
let version = owner.memfork_version.as_deref().unwrap_or("unknown");
let mine = if version == crate::VERSION {
""
} else {
" <- a different version from this one; run `memfork stop`"
};
format!(
"127.0.0.1:{port}, process {}, version {version}{mine}",
owner.pid
)
}
},
}
}
fn source_name(&self) -> Option<&'static str> {
self.source.map(|s| match s {
crate::persist::Source::Environment => "environment",
crate::persist::Source::Project => "project",
crate::persist::Source::PerUser => "per-user",
})
}
}
fn storage() -> Storage {
match crate::persist::datadir::here() {
Ok(dir) => {
let owner = crate::persist::lock::owner(&dir.path);
Storage {
path: Some(dir.path),
source: Some(dir.source),
why: None,
owner,
}
}
Err(why) => Storage {
path: None,
source: None,
why: Some(why.to_string()),
owner: None,
},
}
}
fn describe(checked: &Checked) -> String {
match checked {
Checked::Command(cmd) => format!("asked `{cmd}`"),
Checked::File(path) => format!("read {}", path.display()),
Checked::Nothing => "not checked".to_owned(),
}
}
pub fn text() -> String {
let home = clients::home_dir();
let mut out = String::new();
out.push_str(&format!("memfork {}\n", env!("CARGO_PKG_VERSION")));
let launch = launch::resolve();
out.push_str(&format!(" binary {}\n", launch.program.display()));
if !launch.args.is_empty() {
out.push_str(&format!(
" launches as {}\n",
launch.display(clients::SERVER_ARGS)
));
}
out.push_str(&format!(
" home {}\n",
home.as_deref().unwrap_or("(not found)")
));
out.push_str(&format!(
" engine memfork-core {}\n",
memfork_core::VERSION
));
out.push_str(&format!(" mcp tools {}\n", tools::all().len()));
let storage = storage();
out.push_str(&format!(" data dir {}\n", storage.describe_dir()));
out.push_str(&format!(" lock {}\n", storage.describe_lock()));
out.push_str(&format!(" daemon {}\n", storage.describe_daemon()));
out.push('\n');
out.push_str("Persistence\n");
for line in wrap(DURABILITY_NOTE, 74) {
out.push_str(&format!(" {line}\n"));
}
out.push('\n');
let reports = gather(home.as_deref());
out.push_str("Clients\n");
for r in &reports {
let status = match &r.registration {
Registration::Yes => "registered",
Registration::Stale { .. } => "registered, but not to this MemFork",
Registration::No if r.installed => "not registered",
Registration::No => "not installed",
Registration::Unknown(_) => "unknown",
};
out.push_str(&format!(" {} ({}) [{status}]\n", r.display, r.id));
match &r.cli {
Some((binary, true)) => {
out.push_str(&format!(" command {binary} (found on PATH)\n"));
}
Some((binary, false)) => {
out.push_str(&format!(" command {binary} (not on PATH)\n"));
}
None => out.push_str(" command (this client ships none)\n"),
}
out.push_str(&format!(" checked {}\n", describe(&r.checked)));
if let Registration::Unknown(why) = &r.registration {
out.push_str(&format!(" why {why}\n"));
}
if let Registration::Stale { found } = &r.registration {
out.push_str(&format!(
" points at {}\n",
found.as_deref().unwrap_or("another MemFork")
));
out.push_str(" fix run `memfork init` to point it here\n");
}
match &r.user_path {
Some(path) => out.push_str(&format!(" user {path}\n")),
None => out.push_str(
" user (kept by the client; MemFork neither reads nor writes it)\n",
),
}
if let Some(path) = &r.project_path {
out.push_str(&format!(" project {path}\n"));
}
out.push_str(&format!(" verified {} — {}\n", r.verified, r.docs));
}
let pending: Vec<&str> = reports
.iter()
.filter(|r| r.needs_init())
.map(|r| r.display.as_str())
.collect();
out.push('\n');
if !pending.is_empty() {
out.push_str(&format!(
"Run `memfork init` to register with: {}.\n",
pending.join(", ")
));
} else if reports.iter().any(|r| r.registration == Registration::Yes) {
out.push_str("Every detected client has MemFork registered.\n");
} else {
out.push_str("No MCP clients were detected here.\n");
}
out
}
pub fn json() -> Json {
let home = clients::home_dir();
let reports = gather(home.as_deref());
json!({
"version": env!("CARGO_PKG_VERSION"),
"engine": memfork_core::VERSION,
"binary": launch::resolve().program.display().to_string(),
"launch_command": init::command_line(),
"home": home,
"mcp_tools": tools::all().len(),
"data_dir": storage().path.as_ref().map(|p| p.display().to_string()),
"data_dir_source": storage().source_name(),
"lock": storage().owner.as_ref().map(|o| json!({ "pid": o.pid, "port": o.port })),
"daemon": storage().owner.as_ref().and_then(|o| o.port.map(|port| json!({
"port": port,
"pid": o.pid,
"version": o.memfork_version,
"version_matches": o.memfork_version.as_deref() == Some(crate::VERSION),
}))),
"persistence": {
"enabled": true,
"note": DURABILITY_NOTE,
},
"needs_init": reports.iter().any(ClientReport::needs_init),
"clients": reports.iter().map(|r| json!({
"id": r.id,
"display": r.display,
"command": r.cli.as_ref().map(|(b, _)| b.clone()),
"command_on_path": r.cli.as_ref().map(|(_, found)| *found),
"installed": r.installed,
"registered": r.registration.as_bool(),
"points_at": match r.registration.points_at() {
Some(path) => json!(path),
None => Json::Null,
},
"unknown_because": match &r.registration {
Registration::Unknown(why) => json!(why),
_ => Json::Null,
},
"checked": match &r.checked {
Checked::Command(cmd) => json!({ "how": "command", "detail": cmd }),
Checked::File(path) => {
json!({ "how": "file", "detail": path.display().to_string() })
}
Checked::Nothing => json!({ "how": "nothing", "detail": Json::Null }),
},
"user_config": r.user_path,
"project_config": r.project_path,
"verified": r.verified,
"docs": r.docs,
})).collect::<Vec<_>>(),
})
}
fn wrap(text: &str, width: usize) -> Vec<String> {
let mut lines = Vec::new();
let mut current = String::new();
for word in text.split_whitespace() {
if !current.is_empty() && current.len() + 1 + word.len() > width {
lines.push(std::mem::take(&mut current));
}
if !current.is_empty() {
current.push(' ');
}
current.push_str(word);
}
if !current.is_empty() {
lines.push(current);
}
lines
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_report_says_where_memory_is_kept() {
let text = text();
assert!(text.contains("survives restarts"), "{text}");
assert!(text.contains("Several clients can share it"), "{text}");
assert!(
!text.contains("is refused, and told which process"),
"the persistence note still describes the behaviour the daemon replaced"
);
let binary_line = text
.lines()
.find(|l| l.trim_start().starts_with("binary "))
.unwrap_or_default();
assert!(
!binary_line.trim_end().ends_with(" mcp"),
"the binary line is a command line, not a path: {binary_line}"
);
assert!(
!text.contains("launches as"),
"this build is its own binary, so there is nothing extra to say: {text}"
);
assert!(text.contains("data dir "), "{text}");
assert!(text.contains("lock "), "{text}");
assert!(text.contains("daemon "), "{text}");
let json = json();
assert_eq!(json["persistence"]["enabled"], true);
assert!(json["persistence"]["note"].is_string());
}
#[test]
fn the_report_covers_every_client_in_the_registry() {
let text = text();
for client in clients::all() {
assert!(text.contains(&client.display), "{} is missing", client.id);
assert!(
text.contains(&client.docs),
"{} has no docs link",
client.id
);
}
assert_eq!(
json()["clients"].as_array().map(Vec::len),
Some(clients::all().len())
);
}
#[test]
fn the_report_states_the_version_and_tool_count() {
let text = text();
assert!(text.contains(env!("CARGO_PKG_VERSION")));
assert!(text.contains(&tools::all().len().to_string()));
}
#[test]
fn the_report_says_how_it_asked() {
let text = text();
assert!(text.contains(" checked "), "{text}");
}
#[test]
fn wrapping_never_loses_or_splits_a_word() {
let words: Vec<&str> = DURABILITY_NOTE.split_whitespace().collect();
let wrapped = wrap(DURABILITY_NOTE, 40);
let rejoined: Vec<&str> = wrapped.iter().flat_map(|l| l.split_whitespace()).collect();
assert_eq!(words, rejoined);
assert!(wrapped.iter().all(|l| l.len() <= 40 || !l.contains(' ')));
}
}