use std::fs;
use std::io;
use std::path::Path;
use anyhow::Result;
use openmoat_audit::Store;
use openmoat_hosts::Host;
use crate::approvals::{self, GRANT_TTL_MS, Grants};
use crate::cli::{Format, StatusArgs};
use crate::exit::Code;
use crate::home::Home;
use crate::integrity::{HookPinGap, Lock};
use crate::report::{Attention, Mark, Printer, Row};
use crate::sandbox::Plan;
use crate::{protection, render, time};
mod agents;
const RECENT_EVENTS: usize = 5;
#[derive(Default)]
struct Shown {
attention: Attention,
agents: Vec<Row>,
openmoat: Vec<Row>,
}
impl Shown {
fn needs(&mut self, mark: Mark, label: &str, text: impl Into<String>) {
self.attention.push(Row::new(mark, label, text));
}
fn state(&mut self, mark: Mark, label: &str, text: impl Into<String>) {
self.openmoat.push(Row::new(mark, label, text));
}
}
pub fn run(args: &StatusArgs) -> Result<Code> {
let home = Home::locate()?;
let binary = crate::install::hook_binary()?;
let update = crate::upgrade::available(&home);
if args.format == Format::Json {
render::json(&report(&home, &binary, update.as_ref())?)?;
return Ok(Code::Ok);
}
let mut shown = Shown::default();
let mut healthy = policies(&mut shown, &home)?;
if let Some(update) = &update {
let row = Row::new(Mark::Attention, "Policy", format!("{update} to review"))
.fix("openmoat policy upgrade");
shown.attention.push(row);
}
healthy &= lock(&mut shown, &home, &binary)?;
healthy &= mcp_line(&mut shown, &home, &binary);
for line in mcp_outside(&home, &binary) {
shown.needs(Mark::Attention, "MCP servers", line);
}
healthy &= approvals(&mut shown, &home);
healthy &= agents::hooks(&mut shown, &home, &binary)?;
for warning in crate::project_settings::warnings_here(&home) {
let text = format!("project settings {}", warning.text);
shown.needs(Mark::Attention, warning.host.display_name(), text);
}
for warning in crate::project_settings::other_hooks::warnings_here(&home) {
let text = format!("other hook {}", warning.text);
shown.needs(Mark::Attention, warning.host.display_name(), text);
}
for warning in crate::project_settings::git_config::warnings_here() {
shown.needs(
Mark::Attention,
"Repository",
format!("git config {warning}"),
);
}
if let Ok(policy) = home.load_policy() {
healthy &= agents::sandboxes(&mut shown, &home, &Plan::new(&home, &policy)?, &binary);
}
let audit = audit(&mut shown, &home)?;
healthy &= audit.is_some();
opt_in(&mut shown, &home);
mcp_servers(&mut shown, &home, &binary);
if let Some(boundary) = protection::run_boundary(&home, &binary) {
healthy &= boundary.met;
let mark = if boundary.met { Mark::Ok } else { Mark::Broken };
if boundary.met {
shown.state(mark, "Run boundary", boundary.describe());
} else {
shown.needs(mark, "Run boundary", boundary.describe());
}
}
let agents = protection::report(&home, &binary)?;
healthy &= agents.iter().all(protection::Protection::meets_required);
let table = crate::report::agent_table(&agents, &shown.attention, false);
let mut out = io::stdout().lock();
let mut printer = Printer::stdout(&mut out);
printer.title("status")?;
printer.attention(&shown.attention)?;
let mut table = table;
table.rows.extend(crate::report::os_sandbox_rows(&agents));
table.rows.append(&mut shown.agents);
printer.agents(&table)?;
printer.heading("OpenMoat")?;
printer.rows(&shown.openmoat)?;
if let Some(recent) = audit.filter(|r| !r.is_empty()) {
printer.heading("Latest decisions")?;
drop(printer);
render::event_table(&recent)?;
}
Ok(if healthy { Code::Ok } else { Code::Usage })
}
pub(super) fn json() -> Result<serde_json::Value> {
let home = Home::locate()?;
let binary = crate::install::hook_binary()?;
let update = crate::upgrade::available(&home);
report(&home, &binary, update.as_ref())
}
fn report(home: &Home, binary: &Path, update: Option<&String>) -> Result<serde_json::Value> {
let drift: Vec<String> = Lock::load(&home.lock_path())
.map(|lock| lock.verify().iter().map(ToString::to_string).collect())
.unwrap_or_default();
let (plugins, hooks): (Vec<_>, Vec<_>) = crate::heartbeat::all(home, binary)
.into_iter()
.partition(|one| crate::heartbeat::has_plugin(one.of));
Ok(serde_json::json!({
"agents": protection::report(home, binary)?,
"run_boundary": protection::run_boundary(home, binary),
"mcp_servers": crate::mcp::status::report(
home,
binary,
std::env::current_dir().ok().as_deref(),
)
.map(|found| found.servers)
.unwrap_or_default(),
"plugins": plugins,
"hooks": hooks,
"hook_warnings": hook_warnings(home, binary)?,
"policy_update": update,
"lock_drift": drift,
"mcp_changes": mcp_changes(home, binary).unwrap_or_default(),
"mcp_outside": mcp_outside(home, binary),
"project_settings": crate::project_settings::warnings_here(home)
.into_iter()
.map(|warning| warning.text)
.collect::<Vec<_>>(),
"other_hooks": crate::project_settings::other_hooks::warnings_here(home)
.into_iter()
.map(|warning| warning.text)
.collect::<Vec<_>>(),
"repo_git_config": crate::project_settings::git_config::warnings_here(),
"opt_in": crate::opt_in::rows(home, time::now_ms()),
"own_sandbox_linux": agents::own_sandbox_linux(home, binary),
}))
}
fn opt_in(shown: &mut Shown, home: &Home) {
for row in crate::opt_in::rows(home, time::now_ms()) {
match (row.alert, row.attention) {
(true, _) => shown.needs(Mark::Broken, row.label, row.text),
(false, true) => shown.needs(Mark::Attention, row.label, row.text),
(false, false) => shown.state(Mark::Ok, row.label, row.text),
}
}
}
fn hook_warnings(home: &Home, binary: &Path) -> Result<Vec<String>> {
let mut warnings = Vec::new();
for host in Host::ALL {
let config = crate::install::HostConfig::for_host(home, host)?;
if config.set_up(binary)
&& let Some(warning) = config.trust_warning()
{
warnings.push(format!("{}: {warning}", host.display_name()));
}
}
Ok(warnings)
}
fn mcp_changes(home: &Home, binary: &Path) -> Result<Vec<String>> {
let path = home.lock_path();
if !path.is_file() {
return Ok(Vec::new());
}
let lock = Lock::load(&path)?;
let cwd = std::env::current_dir().ok();
let found = crate::mcp::review(
home,
&lock,
&crate::mcp::set_up_hosts(home, binary),
cwd.as_deref(),
)?;
let mut lines = Vec::new();
if found.pinned {
lines.extend(
found
.changes
.iter()
.map(|c| c.describe().lines().next().unwrap_or_default().to_owned()),
);
}
lines.extend(
found
.unreadable
.iter()
.map(|(p, why)| format!("{} cannot be read: {why}", p.display())),
);
for (_, pins) in crate::mcp::tools::all(home)? {
if pins.held_count() > 0 {
lines.push(format!(
"MCP server `{}` lists {}",
pins.server,
pins.held_summary()
));
}
}
Ok(lines)
}
fn mcp_outside(home: &Home, binary: &Path) -> Vec<String> {
let cwd = std::env::current_dir().ok();
match crate::mcp::outside::report(home, binary, cwd.as_deref()) {
Ok(found) => found
.iter()
.map(crate::mcp::outside::Outside::describe)
.collect(),
Err(e) => vec![format!(
"cannot list the servers that start outside OpenMoat: {e:#}"
)],
}
}
fn mcp_servers(shown: &mut Shown, home: &Home, binary: &Path) {
let cwd = std::env::current_dir().ok();
match crate::mcp::status::report(home, binary, cwd.as_deref()) {
Ok(found) => {
for server in &found.servers {
let mark = if server.protected {
Mark::Ok
} else {
Mark::Attention
};
shown.state(mark, "MCP server", server.describe());
}
}
Err(error) => shown.needs(
Mark::Attention,
"MCP servers",
format!("cannot list them: {error:#}"),
),
}
}
fn mcp_line(shown: &mut Shown, home: &Home, binary: &Path) -> bool {
match mcp_changes(home, binary) {
Ok(lines) if lines.is_empty() => {
let text = "nothing waits for `openmoat mcp accept`";
shown.state(Mark::Ok, "MCP servers", text);
true
}
Ok(lines) => {
for line in lines {
let row = Row::new(Mark::Broken, "MCP servers", line)
.fix("`openmoat mcp accept` shows it and asks");
shown.attention.push(row);
}
false
}
Err(error) => {
shown.needs(Mark::Broken, "MCP servers", format!("{error:#}"));
false
}
}
}
fn policies(shown: &mut Shown, home: &Home) -> Result<bool> {
let mut healthy = true;
let policy_path = home.policy_path();
match home.load_policy() {
Ok(policy) => {
let bytes = fs::read(&policy_path)?;
let digest = crate::integrity::sha256_hex(&bytes);
let (deny, allow, review) = policy.rule_count();
let text = format!(
"{} · {deny} deny · {allow} allow · {review} review rules · sha256:{}",
policy_path.display(),
digest.get(..12).unwrap_or(&digest)
);
shown.state(Mark::Ok, "Policy", text);
}
Err(error) => {
healthy = false;
shown.needs(Mark::Broken, "Policy", format!("{error:#}"));
}
}
match crate::repo::summary(home) {
Ok(Some(line)) => shown.state(Mark::Info, "Repo policy", line),
Ok(None) => {}
Err(error) => {
healthy = false;
let text = format!("{error:#}; every call in this project is denied");
shown.needs(Mark::Broken, "Repo policy", text);
}
}
Ok(healthy)
}
fn lock(shown: &mut Shown, home: &Home, binary: &Path) -> Result<bool> {
let lock_path = home.lock_path();
let lock = match Lock::load(&lock_path) {
Ok(lock) => lock,
Err(_) if !lock_path.exists() => {
let row = Row::new(Mark::Broken, "Lock", "missing").fix("openmoat init");
shown.attention.push(row);
return Ok(false);
}
Err(error) => {
shown.needs(Mark::Broken, "Lock", format!("{error:#}"));
return Ok(false);
}
};
let mut healthy = true;
let drift = lock.verify();
if drift.is_empty() {
let text = format!("{} files pinned, intact", lock.entries.len());
shown.state(Mark::Ok, "Lock", text);
} else {
healthy = false;
for d in drift {
let row = Row::new(Mark::Broken, "Lock", d.to_string()).fix("openmoat doctor");
shown.attention.push(row);
}
}
let own = crate::integrity::binary::check(home, &lock);
if let Some(reason) = own.deny_reason() {
healthy = false;
let row = Row::new(Mark::Broken, "Binary", reason).fix("openmoat init");
shown.attention.push(row);
} else if let Some(note) = own.note() {
shown.state(Mark::Info, "Binary", note);
}
let installed = crate::integrity::installed_hook_files(home, binary)?;
let gap = HookPinGap::new(&lock, home, &installed);
for path in gap.unpinned {
healthy = false;
let row = Row::new(
Mark::Broken,
"Lock",
format!("{} is not pinned", path.display()),
)
.fix("openmoat init to pin it");
shown.attention.push(row);
}
for path in gap.elsewhere {
let text = format!(
"{} is pinned but not this shell's hook file ({})",
path.display(),
HookPinGap::moved_by()
);
shown.state(Mark::Info, "Lock", text);
}
Ok(healthy)
}
fn approvals(shown: &mut Shown, home: &Home) -> bool {
let grants = match Grants::load(&home.grants_path()) {
Ok(grants) => grants,
Err(error) => {
shown.needs(Mark::Broken, "Approvals", format!("{error:#}"));
return false;
}
};
let now = time::now_ms();
let ages: Vec<i64> = grants.active(now).map(|g| now - g.granted_at_ms).collect();
let text = match ages.iter().max() {
Some(oldest) => format!(
"{} active session grant(s), oldest {} old (each expires after {})",
ages.len(),
time::duration(*oldest),
time::duration(GRANT_TTL_MS)
),
None => "no active session grants".to_owned(),
};
shown.state(Mark::Info, "Approvals", text);
let overlay = approvals::Overlay::load(&home.overlay_path());
if let Some(text) = overlay
.ok()
.and_then(|o| approvals::expiry_summary(&o, now))
{
shown.state(Mark::Info, "Approvals", text);
}
for grant in grants.active(now).filter(|g| g.unbound()) {
let text = format!(
"{} session {}: {} needs approving again: it names no project, so it no longer \
applies (`openmoat allow --last` after its next review)",
grant.host,
grant.session_id,
approvals::describe(&grant.action)
);
shown.needs(Mark::Attention, "Approvals", text);
}
true
}
fn audit(shown: &mut Shown, home: &Home) -> Result<Option<Vec<openmoat_audit::Event>>> {
let audit_path = home.audit_path();
if !audit_path.is_file() {
let row = Row::new(Mark::Broken, "Audit log", "missing").fix("openmoat init");
shown.attention.push(row);
return Ok(None);
}
let store = Store::open_read_only(&audit_path)?;
let text = format!("{} · {} events", audit_path.display(), store.count()?);
shown.state(Mark::Ok, "Audit log", text);
Ok(Some(store.recent(RECENT_EVENTS)?))
}