From adef215842a384e3c73696221e2a0398146f7a48 Mon Sep 17 00:00:00 2001 From: Bradley Hilton Date: Thu, 29 Oct 2026 04:49:10 +0100 Subject: [PATCH 1/2] fix: make diagnostics reports safe and accurate --- Cargo.lock | 1 + atomic-agent/src/hooks/claude_code/mod.rs | 5 +- atomic-agent/src/hooks/live.rs | 351 ++++++++ atomic-agent/src/hooks/mod.rs | 1 + atomic-cli/Cargo.toml | 1 + .../src/commands/diagnostics/collect.rs | 818 ++++++++++++++---- atomic-cli/src/commands/diagnostics/mod.rs | 10 +- .../tests/it/diagnostics_integration_test.rs | 688 ++++++++++++++- docs/diagnostics.md | 46 +- 9 files changed, 1721 insertions(+), 200 deletions(-) create mode 100644 atomic-agent/src/hooks/live.rs diff --git a/Cargo.lock b/Cargo.lock index d627852c..1bb82edd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -304,6 +304,7 @@ dependencies = [ "thiserror 1.0.69", "tokio", "tokio-stream", + "toml", "tonic", "tower 0.4.13", "tracing", diff --git a/atomic-agent/src/hooks/claude_code/mod.rs b/atomic-agent/src/hooks/claude_code/mod.rs index 1a318983..2a84f231 100644 --- a/atomic-agent/src/hooks/claude_code/mod.rs +++ b/atomic-agent/src/hooks/claude_code/mod.rs @@ -155,9 +155,8 @@ impl AgentHook for ClaudeCodeHook { return false; }; - // Check if any hook command starts with our prefix - let json_str = raw.to_string(); - json_str.contains(ATOMIC_HOOK_PREFIX) + super::live::json_hooks_active("claude-code", &raw, "hooks", ATOMIC_HOOK_PREFIX) + .unwrap_or(false) } fn supported_hooks(&self) -> Vec { diff --git a/atomic-agent/src/hooks/live.rs b/atomic-agent/src/hooks/live.rs new file mode 100644 index 00000000..12e5bec7 --- /dev/null +++ b/atomic-agent/src/hooks/live.rs @@ -0,0 +1,351 @@ +//! Read-only inspection of hook configuration formats understood by Atomic. + +use serde_json::Value; + +/// Inspect an already parsed settings document. Unsupported formats and +/// malformed hook structures return an error rather than implying absence. +/// +/// # Errors +/// Returns a static, content-free explanation when the configuration cannot be +/// interpreted reliably. +pub fn json_hooks_active( + agent: &str, + root: &Value, + hooks_key: &str, + prefix: &str, +) -> Result { + let events: &[&str] = match agent { + "claude-code" | "codex" => &[ + "SessionStart", + "SessionEnd", + "Stop", + "UserPromptSubmit", + "PreToolUse", + "PostToolUse", + ], + "gemini-cli" => &[ + "SessionStart", + "SessionEnd", + "BeforeAgent", + "AfterAgent", + "BeforeTool", + "AfterTool", + ], + _ => return Err("agent hook format is not supported for inspection"), + }; + if hooks_key != "hooks" || prefix != format!("atomic agent hooks {agent}") { + return Err("unsupported hook key or command prefix"); + } + let root = root.as_object().ok_or("settings root is not an object")?; + if agent == "gemini-cli" { + for key in ["hooksConfig", "tools"] { + if root.get(key).is_some_and(|value| !value.is_object()) { + return Err("hook settings are not an object"); + } + } + if let Some(disabled) = root.get("hooksConfig").and_then(|v| v.get("disabled")) { + if !disabled + .as_array() + .is_some_and(|names| names.iter().all(Value::is_string)) + { + return Err("disabled hook names are not an array of strings"); + } + } + } + let flags = match agent { + "claude-code" => [root.get("disableAllHooks"), None], + "gemini-cli" => [ + root.get("hooksConfig").and_then(|v| v.get("enabled")), + root.get("tools").and_then(|v| v.get("enableHooks")), + ], + _ => [None, None], + }; + for flag in flags.into_iter().flatten() { + if !flag.is_boolean() { + return Err("hook enablement flag is not a boolean"); + } + } + if globally_disabled(agent, root) { + return Ok(false); + } + let Some(hooks) = root.get(hooks_key) else { + return Ok(false); + }; + let hooks = hooks.as_object().ok_or("hooks are not an object")?; + if hooks.iter().any(|(event, entries)| { + !events.contains(&event.as_str()) && entries.to_string().contains(prefix) + }) { + return Err("hook event cannot be verified"); + } + let mut active = false; + for event in events { + let Some(groups) = hooks.get(*event) else { + continue; + }; + let groups = groups.as_array().ok_or("hook event is not an array")?; + for group in groups { + let group = group.as_object().ok_or("hook group is not an object")?; + if disabled(group)? { + continue; + } + if group.get("matcher").is_some_and(|v| !v.is_string()) { + return Err("hook matcher is not a string"); + } + let entries = group + .get("hooks") + .and_then(Value::as_array) + .ok_or("hook group has no hook array")?; + for entry in entries { + let entry = entry.as_object().ok_or("hook entry is not an object")?; + if disabled(entry)? { + continue; + } + if agent == "gemini-cli" { + if let Some(name) = entry.get("name").and_then(Value::as_str) { + if root + .get("hooksConfig") + .and_then(|v| v.get("disabled")) + .and_then(Value::as_array) + .is_some_and(|names| names.iter().any(|v| v.as_str() == Some(name))) + { + continue; + } + } + } + let hook_type = entry + .get("type") + .and_then(Value::as_str) + .ok_or("hook type is missing or invalid")?; + if hook_type != "command" { + continue; + } + let command = entry + .get("command") + .and_then(Value::as_str) + .ok_or("command hook has no command")?; + if is_invocation(command, prefix, agent, event) { + active = true; + } else if command.contains(prefix) { + return Err("hook command cannot be verified"); + } + } + } + } + Ok(active) +} + +/// Whether this settings object disables all hooks at its scope. +pub fn globally_disabled(agent: &str, root: &serde_json::Map) -> bool { + match agent { + "claude-code" => root.get("disableAllHooks") == Some(&Value::Bool(true)), + "gemini-cli" => { + root.get("hooksConfig").and_then(|v| v.get("enabled")) == Some(&Value::Bool(false)) + || root.get("tools").and_then(|v| v.get("enableHooks")) == Some(&Value::Bool(false)) + } + _ => false, + } +} + +fn disabled(entry: &serde_json::Map) -> Result { + for flag in [entry.get("disabled"), entry.get("enabled")] + .into_iter() + .flatten() + { + if !flag.is_boolean() { + return Err("hook enablement flag is not a boolean"); + } + } + Ok(entry.get("disabled") == Some(&Value::Bool(true)) + || entry.get("enabled") == Some(&Value::Bool(false))) +} + +fn is_invocation(command: &str, prefix: &str, agent: &str, event: &str) -> bool { + if prefix.is_empty() { + return false; + } + let command = command.trim(); + let guard = "test -d .atomic || test -f .atomic-sandbox && "; + let (command, guarded) = match command.strip_prefix(guard) { + Some(command) => (command, true), + None => (command, false), + }; + let command = if guarded { + let Some(command) = command.strip_suffix(" || true") else { + return false; + }; + command + } else { + command + }; + let Some(rest) = command.strip_prefix(prefix) else { + return false; + }; + if !rest.starts_with(char::is_whitespace) { + return false; + } + let mut args = rest.split_whitespace(); + let Some(verb) = args.next() else { + return false; + }; + let recognized = matches!( + (agent, event, verb), + ( + "claude-code" | "codex" | "gemini-cli", + "SessionStart", + "session-start" + ) | ( + "claude-code" | "codex" | "gemini-cli", + "SessionEnd", + "session-end" + ) | ("claude-code" | "codex", "Stop", "stop") + | ( + "claude-code" | "codex", + "UserPromptSubmit", + "user-prompt-submit" + ) + | ("claude-code", "PreToolUse", "pre-task") + | ( + "claude-code", + "PostToolUse", + "post-task" | "post-todo" | "post-tool" + ) + | ("codex", "PreToolUse", "pre-tool") + | ("codex", "PostToolUse", "post-tool") + | ("gemini-cli", "BeforeAgent", "before-agent") + | ("gemini-cli", "AfterAgent", "after-agent") + | ("gemini-cli", "BeforeTool", "before-tool") + | ("gemini-cli", "AfterTool", "after-tool") + ); + if !recognized { + return false; + } + match (args.next(), args.next()) { + (None, None) => true, + (Some("--foreground"), None) => agent == "codex" && verb == "stop", + _ => false, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn only_active_command_entries_count() { + let prefix = "atomic agent hooks claude-code"; + let active = |command: &str| json!({"hooks":{"Stop":[{"hooks":[{"type":"command","command":command}]}]}}); + for command in ["atomic agent hooks claude-code stop", "test -d .atomic || test -f .atomic-sandbox && atomic agent hooks claude-code stop || true"] { + assert_eq!(json_hooks_active("claude-code", &active(command), "hooks", prefix), Ok(true)); + } + for root in [ + json!({"notes":prefix,"hooks":{}}), + json!({"disableAllHooks":true,"hooks":active(prefix)["hooks"]}), + json!({"hooks":{"Stop":[{"disabled":true,"hooks":[{"type":"command","command":format!("{prefix} stop")}]}]}}), + ] { + assert_eq!( + json_hooks_active("claude-code", &root, "hooks", prefix), + Ok(false), + "{root}" + ); + } + for command in [ + format!("echo {prefix} stop"), + "atomic agent hooks claude-code-not stop".to_string(), + ] { + assert!(json_hooks_active("claude-code", &active(&command), "hooks", prefix).is_err()); + } + } + + #[test] + fn supported_formats_and_disabled_states() { + for (agent, event, verb) in [ + ("claude-code", "Stop", "stop"), + ("codex", "Stop", "stop"), + ("gemini-cli", "AfterAgent", "after-agent"), + ] { + let prefix = format!("atomic agent hooks {agent}"); + let mut root = json!({"hooks":{event:[{"hooks":[{"type":"command","name":"atomic-test","command":format!("{prefix} {verb}")}]}]}}); + assert_eq!( + json_hooks_active(agent, &root, "hooks", &prefix), + Ok(true), + "{agent}" + ); + if agent == "claude-code" { + root["tools"] = json!({"enableHooks":false}); + assert_eq!(json_hooks_active(agent, &root, "hooks", &prefix), Ok(true)); + } + root["hooks"][event][0]["hooks"][0]["enabled"] = json!(false); + assert_eq!( + json_hooks_active(agent, &root, "hooks", &prefix), + Ok(false), + "{agent}" + ); + root["hooks"][event][0]["hooks"][0]["enabled"] = json!(true); + assert!(json_hooks_active(agent, &root, "other", &prefix).is_err()); + if agent == "gemini-cli" { + root["hooksConfig"] = json!({"disabled":["atomic-test"]}); + assert_eq!(json_hooks_active(agent, &root, "hooks", &prefix), Ok(false)); + } + } + assert!(json_hooks_active( + "opencode", + &json!({}), + "hooks", + "atomic agent hooks opencode" + ) + .is_err()); + assert!(json_hooks_active( + "codex", + &json!({"hooks":[]}), + "hooks", + "atomic agent hooks codex" + ) + .is_err()); + let incomplete = json!({"hooks":{"Stop":[{"hooks":[ + {"type":"command","command":"atomic agent hooks claude-code stop"}, + {"type":"command"} + ]}]}}); + assert!(json_hooks_active( + "claude-code", + &incomplete, + "hooks", + "atomic agent hooks claude-code" + ) + .is_err()); + } + + #[test] + fn built_in_installers_produce_recognised_hooks() { + use crate::hooks::AgentHook; + + let home = tempfile::tempdir().unwrap(); + let claude = crate::hooks::claude_code::ClaudeCodeHook::new(); + claude.install(home.path()).unwrap(); + let gemini = crate::hooks::gemini_cli::GeminiCliHook::new(); + gemini.install(home.path()).unwrap(); + let codex = crate::hooks::codex::CodexHook::new(); + codex + .install_at(&home.path().join(".codex/hooks.json"), false) + .unwrap(); + for (agent, relative) in [ + ("claude-code", ".claude/settings.json"), + ("gemini-cli", ".gemini/settings.json"), + ("codex", ".codex/hooks.json"), + ] { + let root: Value = + serde_json::from_slice(&std::fs::read(home.path().join(relative)).unwrap()) + .unwrap(); + assert_eq!( + json_hooks_active( + agent, + &root, + "hooks", + &format!("atomic agent hooks {agent}") + ), + Ok(true), + "{agent}" + ); + } + } +} diff --git a/atomic-agent/src/hooks/mod.rs b/atomic-agent/src/hooks/mod.rs index 52b274ec..dcdc9916 100644 --- a/atomic-agent/src/hooks/mod.rs +++ b/atomic-agent/src/hooks/mod.rs @@ -86,6 +86,7 @@ pub mod grok; pub mod hermes; pub mod kilo; pub mod kiro; +pub mod live; pub mod manifest; pub mod opencode; pub mod pi; diff --git a/atomic-cli/Cargo.toml b/atomic-cli/Cargo.toml index 9cbf3305..32d1317c 100644 --- a/atomic-cli/Cargo.toml +++ b/atomic-cli/Cargo.toml @@ -91,6 +91,7 @@ uuid = { version = "1.0", features = ["serde", "v4"] } # Utilities serde = { workspace = true } serde_json = { workspace = true } +toml = { workspace = true } bytes = { workspace = true } fs2 = "0.4" url = { workspace = true } diff --git a/atomic-cli/src/commands/diagnostics/collect.rs b/atomic-cli/src/commands/diagnostics/collect.rs index 3fb0e102..892c6c26 100644 --- a/atomic-cli/src/commands/diagnostics/collect.rs +++ b/atomic-cli/src/commands/diagnostics/collect.rs @@ -7,6 +7,7 @@ //! the network. A value that cannot be read is reported with the reason, //! never filled in by inference. +use std::fmt; use std::io::ErrorKind; use std::path::{Path, PathBuf}; @@ -16,7 +17,6 @@ use serde::Serialize; use crate::commands::find_repository_root; use crate::commands::git::hook_dispatchers::{inspect_dispatchers, DispatcherReport}; -use crate::commands::git::shim::shim_config; use crate::commands::update::{detect_source, StdEnv}; use crate::error::CliError; use crate::logging::redact; @@ -241,28 +241,84 @@ pub(crate) struct NotCollected { /// tests point every location at temporary directories. pub(crate) struct Sources { pub home: Option, - pub integrations_root: Result, + pub integrations_root: Result, pub integrations_root_overridden: bool, /// The enclosing Atomic workspace; `Ok(None)` outside one. - pub workspace: Result, String>, + pub workspace: Result, SourceError>, pub install_source: String, } +/// Only these fixed summaries may cross the boundary into a support report. +#[derive(Clone, Copy, Debug)] +pub(crate) enum SourceError { + WorkspaceLookup, + IntegrationsHome, +} + +impl fmt::Display for SourceError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::WorkspaceLookup => "cannot determine the current workspace", + Self::IntegrationsHome => "cannot resolve home directory", + }) + } +} + +/// ErrorKind is safe to classify; arbitrary OS error messages are not. +fn io_summary(kind: ErrorKind) -> &'static str { + match kind { + ErrorKind::NotFound => "not found", + ErrorKind::PermissionDenied => "permission denied", + ErrorKind::InvalidData => "invalid data or encoding", + ErrorKind::IsADirectory => "is a directory", + ErrorKind::NotADirectory => "a path component is not a directory", + _ => "I/O error", + } +} + +// A dangling symlink or a concurrent replacement is not proof of absence. +fn demonstrably_missing(path: &Path) -> bool { + match std::fs::symlink_metadata(path) { + Ok(_) => return false, + Err(error) if error.kind() == ErrorKind::NotFound => {} + Err(_) => return false, + } + for ancestor in path.ancestors().skip(1) { + match std::fs::symlink_metadata(ancestor) { + Ok(metadata) if metadata.file_type().is_symlink() => { + return std::fs::metadata(ancestor).is_ok(); + } + Ok(_) => return true, + Err(error) if error.kind() == ErrorKind::NotFound => {} + Err(_) => return false, + } + } + false +} + impl Sources { pub(crate) fn from_process() -> Self { - let workspace = match find_repository_root() { + let home = dirs::home_dir(); + let workspace = match workspace_search_readable(home.as_deref()) + .map_err(Some) + .and_then(|()| { + find_repository_root().map_err(|error| match error { + CliError::RepositoryNotFound { .. } => None, + _ => Some(SourceError::WorkspaceLookup), + }) + }) { Ok(root) => Ok(Some(root)), - Err(CliError::RepositoryNotFound { .. }) => Ok(None), - Err(error) => Err(error.to_string()), + Err(None) => linked_git_search_readable(home.as_deref()).map(|()| None), + Err(Some(error)) => Err(error), }; let install_source = std::env::current_exe() .map(|exe| detect_source(&exe, &StdEnv).short_label()) .unwrap_or("unknown") .to_string(); Self { - home: dirs::home_dir(), + home, integrations_root: atomic_agent::integrations::integrations_root() - .map_err(|error| error.to_string()), + .map_err(|_| SourceError::IntegrationsHome), integrations_root_overridden: std::env::var_os("ATOMIC_INTEGRATIONS_HOME").is_some(), workspace, install_source, @@ -270,13 +326,142 @@ impl Sources { } } +// The shared discovery helper uses boolean file checks; preflight their +// filesystem errors so an inaccessible ancestor is not reported as absent. +fn workspace_search_readable(home: Option<&Path>) -> Result<(), SourceError> { + let cwd = std::env::current_dir().map_err(|_| SourceError::WorkspaceLookup)?; + let mut current = cwd + .canonicalize() + .map_err(|_| SourceError::WorkspaceLookup)?; + let home = home.and_then(|path| path.canonicalize().ok()); + loop { + let dot = current.join(".atomic"); + for path in [ + dot.clone(), + dot.join("atomic.redb"), + dot.join("pristine.redb"), + current.join(".atomic-sandbox"), + ] { + match std::fs::metadata(&path) { + Ok(_) => {} + Err(error) + if error.kind() == ErrorKind::NotFound && demonstrably_missing(&path) => {} + Err(error) + if error.kind() == ErrorKind::NotADirectory && path.starts_with(&dot) => {} + Err(_) => return Err(SourceError::WorkspaceLookup), + } + } + if (dot.is_dir() && atomic_repository::has_database(&dot)) + || current.join(".atomic-sandbox").is_file() + { + break; + } + if home.as_deref() == Some(current.as_path()) || !current.pop() { + break; + } + } + Ok(()) +} + +// Only called after ordinary discovery found no Atomic parent. Git's shared +// resolver treats a failed rev-parse as absence, even for a broken gitfile. +fn linked_git_search_readable(home: Option<&Path>) -> Result<(), SourceError> { + let cwd = std::env::current_dir().map_err(|_| SourceError::WorkspaceLookup)?; + let mut current = cwd + .canonicalize() + .map_err(|_| SourceError::WorkspaceLookup)?; + let home = home.and_then(|path| path.canonicalize().ok()); + loop { + let git = current.join(".git"); + match std::fs::metadata(&git) { + Ok(metadata) if metadata.is_file() => return inspect_linked_git(¤t), + Ok(_) => return Ok(()), + Err(error) if error.kind() == ErrorKind::NotFound && demonstrably_missing(&git) => {} + Err(_) => return Err(SourceError::WorkspaceLookup), + } + if home.as_deref() == Some(current.as_path()) || !current.pop() { + return Ok(()); + } + } +} + +fn inspect_linked_git(root: &Path) -> Result<(), SourceError> { + use std::process::{Command, Stdio}; + + let output = Command::new("git") + .arg("--no-optional-locks") + .arg("-C") + .arg(root) + .args([ + "rev-parse", + "--show-toplevel", + "--git-common-dir", + "--git-dir", + "--git-path", + "index", + ]) + .env_remove("GIT_INDEX_FILE") + .env("GIT_TERMINAL_PROMPT", "0") + .stdin(Stdio::null()) + .stderr(Stdio::null()) + .output() + .map_err(|_| SourceError::WorkspaceLookup)?; + if !output.status.success() { + return Err(SourceError::WorkspaceLookup); + } + let lines: Vec<&[u8]> = output + .stdout + .split(|byte| *byte == b'\n') + .filter(|line| !line.is_empty()) + .map(|line| line.strip_suffix(b"\r").unwrap_or(line)) + .collect(); + let [worktree, common, gitdir, _index] = lines.as_slice() else { + return Err(SourceError::WorkspaceLookup); + }; + let resolve = |bytes: &[u8]| -> Result { + if bytes.is_empty() || bytes.contains(&0) || bytes.contains(&b'\r') { + return Err(SourceError::WorkspaceLookup); + } + #[cfg(unix)] + let path = { + use std::os::unix::ffi::OsStringExt; + PathBuf::from(std::ffi::OsString::from_vec(bytes.to_vec())) + }; + #[cfg(not(unix))] + let path = + PathBuf::from(std::str::from_utf8(bytes).map_err(|_| SourceError::WorkspaceLookup)?); + let path = if path.is_absolute() { + path + } else { + root.join(path) + }; + path.canonicalize() + .map_err(|_| SourceError::WorkspaceLookup) + }; + let worktree = resolve(worktree)?; + let common = resolve(common)?; + let gitdir = resolve(gitdir)?; + if worktree != root || !common.is_dir() || !gitdir.is_dir() { + return Err(SourceError::WorkspaceLookup); + } + let atomic = common + .parent() + .ok_or(SourceError::WorkspaceLookup)? + .join(".atomic"); + match std::fs::metadata(&atomic) { + Ok(metadata) if metadata.is_dir() => Err(SourceError::WorkspaceLookup), + Ok(_) => Ok(()), + Err(error) if error.kind() == ErrorKind::NotFound && demonstrably_missing(&atomic) => { + Ok(()) + } + Err(_) => Err(SourceError::WorkspaceLookup), + } +} + /// One agent adapter, reduced to what the report needs from it. -pub(crate) struct AgentProbe<'a> { +pub(crate) struct AgentProbe { pub name: String, pub display_name: String, - /// The adapter's own "are Atomic hooks installed?" check, run against a - /// base directory — the check `atomic agent status` uses. - pub hooks_installed: Box bool + 'a>, } /// Collect the report from the real environment. @@ -287,7 +472,6 @@ pub(crate) fn collect() -> Report { .map(|agent| AgentProbe { name: agent.name().to_string(), display_name: agent.display_name().to_string(), - hooks_installed: Box::new(move |base| agent.is_installed(base)), }) .collect::>(); let packaged = atomic_agent::integrations::registered_integrations(); @@ -298,7 +482,7 @@ pub(crate) fn collect() -> Report { /// adapters, `packaged` the agents with an integration package. pub(crate) fn collect_from( sources: &Sources, - probes: &[AgentProbe<'_>], + probes: &[AgentProbe], packaged: &[String], ) -> Report { let home = sources.home.as_deref(); @@ -330,9 +514,7 @@ pub(crate) fn collect_from( .map(|agent| { let lookup = match &sources.integrations_root { Ok(root) => read_receipt(&root.join(&agent).join(RECEIPT_FILE)), - Err(reason) => ReceiptLookup::Unreadable(format!( - "integrations directory unresolved: {reason}" - )), + Err(_) => ReceiptLookup::Unreadable(ReceiptError::IntegrationsHome), }; (agent, lookup) }) @@ -362,7 +544,7 @@ pub(crate) fn collect_from( let state = match lookup { ReceiptLookup::Absent => IntegrationState::NotInstalled, ReceiptLookup::Unreadable(reason) => IntegrationState::Unreadable { - reason: reason.clone(), + reason: reason.to_string(), }, ReceiptLookup::Found(receipt) => { let mut files = FileCounts { @@ -415,23 +597,83 @@ pub(crate) fn collect_from( let mut agents: Vec = probes .iter() .map(|probe| { - let adapter = AdapterCheck { - workspace: workspace_root.map(|root| (probe.hooks_installed)(root)), - home: home.map(|home| (probe.hooks_installed)(home)), - }; let receipt = receipt_for(&probe.name); - let settings = match receipt { + let mut settings: Vec = match receipt { Some(ReceiptLookup::Found(receipt)) => receipt .settings .iter() .map(|entry| SettingsProbe { - path: display_path(&entry.target, home), - hooks: settings_hooks(&entry.target, &entry.command_prefix), + path: "receipt-listed settings".to_string(), + hooks: if known_settings_location( + &probe.name, + &entry.target, + home, + workspace_root, + ) { + settings_hooks( + &probe.name, + &entry.target, + &entry.hooks_key, + &entry.command_prefix, + ) + } else { + HookPresence::Unreadable(HookError::Invalid( + "receipt settings location cannot be verified", + )) + }, }) .collect(), _ => Vec::new(), }; - let (enabled, evidence) = classify_enabled(&probe.name, adapter, receipt, &settings); + // Built-in adapters can install without a receipt. Inspect the + // actual configuration instead of trusting their boolean checks. + let builtin_path = match probe.name.as_str() { + "claude-code" => Some(".claude/settings.json"), + "gemini-cli" => Some(".gemini/settings.json"), + "codex" => Some(".codex/hooks.json"), + _ => None, + }; + if let Some(relative) = builtin_path { + let prefix = format!("atomic agent hooks {}", probe.name); + for base in [workspace_root, home].into_iter().flatten() { + let path = base.join(relative); + settings.push(SettingsProbe { + path: display_path(&path, home), + hooks: settings_hooks(&probe.name, &path, "hooks", &prefix), + }); + } + if probe.name == "claude-code" { + if let Some(root) = workspace_root { + let path = root.join(".claude/settings.local.json"); + settings.push(SettingsProbe { + path: display_path(&path, home), + hooks: settings_hooks(&probe.name, &path, "hooks", &prefix), + }); + } + } + if home.is_none() { + settings.push(SettingsProbe { + path: "home settings".to_string(), + hooks: HookPresence::Unreadable(HookError::Invalid( + "home directory is unavailable", + )), + }); + } + if sources.workspace.is_err() { + settings.push(SettingsProbe { + path: "workspace settings".to_string(), + hooks: HookPresence::Unreadable(HookError::Invalid( + "workspace is unavailable", + )), + }); + } + } + let (mut enabled, mut evidence) = classify_enabled(receipt, &settings); + if builtin_path.is_none() && enabled == Enabled::No { + enabled = Enabled::Unknown; + evidence = + vec!["active hook or plugin configuration cannot be verified".to_string()]; + } AgentState { name: probe.name.clone(), display_name: probe.display_name.clone(), @@ -457,7 +699,7 @@ pub(crate) fn collect_from( }, Ok(None) => Workspace::NotFound, Err(reason) => Workspace::Unreadable { - reason: reason.clone(), + reason: reason.to_string(), }, }, integrations: Integrations { @@ -467,7 +709,11 @@ pub(crate) fn collect_from( .ok() .map(|root| display_path(root, home)), root_overridden: sources.integrations_root_overridden, - root_error: sources.integrations_root.as_ref().err().cloned(), + root_error: sources + .integrations_root + .as_ref() + .err() + .map(ToString::to_string), packages: integrations, }, skills: Skills { @@ -489,17 +735,49 @@ pub(crate) fn collect_from( enum ReceiptLookup { Found(Receipt), Absent, - Unreadable(String), + Unreadable(ReceiptError), +} + +#[derive(Debug)] +enum ReceiptError { + IntegrationsHome, + Read(ErrorKind), + Parse(serde_json::error::Category), +} + +impl fmt::Display for ReceiptError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::IntegrationsHome => write!( + f, + "integrations directory unresolved: {}", + SourceError::IntegrationsHome + ), + Self::Read(kind) => write!(f, "cannot read receipt: {}", io_summary(*kind)), + Self::Parse(category) => write!( + f, + "corrupt receipt: {}", + match category { + serde_json::error::Category::Io => "I/O error", + serde_json::error::Category::Syntax => "invalid JSON syntax", + serde_json::error::Category::Data => "invalid receipt data", + serde_json::error::Category::Eof => "incomplete JSON", + } + ), + } + } } fn read_receipt(path: &Path) -> ReceiptLookup { match std::fs::read_to_string(path) { Ok(text) => match serde_json::from_str::(&text) { Ok(receipt) => ReceiptLookup::Found(receipt), - Err(error) => ReceiptLookup::Unreadable(format!("corrupt receipt: {error}")), + Err(error) => ReceiptLookup::Unreadable(ReceiptError::Parse(error.classify())), }, - Err(error) if error.kind() == ErrorKind::NotFound => ReceiptLookup::Absent, - Err(error) => ReceiptLookup::Unreadable(format!("cannot read receipt: {error}")), + Err(error) if error.kind() == ErrorKind::NotFound && demonstrably_missing(path) => { + ReceiptLookup::Absent + } + Err(error) => ReceiptLookup::Unreadable(ReceiptError::Read(error.kind())), } } @@ -531,7 +809,24 @@ fn file_state(path: &Path, recorded_blake3: &str) -> FileState { enum HookPresence { Present, Absent, - Unreadable(String), + Disabled, + Restricted, + Unreadable(HookError), +} + +#[derive(Debug)] +enum HookError { + Read(ErrorKind), + Invalid(&'static str), +} + +impl fmt::Display for HookError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Read(kind) => write!(f, "settings could not be read: {}", io_summary(*kind)), + Self::Invalid(reason) => f.write_str(reason), + } + } } struct SettingsProbe { @@ -539,12 +834,75 @@ struct SettingsProbe { hooks: HookPresence, } -fn settings_hooks(path: &Path, command_prefix: &str) -> HookPresence { +fn known_settings_location( + agent: &str, + path: &Path, + home: Option<&Path>, + workspace: Option<&Path>, +) -> bool { + let relative = match agent { + "claude-code" => ".claude/settings.json", + "gemini-cli" => ".gemini/settings.json", + "codex" => ".codex/hooks.json", + _ => return false, + }; + [home, workspace] + .into_iter() + .flatten() + .any(|base| base.join(relative) == path) + || (agent == "claude-code" + && workspace.is_some_and(|base| base.join(".claude/settings.local.json") == path)) +} + +fn settings_hooks(agent: &str, path: &Path, hooks_key: &str, command_prefix: &str) -> HookPresence { match std::fs::read_to_string(path) { - Ok(text) if text.contains(command_prefix) => HookPresence::Present, - Ok(_) => HookPresence::Absent, - Err(error) if error.kind() == ErrorKind::NotFound => HookPresence::Absent, - Err(error) => HookPresence::Unreadable(error.to_string()), + Ok(text) => match serde_json::from_str::(&text) { + Ok(root) => match atomic_agent::hooks::live::json_hooks_active( + agent, + &root, + hooks_key, + command_prefix, + ) { + Ok(active) => { + // Named Gemini exclusions can also mask a hook declared in + // another settings scope, so don't infer the merged state. + let restricted = root.get("hooks").is_some_and(has_disabled_entry) + || (agent == "gemini-cli" + && root + .get("hooksConfig") + .and_then(|v| v.get("disabled")) + .and_then(serde_json::Value::as_array) + .is_some_and(|names| !names.is_empty())); + let disabled = root.as_object().is_some_and(|object| { + atomic_agent::hooks::live::globally_disabled(agent, object) + }); + match (active, restricted || disabled) { + (true, true) => HookPresence::Restricted, + (true, false) => HookPresence::Present, + (false, true) => HookPresence::Disabled, + (false, false) => HookPresence::Absent, + } + } + Err(reason) => HookPresence::Unreadable(HookError::Invalid(reason)), + }, + Err(_) => HookPresence::Unreadable(HookError::Invalid("settings could not be parsed")), + }, + Err(error) if error.kind() == ErrorKind::NotFound && demonstrably_missing(path) => { + HookPresence::Absent + } + Err(error) => HookPresence::Unreadable(HookError::Read(error.kind())), + } +} + +fn has_disabled_entry(value: &serde_json::Value) -> bool { + match value { + serde_json::Value::Object(object) => { + object.get("disabled") == Some(&serde_json::Value::Bool(true)) + || object.get("enabled") == Some(&serde_json::Value::Bool(false)) + || object.values().any(has_disabled_entry) + } + serde_json::Value::Array(values) => values.iter().any(has_disabled_entry), + _ => false, } } @@ -564,17 +922,31 @@ fn describe_source(source: &str, agent: &str, home: Option<&Path>) -> (&'static // Skills fn read_skills_package(cache: &Path) -> SkillsPackage { - if !cache - .join(atomic_agent::integrations::MANIFEST_FILE) - .exists() - { - return SkillsPackage::NotFound { - reason: "no synced atomic-skills package (it is synced by `atomic agent enable`; \ + let manifest_path = cache.join(atomic_agent::integrations::MANIFEST_FILE); + let text = match std::fs::read_to_string(&manifest_path) { + Ok(text) => text, + Err(error) + if error.kind() == ErrorKind::NotFound && demonstrably_missing(&manifest_path) => + { + return SkillsPackage::NotFound { + reason: "no synced atomic-skills package (it is synced by `atomic agent enable`; \ `--from-skills` installs leave no cache)" - .to_string(), - }; - } - match IntegrationManifest::load(cache) { + .to_string(), + } + } + Err(error) => { + return SkillsPackage::Unreadable { + reason: format!( + "cannot read skills package manifest: {}", + io_summary(error.kind()) + ), + } + } + }; + match toml::from_str::(&text) { + Ok(manifest) if manifest.check_schema().is_err() => SkillsPackage::Unreadable { + reason: "unsupported skills package manifest schema".to_string(), + }, Ok(manifest) => SkillsPackage::Available { name: SKILLS_PACKAGE, version: manifest.version, @@ -584,8 +956,8 @@ fn read_skills_package(cache: &Path) -> SkillsPackage { .map(|skill| skill.name) .collect(), }, - Err(error) => SkillsPackage::Unreadable { - reason: error.to_string(), + Err(_) => SkillsPackage::Unreadable { + reason: "skills package manifest could not be parsed".to_string(), }, } } @@ -631,90 +1003,126 @@ fn frontmatter_version(text: &str) -> Option { // Agents -/// The adapter's hook check, run from the workspace and from the home -/// directory; `None` where that base does not exist. -#[derive(Clone, Copy)] -struct AdapterCheck { - workspace: Option, - home: Option, -} - /// Decide whether an agent's Atomic hooks are active, and on what evidence. /// /// "Installed" (a receipt exists) and "enabled" (hooks are in the agent's /// live configuration) are separate questions: a receipt survives a user /// deleting the hooks by hand, and the built-in hooks need no receipt. fn classify_enabled( - agent: &str, - adapter: AdapterCheck, receipt: Option<&ReceiptLookup>, settings: &[SettingsProbe], ) -> (Enabled, Vec) { let mut evidence = Vec::new(); - match (adapter.workspace, adapter.home) { - (Some(true), Some(true)) => { - evidence.push(format!("the {agent} adapter finds Atomic hooks installed")) - } - (Some(true), _) => evidence.push(format!( - "the {agent} adapter finds Atomic hooks in the workspace configuration" - )), - (_, Some(true)) => evidence.push(format!( - "the {agent} adapter finds Atomic hooks in the home-directory configuration" - )), - _ => {} - } for probe in settings { - if matches!(probe.hooks, HookPresence::Present) { + if matches!( + probe.hooks, + HookPresence::Present | HookPresence::Restricted + ) { evidence.push(format!("Atomic hook commands present in {}", probe.path)); } } + let unreadable: Vec = settings + .iter() + .filter_map(|probe| match &probe.hooks { + HookPresence::Unreadable(reason) => { + Some(format!("cannot inspect {}: {reason}", probe.path)) + } + _ => None, + }) + .collect(); + if !unreadable.is_empty() { + return (Enabled::Unknown, unreadable); + } if !evidence.is_empty() { + if settings.iter().any(|probe| { + matches!( + probe.hooks, + HookPresence::Disabled | HookPresence::Restricted + ) + }) { + return ( + Enabled::Unknown, + vec![ + "a settings scope disables hooks; effective enablement cannot be verified" + .to_string(), + ], + ); + } return (Enabled::Yes, evidence); } - match receipt { None | Some(ReceiptLookup::Absent) => (Enabled::No, evidence), Some(ReceiptLookup::Unreadable(reason)) => ( Enabled::Unknown, vec![format!("integration receipt unreadable: {reason}")], ), - Some(ReceiptLookup::Found(_)) if settings.is_empty() => ( - Enabled::Unknown, - vec![ - "the integration is installed, but its hooks are not in a settings file \ - Atomic can inspect, and the adapter reports none" - .to_string(), - ], - ), + Some(ReceiptLookup::Found(receipt)) + if receipt.settings.is_empty() || settings.is_empty() => + { + ( + Enabled::Unknown, + vec![ + "the integration is installed, but its hooks are not in a settings file \ + Atomic can inspect" + .to_string(), + ], + ) + } Some(ReceiptLookup::Found(_)) => { - let unreadable: Vec = settings - .iter() - .filter_map(|probe| match &probe.hooks { - HookPresence::Unreadable(error) => { - Some(format!("cannot read {}: {error}", probe.path)) - } - _ => None, - }) - .collect(); - if unreadable.is_empty() { - let paths: Vec<&str> = settings.iter().map(|probe| probe.path.as_str()).collect(); - ( - Enabled::No, - vec![format!( - "the integration receipt lists {}, but no Atomic hook commands remain there", - paths.join(", ") - )], - ) - } else { - (Enabled::Unknown, unreadable) - } + let paths: Vec<&str> = settings.iter().map(|probe| probe.path.as_str()).collect(); + ( + Enabled::No, + vec![format!( + "the inspected settings {} contain no active Atomic hook commands", + paths.join(", ") + )], + ) } } } // Git shim -fn collect_git_shim(workspace: &Result, String>, home: Option<&Path>) -> GitShim { +#[derive(Debug)] +enum ShimConfigError { + Location, + Read(ErrorKind), + Parse, +} + +impl fmt::Display for ShimConfigError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Location => f.write_str("cannot resolve repository configuration location"), + Self::Read(kind) => write!( + f, + "cannot read repository configuration: {}", + io_summary(*kind) + ), + Self::Parse => f.write_str("repository configuration could not be parsed"), + } + } +} + +fn read_shim_config(root: &Path) -> Result { + let dir = atomic_repository::Repository::canonical_dot_dir(root) + .map_err(|_| ShimConfigError::Location)?; + // Reading directly avoids `Path::exists` treating access errors as an + // absent config, while preserving the default for a genuinely missing file. + let path = dir.join("config.toml"); + match std::fs::read_to_string(&path) { + Ok(text) => toml::from_str(&text).map_err(|_| ShimConfigError::Parse), + Err(error) if error.kind() == ErrorKind::NotFound && demonstrably_missing(&path) => { + Ok(Default::default()) + } + Err(error) => Err(ShimConfigError::Read(error.kind())), + } +} + +fn collect_git_shim( + workspace: &Result, SourceError>, + home: Option<&Path>, +) -> GitShim { let root = match workspace { Ok(Some(root)) => root, Ok(None) => { @@ -733,10 +1141,10 @@ fn collect_git_shim(workspace: &Result, String>, home: Option<&P } }; - let (status, reason) = match shim_config(root) { + let (status, reason) = match read_shim_config(root) { Ok(config) if config.git.shim.enabled => (ShimStatus::Enabled, None), Ok(_) => (ShimStatus::Disabled, None), - Err(error) => (ShimStatus::Unknown, Some(error.to_string())), + Err(reason) => (ShimStatus::Unknown, Some(reason.to_string())), }; let hooks = match inspect_dispatchers(root) { Ok(None) => GitHooks::NoGitRepository, @@ -753,8 +1161,8 @@ fn collect_git_shim(workspace: &Result, String>, home: Option<&P }) .collect(), }, - Err(error) => GitHooks::Unreadable { - reason: error.to_string(), + Err(_) => GitHooks::Unreadable { + reason: "cannot inspect Git repository hooks or administrative paths".to_string(), }, }; GitShim { @@ -768,7 +1176,15 @@ fn collect_git_shim(workspace: &Result, String>, home: Option<&P /// carry the user's account name. The part after `~` is joined with `/` on /// every platform, so Windows never renders a mixed `~/.x\settings.json`. fn display_path(path: &Path, home: Option<&Path>) -> String { - match home.and_then(|home| path.strip_prefix(home).ok()) { + let canonical_home = home.and_then(|home| home.canonicalize().ok()); + let relative = home + .and_then(|home| path.strip_prefix(home).ok()) + .or_else(|| { + canonical_home + .as_deref() + .and_then(|home| path.strip_prefix(home).ok()) + }); + match relative { Some(rest) if rest.as_os_str().is_empty() => "~".to_string(), Some(rest) => { let parts: Vec<_> = rest @@ -862,11 +1278,10 @@ mod tests { } } - fn probe(name: &str, installed: bool) -> AgentProbe<'static> { + fn probe(name: &str) -> AgentProbe { AgentProbe { name: name.to_string(), display_name: name.to_uppercase(), - hooks_installed: Box::new(move |_| installed), } } @@ -889,7 +1304,7 @@ mod tests { let fixture = Fixture::new(); let report = collect_from( &fixture.sources(None), - &[probe("claude-code", false)], + &[probe("claude-code")], &["claude-code".to_string(), SKILLS_PACKAGE.to_string()], ); @@ -934,7 +1349,7 @@ mod tests { let report = collect_from( &fixture.sources(None), - &[probe("opencode", false)], + &[probe("opencode")], &["opencode".to_string()], ); @@ -965,7 +1380,7 @@ mod tests { let report = collect_from( &fixture.sources(None), - &[probe("cline", false)], + &[probe("cline")], &["cline".to_string()], ); @@ -995,9 +1410,9 @@ mod tests { fn an_unresolvable_integrations_directory_is_reported_not_treated_as_empty() { let fixture = Fixture::new(); let mut sources = fixture.sources(None); - sources.integrations_root = Err("cannot resolve home directory".to_string()); + sources.integrations_root = Err(SourceError::IntegrationsHome); - let report = collect_from(&sources, &[probe("cline", false)], &["cline".to_string()]); + let report = collect_from(&sources, &[probe("cline")], &["cline".to_string()]); assert_eq!( report.integrations.root_error.as_deref(), @@ -1014,6 +1429,33 @@ mod tests { assert_eq!(agent(&report, "cline").enabled, Enabled::Unknown); } + #[test] + fn failed_workspace_lookup_stays_unknown_in_both_report_fields() { + let fixture = Fixture::new(); + let mut sources = fixture.sources(None); + sources.workspace = Err(SourceError::WorkspaceLookup); + + let report = collect_from(&sources, &[], &[]); + assert!(matches!(report.workspace, Workspace::Unreadable { .. })); + assert_eq!(report.git_shim.status, ShimStatus::Unknown); + let json = serde_json::to_string(&report).unwrap(); + assert!(json.contains("cannot determine the current workspace")); + assert!(!json.contains(&fixture.home.path().display().to_string())); + } + + #[test] + fn unsupported_manifest_schema_does_not_echo_the_agent_name() { + let fixture = Fixture::new(); + fixture.skills_cache("schema = 2\nagent = \"SYNTHETIC_SCHEMA_SECRET\"\nversion = \"1\"\n"); + let package = + read_skills_package(&fixture.integrations().join(SKILLS_PACKAGE).join("repo")); + let SkillsPackage::Unreadable { reason } = package else { + panic!("unsupported manifest must be unreadable"); + }; + assert!(reason.contains("schema")); + assert!(!reason.contains("SYNTHETIC_SCHEMA_SECRET")); + } + #[test] fn skills_are_found_from_receipts_with_their_package_and_file_versions() { let fixture = Fixture::new(); @@ -1043,7 +1485,7 @@ mod tests { let report = collect_from( &fixture.sources(None), - &[probe("claude-code", false), probe("cline", false)], + &[probe("claude-code"), probe("cline")], &["claude-code".to_string(), "cline".to_string()], ); @@ -1113,32 +1555,24 @@ mod tests { serde_json::from_value(serde_json::json!({ "schema": 1, "agent": "x", "version": "1", "cli_version": "1", "installed_at": "t", "source": "s", "files": [], + "settings": [{"target":"/tmp/x", "hooks_key":"hooks", "command_prefix":"atomic agent hooks x"}], })) .unwrap(), ) } - const NOTHING: AdapterCheck = AdapterCheck { - workspace: Some(false), - home: Some(false), - }; - #[test] fn enabled_rests_on_live_hooks_not_on_the_receipt() { // Installed, but the user removed the hooks from settings by hand. let (enabled, evidence) = classify_enabled( - "x", - NOTHING, Some(&receipt()), &[settings("~/.x/settings.json", HookPresence::Absent)], ); assert_eq!(enabled, Enabled::No); - assert!(evidence[0].contains("no Atomic hook commands remain")); + assert!(evidence[0].contains("no active Atomic hook commands")); // Installed, and the settings file still carries the hooks. let (enabled, evidence) = classify_enabled( - "x", - NOTHING, Some(&receipt()), &[settings("~/.x/settings.json", HookPresence::Present)], ); @@ -1147,96 +1581,132 @@ mod tests { evidence, ["Atomic hook commands present in ~/.x/settings.json"] ); - - // Built-in hooks need no receipt at all. - let (enabled, evidence) = classify_enabled( - "x", - AdapterCheck { - workspace: Some(true), - home: Some(false), - }, - None, - &[], - ); - assert_eq!(enabled, Enabled::Yes); - assert!(evidence[0].contains("workspace configuration")); } #[test] fn enabled_is_unknown_when_the_evidence_cannot_be_read() { let (enabled, evidence) = classify_enabled( - "x", - NOTHING, Some(&receipt()), &[settings( "~/.x/settings.json", - HookPresence::Unreadable("permission denied".into()), + HookPresence::Unreadable(HookError::Read(ErrorKind::PermissionDenied)), )], ); assert_eq!(enabled, Enabled::Unknown); assert!(evidence[0].contains("permission denied")); // A package whose hooks live outside any settings file. - let (enabled, _) = classify_enabled("x", NOTHING, Some(&receipt()), &[]); + let (enabled, _) = classify_enabled(Some(&receipt()), &[]); assert_eq!(enabled, Enabled::Unknown); - // Outside a workspace with no adapter hit and no receipt: no. - let (enabled, evidence) = classify_enabled( - "x", - AdapterCheck { - workspace: None, - home: Some(false), - }, - None, - &[], - ); + // No receipt and no hooks in the inspected settings: no. + let (enabled, evidence) = classify_enabled(None, &[]); assert_eq!(enabled, Enabled::No); assert!(evidence.is_empty()); + + let (enabled, _) = classify_enabled( + None, + &[settings( + "home", + HookPresence::Unreadable(HookError::Invalid("bad settings")), + )], + ); + assert_eq!(enabled, Enabled::Unknown); + + let (enabled, _) = classify_enabled( + None, + &[ + settings("workspace", HookPresence::Present), + settings("home", HookPresence::Disabled), + ], + ); + assert_eq!(enabled, Enabled::Unknown); + } + + #[test] + fn missing_home_and_failed_workspace_lookup_are_unknown() { + let fixture = Fixture::new(); + let mut sources = fixture.sources(None); + sources.home = None; + let report = collect_from(&sources, &[probe("claude-code")], &[]); + assert_eq!(agent(&report, "claude-code").enabled, Enabled::Unknown); + + let mut sources = fixture.sources(None); + sources.workspace = Err(SourceError::WorkspaceLookup); + let report = collect_from(&sources, &[probe("claude-code")], &[]); + assert_eq!(agent(&report, "claude-code").enabled, Enabled::Unknown); } #[test] fn receipt_settings_are_checked_against_the_live_file() { let fixture = Fixture::new(); - let settings_path = fixture.home.path().join(".x").join("settings.json"); + let settings_path = fixture.home.path().join(".claude").join("settings.json"); fs::create_dir_all(settings_path.parent().unwrap()).unwrap(); fs::write( &settings_path, - r#"{"hooks":{"Stop":[{"command":"atomic agent hooks x stop"}]}}"#, + r#"{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"atomic agent hooks claude-code stop"}]}]}}"#, ) .unwrap(); fixture.write_receipt( - "x", + "claude-code", &serde_json::json!({ - "schema": 1, "agent": "x", "version": "3.0.0", "cli_version": "0.19.0", + "schema": 1, "agent": "claude-code", "version": "3.0.0", "cli_version": "0.19.0", "installed_at": "t", "source": "https://alice:s3cret@example.com/pkg?token=1", "files": [], "settings": [{ "target": settings_path, "hooks_key": "hooks", - "command_prefix": "atomic agent hooks x", + "command_prefix": "atomic agent hooks claude-code", }], }), ); let report = collect_from( &fixture.sources(None), - &[probe("x", false)], - &["x".to_string()], + &[probe("claude-code")], + &["claude-code".to_string()], ); - let x = agent(&report, "x"); + let x = agent(&report, "claude-code"); assert_eq!(x.enabled, Enabled::Yes); - assert_eq!( - x.evidence, - ["Atomic hook commands present in ~/.x/settings.json"] - ); + assert!(x + .evidence + .iter() + .any(|e| e == "Atomic hook commands present in ~/.claude/settings.json")); - let IntegrationState::Installed(installed) = integration(&report, "x") else { + let IntegrationState::Installed(installed) = integration(&report, "claude-code") else { panic!("x is installed"); }; assert_eq!(installed.source_kind, "url"); assert_eq!(installed.source, "https://***@example.com/pkg"); } + #[test] + fn gemini_disabled_names_do_not_prove_other_scopes_active() { + let home = TempDir::new().unwrap(); + let path = home.path().join("settings.json"); + fs::write( + &path, + r#"{"hooksConfig":{"disabled":["atomic-test"]},"hooks":{}}"#, + ) + .unwrap(); + let (enabled, _) = classify_enabled( + None, + &[ + settings("workspace", HookPresence::Present), + settings( + "home", + settings_hooks( + "gemini-cli", + &path, + "hooks", + "atomic agent hooks gemini-cli", + ), + ), + ], + ); + assert_eq!(enabled, Enabled::Unknown); + } + #[test] fn a_workspace_without_git_reports_the_shim_consent_and_no_git() { let fixture = Fixture::new(); @@ -1317,4 +1787,18 @@ mod tests { assert_eq!(display_path(Path::new("/opt/x"), Some(home)), "/opt/x"); assert_eq!(display_path(Path::new("/opt/x"), None), "/opt/x"); } + + #[test] + #[cfg(unix)] + fn canonical_paths_under_a_symlinked_home_are_normalized() { + let temp = TempDir::new().unwrap(); + let home = temp.path().join("home"); + fs::create_dir(&home).unwrap(); + let alias = temp.path().join("home-alias"); + std::os::unix::fs::symlink(&home, &alias).unwrap(); + assert_eq!( + display_path(&home.canonicalize().unwrap().join("project"), Some(&alias)), + "~/project" + ); + } } diff --git a/atomic-cli/src/commands/diagnostics/mod.rs b/atomic-cli/src/commands/diagnostics/mod.rs index 86e87fa4..09a3c8f8 100644 --- a/atomic-cli/src/commands/diagnostics/mod.rs +++ b/atomic-cli/src/commands/diagnostics/mod.rs @@ -5,11 +5,11 @@ //! agent integration packages and their versions, installed skills, which //! agents have Atomic hooks enabled, and whether the Git shim is enabled. //! -//! Nothing is written, repaired, or fetched. Values that cannot be read are -//! reported as unknown with the reason. The report never includes -//! credentials, tokens, file contents, or configuration values beyond the -//! booleans and versions listed above; paths under the home directory are -//! shown as `~`. +//! Values that cannot be read are reported as unknown with a safe reason. +//! No configuration is written, repaired, or fetched; normal command logging +//! still applies. Parser errors do not include source text, and paths under a +//! known home directory are shown as `~`. Review metadata and paths before +//! sharing the report, since user-controlled values may contain secrets. //! //! # Examples //! diff --git a/atomic-cli/tests/it/diagnostics_integration_test.rs b/atomic-cli/tests/it/diagnostics_integration_test.rs index c484ab6d..d967f326 100644 --- a/atomic-cli/tests/it/diagnostics_integration_test.rs +++ b/atomic-cli/tests/it/diagnostics_integration_test.rs @@ -3,6 +3,7 @@ use std::path::Path; use std::process::{Command, Output}; +use std::sync::OnceLock; use serde_json::Value; use tempfile::TempDir; @@ -10,30 +11,56 @@ use tempfile::TempDir; struct Fixture { work: TempDir, home: TempDir, + binary: std::path::PathBuf, } impl Fixture { fn new() -> Self { - Self { - work: tempfile::tempdir().unwrap(), - home: tempfile::tempdir().unwrap(), - } + let home = tempfile::tempdir().unwrap(); + let work = tempfile::tempdir_in(home.path()).unwrap(); + // Cargo can release its target lock while tests run, allowing another + // worktree to replace the shared binary between fixtures or commands. + static BINARY: OnceLock<(Vec, std::fs::Permissions)> = OnceLock::new(); + let (bytes, permissions) = BINARY.get_or_init(|| { + let path = Path::new(env!("CARGO_BIN_EXE_atomic")); + ( + std::fs::read(path).expect("read test binary"), + std::fs::metadata(path) + .expect("stat test binary") + .permissions(), + ) + }); + let binary = home.path().join("atomic-under-test"); + std::fs::write(&binary, bytes).expect("pin test binary"); + std::fs::set_permissions(&binary, permissions.clone()) + .expect("make test binary executable"); + Self { work, home, binary } } fn run(&self, args: &[&str]) -> Output { - let mut command = Command::new(env!("CARGO_BIN_EXE_atomic")); + self.run_at(self.work.path(), args) + } + + fn run_at(&self, work: &Path, args: &[&str]) -> Output { + let mut command = Command::new(&self.binary); for (name, _) in std::env::vars_os() { - if name.to_string_lossy().starts_with("ATOMIC_") { + if name.to_string_lossy().starts_with("ATOMIC_") + || name.to_string_lossy().starts_with("GIT_") + { command.env_remove(name); } } command .args(args) - .current_dir(self.work.path()) + .current_dir(work) .env("HOME", self.home.path()) .env("ATOMIC_HOME", self.home.path().join(".atomic")) .env("ATOMIC_CONFIG_DIR", self.home.path().join(".atomic")) .env("ATOMIC_NONINTERACTIVE", "1") + .env("XDG_CONFIG_HOME", self.home.path().join(".config")) + .env("XDG_DATA_HOME", self.home.path().join(".local/share")) + .env("XDG_CACHE_HOME", self.home.path().join(".cache")) + .env("XDG_STATE_HOME", self.home.path().join(".local/state")) .env("GIT_CONFIG_NOSYSTEM", "1") .env("GIT_CONFIG_GLOBAL", "/dev/null") .env("NO_COLOR", "1") @@ -41,12 +68,89 @@ impl Fixture { .expect("run atomic") } + fn ok_at(&self, work: &Path, args: &[&str]) -> String { + let output = self.run_at(work, args); + assert!(output.status.success(), "{args:?}: {output:?}"); + assert!(!String::from_utf8_lossy(&output.stderr).contains("SYNTHETIC_")); + String::from_utf8(output.stdout).unwrap() + } + + fn git(&self, work: &Path, args: &[&str]) { + let output = Command::new("git") + .env_clear() + .env("PATH", std::env::var_os("PATH").unwrap()) + .env("HOME", self.home.path()) + .env("GIT_CONFIG_NOSYSTEM", "1") + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .current_dir(work) + .args(args) + .output() + .expect("run git"); + assert!(output.status.success(), "git {args:?}: {output:?}"); + } + + fn linked_git_worktree(&self, atomic: bool) -> std::path::PathBuf { + let source = self.home.path().join("source"); + std::fs::create_dir(&source).unwrap(); + self.git(&source, &["init", "-q"]); + self.git( + &source, + &[ + "-c", + "user.name=Test", + "-c", + "user.email=test@example.invalid", + "commit", + "--allow-empty", + "-qm", + "initial", + ], + ); + if atomic { + self.ok_at(&source, &["init", "--view", "main"]); + } + self.git( + &source, + &[ + "worktree", + "add", + "--detach", + self.work.path().to_str().unwrap(), + "HEAD", + ], + ); + let pointer = std::fs::read_to_string(self.work.path().join(".git")).unwrap(); + let git_dir = pointer.trim().strip_prefix("gitdir: ").unwrap(); + let path = Path::new(git_dir); + if path.is_absolute() { + path.to_path_buf() + } else { + self.work.path().join(path) + } + } + fn ok(&self, args: &[&str]) -> String { let output = self.run(args); assert!(output.status.success(), "{args:?}: {output:?}"); + assert!( + !String::from_utf8_lossy(&output.stderr).contains("SYNTHETIC_"), + "synthetic source values must not reach stderr" + ); String::from_utf8(output.stdout).unwrap() } + fn assert_home_redacted(&self, output: &str) { + for home in [ + self.home.path().to_path_buf(), + self.home.path().canonicalize().unwrap(), + ] { + assert!( + !output.contains(&home.display().to_string()), + "home directory must be normalized" + ); + } + } + fn json(&self) -> Value { let text = self.ok(&["diagnostics", "--json"]); serde_json::from_str(&text) @@ -64,7 +168,7 @@ impl Fixture { let settings = home.join(".claude/settings.json"); std::fs::write( &settings, - r#"{"hooks":{"Stop":[{"hooks":[{"command":"atomic agent hooks claude-code stop"}]}]}}"#, + r#"{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"atomic agent hooks claude-code stop"}]}]}}"#, ) .unwrap(); let receipt = serde_json::json!({ @@ -73,7 +177,7 @@ impl Fixture { "version": version, "cli_version": "0.19.0", "installed_at": "2026-10-01T12:00:00+00:00", - "source": "https://token:secret@example.com/pkg", + "source": "https://token:secret@example.com/pkg?token=SYNTHETIC_QUERY#SYNTHETIC_FRAGMENT", "files": [{ "dst": file, "blake3": blake3::hash(body.as_bytes()).to_hex().to_string(), @@ -90,6 +194,563 @@ impl Fixture { } } +#[test] +fn claude_enabled_requires_an_active_hook_not_unrelated_text() { + let fixture = Fixture::new(); + fixture.install_integration("claude-code", "1.4.0"); + let settings = fixture.home.path().join(".claude/settings.json"); + for body in [ + r#"{"notes":"atomic agent hooks claude-code is not installed","hooks":{}}"#, + r#"{"disableAllHooks":true,"hooks":{"Stop":[{"hooks":[{"type":"command","command":"atomic agent hooks claude-code stop"}]}]}}"#, + r#"{"hooks":{"Stop":[{"hooks":[{"type":"prompt","prompt":"atomic agent hooks claude-code stop"}]}]}}"#, + ] { + std::fs::write(&settings, body).unwrap(); + let report = fixture.json(); + assert_eq!( + find(&report["integrations"]["packages"], "agent", "claude-code")["status"], + "installed" + ); + assert_ne!( + find(&report["agents"], "name", "claude-code")["enabled"], + "yes", + "{body}" + ); + let text = fixture.ok(&["diagnostics"]); + let line = text + .lines() + .find(|line| line.contains("Claude Code (claude-code):")) + .expect("Claude listed"); + assert!(!line.contains("yes"), "{line}"); + } +} + +#[test] +fn built_in_claude_hooks_work_without_a_receipt() { + let fixture = Fixture::new(); + let path = fixture.home.path().join(".claude/settings.json"); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, r#"{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"test -d .atomic || test -f .atomic-sandbox && atomic agent hooks claude-code stop || true"}]}]}}"#).unwrap(); + let report = fixture.json(); + assert_eq!( + find(&report["integrations"]["packages"], "agent", "claude-code")["status"], + "not_installed" + ); + assert_eq!( + find(&report["agents"], "name", "claude-code")["enabled"], + "yes" + ); + assert!(fixture + .ok(&["diagnostics"]) + .contains("Claude Code (claude-code): yes")); +} + +#[test] +fn receipt_hook_key_cannot_promote_an_unrelated_settings_field() { + let fixture = Fixture::new(); + fixture.install_integration("claude-code", "1.4.0"); + let settings = fixture.home.path().join(".claude/settings.json"); + let hooks = serde_json::json!({"Stop":[{"hooks":[{"type":"command","command":"atomic agent hooks claude-code stop"}]}]}); + std::fs::write( + &settings, + serde_json::json!({"hooks":{},"otherHooks":hooks}).to_string(), + ) + .unwrap(); + let receipt = fixture + .home + .path() + .join(".atomic/integrations/claude-code/receipt.json"); + let mut data: Value = serde_json::from_slice(&std::fs::read(&receipt).unwrap()).unwrap(); + data["settings"][0]["hooks_key"] = "otherHooks".into(); + std::fs::write(receipt, data.to_string()).unwrap(); + assert_eq!( + find(&fixture.json()["agents"], "name", "claude-code")["enabled"], + "unknown" + ); +} + +#[test] +fn built_in_codex_and_gemini_hooks_require_active_native_entries() { + for (agent, path, event, verb) in [ + ("codex", ".codex/hooks.json", "Stop", "stop"), + ( + "gemini-cli", + ".gemini/settings.json", + "AfterAgent", + "after-agent", + ), + ] { + let fixture = Fixture::new(); + let path = fixture.home.path().join(path); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + let mut settings = serde_json::json!({ + "hooks": {event: [{"hooks": [{"type":"command", "name":"atomic-test", "command":format!("atomic agent hooks {agent} {verb}")}]}]} + }); + std::fs::write(&path, settings.to_string()).unwrap(); + assert_eq!( + find(&fixture.json()["agents"], "name", agent)["enabled"], + "yes", + "{agent}" + ); + settings["hooks"][event][0]["hooks"][0]["disabled"] = true.into(); + std::fs::write(&path, settings.to_string()).unwrap(); + assert_ne!( + find(&fixture.json()["agents"], "name", agent)["enabled"], + "yes", + "{agent}" + ); + } +} + +#[test] +fn malformed_repository_config_never_discloses_values_in_either_renderer() { + let fixture = Fixture::new(); + fixture.ok(&["init", "--view", "main"]); + let config = fixture.work.path().join(".atomic/config.toml"); + let cases = [ + "[remotes.origin]\nurl = \"https://SYNTHETIC_USER:SYNTHETIC_PASSWORD@example.com/repo?token=SYNTHETIC_QUERY#SYNTHETIC_FRAGMENT\" typo\n", + "[git.shim]\nenabled = \"SYNTHETIC_TYPE_VALUE\"\n", + ]; + let mut leaks = Vec::new(); + for input in cases { + std::fs::write(&config, input).unwrap(); + let text = fixture.ok(&["diagnostics"]); + let json = fixture.ok(&["diagnostics", "--json"]); + let report: Value = serde_json::from_str(&json).unwrap(); + assert_eq!(report["git_shim"]["status"], "unknown"); + assert!(report["git_shim"]["reason"] + .as_str() + .unwrap() + .contains("configuration")); + for (format, output) in [("text", &text), ("json", &json)] { + if output.contains("SYNTHETIC_") { + leaks.push(format); + } + if output.contains(&fixture.home.path().display().to_string()) { + leaks.push("home path"); + } + fixture.assert_home_redacted(output); + } + } + assert!( + leaks.is_empty(), + "configuration values leaked into formats: {leaks:?}" + ); +} + +#[test] +fn malformed_receipt_and_manifest_never_disclose_values_in_either_renderer() { + let fixture = Fixture::new(); + let integration = fixture.home.path().join(".atomic/integrations/claude-code"); + std::fs::create_dir_all(&integration).unwrap(); + std::fs::write( + integration.join("receipt.json"), + r#"{"schema":"SYNTHETIC_RECEIPT_SECRET"}"#, + ) + .unwrap(); + let cache = fixture + .home + .path() + .join(".atomic/integrations/atomic-skills/repo"); + std::fs::create_dir_all(&cache).unwrap(); + std::fs::write( + cache.join("atomic-integration.toml"), + "schema = \"SYNTHETIC_MANIFEST_SECRET\"\n", + ) + .unwrap(); + let text = fixture.ok(&["diagnostics"]); + let json = fixture.ok(&["diagnostics", "--json"]); + let report: Value = serde_json::from_str(&json).unwrap(); + assert_eq!( + find(&report["integrations"]["packages"], "agent", "claude-code")["status"], + "unreadable" + ); + assert_eq!( + find(&report["agents"], "name", "claude-code")["enabled"], + "unknown" + ); + assert_eq!(report["skills"]["package"]["status"], "unreadable"); + for output in [&text, &json] { + assert!( + !output.contains("SYNTHETIC_"), + "source values must not reach diagnostics" + ); + fixture.assert_home_redacted(output); + } +} + +#[test] +fn unreadable_configuration_and_settings_remain_unknown_without_home_paths() { + let fixture = Fixture::new(); + fixture.ok(&["init", "--view", "main"]); + let config = fixture.work.path().join(".atomic/config.toml"); + std::fs::remove_file(&config).unwrap(); + std::fs::create_dir(&config).unwrap(); + fixture.install_integration("claude-code", "1.4.0"); + let settings = fixture.home.path().join(".claude/settings.json"); + std::fs::remove_file(&settings).unwrap(); + std::fs::create_dir(&settings).unwrap(); + + let text = fixture.ok(&["diagnostics"]); + let json = fixture.ok(&["diagnostics", "--json"]); + let report: Value = serde_json::from_str(&json).unwrap(); + assert_eq!(report["git_shim"]["status"], "unknown"); + assert_eq!( + find(&report["agents"], "name", "claude-code")["enabled"], + "unknown" + ); + assert!(report["git_shim"]["reason"] + .as_str() + .unwrap() + .contains("configuration")); + for output in [&text, &json] { + fixture.assert_home_redacted(output); + } +} + +#[test] +fn git_inspection_errors_do_not_echo_configuration_or_home_paths() { + let fixture = Fixture::new(); + assert!(Command::new("git") + .env_clear() + .env("PATH", std::env::var_os("PATH").unwrap()) + .args(["init", "-q"]) + .current_dir(fixture.work.path()) + .env("HOME", fixture.home.path()) + .env("GIT_CONFIG_NOSYSTEM", "1") + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .status() + .unwrap() + .success()); + fixture.ok(&["init", "--view", "main"]); + std::fs::write( + fixture.work.path().join(".git/config"), + "[core]\n bare = SYNTHETIC_GIT_SECRET\n", + ) + .unwrap(); + let text = fixture.ok(&["diagnostics"]); + let json = fixture.ok(&["diagnostics", "--json"]); + let report: Value = serde_json::from_str(&json).unwrap(); + assert_eq!(report["git_shim"]["hooks"]["status"], "unreadable"); + assert!(report["git_shim"]["hooks"]["reason"] + .as_str() + .unwrap() + .contains("Git")); + for output in [&text, &json] { + assert!( + !output.contains("SYNTHETIC_GIT_SECRET"), + "Git configuration values must not reach diagnostics" + ); + fixture.assert_home_redacted(output); + } +} + +#[test] +fn plugin_file_presence_alone_does_not_prove_enablement() { + let fixture = Fixture::new(); + let path = fixture + .home + .path() + .join(".config/opencode/plugins/atomic-hooks.ts"); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, "// not an active Atomic hook\n").unwrap(); + let report = fixture.json(); + assert_eq!( + find(&report["agents"], "name", "opencode")["enabled"], + "unknown" + ); +} + +#[test] +fn unreadable_receipt_and_manifest_are_unknown_with_safe_reasons() { + let fixture = Fixture::new(); + let receipt = fixture + .home + .path() + .join(".atomic/integrations/claude-code/receipt.json"); + let manifest = fixture + .home + .path() + .join(".atomic/integrations/atomic-skills/repo/atomic-integration.toml"); + std::fs::create_dir_all(receipt).unwrap(); + std::fs::create_dir_all(manifest).unwrap(); + let text = fixture.ok(&["diagnostics"]); + let json = fixture.ok(&["diagnostics", "--json"]); + let report: Value = serde_json::from_str(&json).unwrap(); + let integration = find(&report["integrations"]["packages"], "agent", "claude-code"); + assert_eq!(integration["status"], "unreadable"); + assert!(integration["reason"].as_str().unwrap().contains("receipt")); + assert_eq!( + find(&report["agents"], "name", "claude-code")["enabled"], + "unknown" + ); + assert_eq!(report["skills"]["package"]["status"], "unreadable"); + assert!(report["skills"]["package"]["reason"] + .as_str() + .unwrap() + .contains("manifest")); + fixture.assert_home_redacted(&text); + fixture.assert_home_redacted(&json); +} + +#[test] +fn malformed_claude_settings_are_unknown_with_and_without_a_receipt() { + for receipt in [false, true] { + let fixture = Fixture::new(); + if receipt { + fixture.install_integration("claude-code", "1.0.0"); + } + let settings = fixture.home.path().join(".claude/settings.json"); + std::fs::create_dir_all(settings.parent().unwrap()).unwrap(); + std::fs::write(&settings, "{ SYNTHETIC_SETTINGS_SECRET").unwrap(); + let report = fixture.json(); + let claude = find(&report["agents"], "name", "claude-code"); + assert_eq!(claude["enabled"], "unknown", "receipt={receipt}: {claude}"); + assert!(!claude["evidence"].as_array().unwrap().is_empty()); + let text = fixture.ok(&["diagnostics"]); + assert!(text.contains("Claude Code (claude-code): unknown")); + assert!(text.contains("settings could not be parsed")); + assert!(!format!("{report}{text}").contains("SYNTHETIC_SETTINGS_SECRET")); + } +} + +#[test] +fn unreadable_workspace_and_home_settings_remain_unknown() { + for workspace in [false, true] { + let fixture = Fixture::new(); + if workspace { + fixture.ok(&["init", "--view", "main"]); + } + let base = if workspace { + fixture.work.path() + } else { + fixture.home.path() + }; + std::fs::create_dir_all(base.join(".claude/settings.json")).unwrap(); + let report = fixture.json(); + let claude = find(&report["agents"], "name", "claude-code"); + assert_eq!(claude["enabled"], "unknown"); + assert!(claude["evidence"].to_string().contains("could not be read")); + } +} + +#[test] +fn malformed_builtin_hook_formats_without_receipts_are_unknown() { + let fixture = Fixture::new(); + for (name, relative) in [ + ("gemini-cli", ".gemini/settings.json"), + ("codex", ".codex/hooks.json"), + ] { + let path = fixture.home.path().join(relative); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, "{ bad JSON SYNTHETIC_SETTINGS_SECRET").unwrap(); + let report = fixture.json(); + let agent = find(&report["agents"], "name", name); + assert_eq!(agent["enabled"], "unknown", "{name}: {agent}"); + assert!(!agent.to_string().contains("SYNTHETIC_SETTINGS_SECRET")); + } +} + +#[test] +fn conflicting_or_unreadable_scopes_never_prove_enabled() { + let fixture = Fixture::new(); + fixture.ok(&["init", "--view", "main"]); + fixture.install_integration("claude-code", "1.0.0"); + let path = fixture.work.path().join(".claude/settings.local.json"); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + for body in [ + r#"{"disableAllHooks":true}"#, + r#"{"hooks":{"Stop":[{"disabled":true,"hooks":[{"type":"command","command":"atomic agent hooks claude-code stop"}]}]}}"#, + "{ malformed", + ] { + std::fs::write(&path, body).unwrap(); + let report = fixture.json(); + assert_eq!( + find(&report["agents"], "name", "claude-code")["enabled"], + "unknown", + "{body}" + ); + } + std::fs::write(&path, r#"{"hooks":{}}"#).unwrap(); + assert_eq!( + find(&fixture.json()["agents"], "name", "claude-code")["enabled"], + "yes" + ); +} + +#[test] +fn receipt_cannot_make_an_unloaded_settings_file_active() { + let fixture = Fixture::new(); + fixture.install_integration("claude-code", "1.0.0"); + let actual = fixture.home.path().join(".claude/settings.json"); + let other = fixture.home.path().join("SYNTHETIC_RECEIPT_PATH.json"); + std::fs::copy(&actual, &other).unwrap(); + std::fs::write(&actual, r#"{"hooks":{}}"#).unwrap(); + let receipt = fixture + .home + .path() + .join(".atomic/integrations/claude-code/receipt.json"); + let mut data: Value = serde_json::from_slice(&std::fs::read(&receipt).unwrap()).unwrap(); + data["settings"][0]["target"] = other.to_string_lossy().into_owned().into(); + std::fs::write(receipt, data.to_string()).unwrap(); + let report = fixture.json(); + assert_eq!( + find(&report["agents"], "name", "claude-code")["enabled"], + "unknown" + ); + assert!(!format!("{report}{}", fixture.ok(&["diagnostics"])).contains("SYNTHETIC_RECEIPT_PATH")); +} + +#[cfg(unix)] +#[test] +fn inaccessible_settings_permissions_are_unknown_when_enforced() { + use std::os::unix::fs::PermissionsExt; + let fixture = Fixture::new(); + let path = fixture.home.path().join(".claude/settings.json"); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, r#"{"hooks":{}}"#).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o000)).unwrap(); + if std::fs::read(&path).is_err() { + assert_eq!( + find(&fixture.json()["agents"], "name", "claude-code")["enabled"], + "unknown" + ); + } + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).unwrap(); +} + +#[cfg(unix)] +#[test] +fn dangling_settings_symlink_is_not_treated_as_missing() { + let fixture = Fixture::new(); + let path = fixture.home.path().join(".claude/settings.json"); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::os::unix::fs::symlink(fixture.home.path().join("missing"), path).unwrap(); + let report = fixture.json(); + assert_eq!( + find(&report["agents"], "name", "claude-code")["enabled"], + "unknown" + ); +} + +#[cfg(unix)] +#[test] +fn dangling_workspace_marker_keeps_discovery_unknown() { + let fixture = Fixture::new(); + std::os::unix::fs::symlink( + fixture.work.path().join("SYNTHETIC_MISSING_TARGET"), + fixture.work.path().join(".atomic-sandbox"), + ) + .unwrap(); + let report = fixture.json(); + assert_eq!(report["workspace"]["status"], "unreadable"); + assert_eq!( + find(&report["agents"], "name", "claude-code")["enabled"], + "unknown" + ); + assert!( + !format!("{report}{}", fixture.ok(&["diagnostics"])).contains("SYNTHETIC_MISSING_TARGET") + ); +} + +#[test] +fn linked_git_without_atomic_is_not_a_workspace() { + let fixture = Fixture::new(); + fixture.linked_git_worktree(false); + let report = fixture.json(); + assert_eq!(report["workspace"]["status"], "not_found"); + assert_eq!( + find(&report["agents"], "name", "claude-code")["enabled"], + "no" + ); + let text = fixture.ok(&["diagnostics"]); + assert!(text + .lines() + .any(|line| line.contains("Not enabled") && line.contains("claude-code"))); +} + +#[test] +fn linked_atomic_workspace_finds_active_workspace_hooks() { + let fixture = Fixture::new(); + fixture.linked_git_worktree(true); + let settings = fixture.work.path().join(".claude/settings.json"); + std::fs::create_dir_all(settings.parent().unwrap()).unwrap(); + std::fs::write(settings, r#"{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"atomic agent hooks claude-code stop"}]}]}}"#).unwrap(); + let report = fixture.json(); + assert_eq!(report["workspace"]["status"], "found"); + assert_eq!( + find(&report["agents"], "name", "claude-code")["enabled"], + "yes" + ); + assert!(fixture + .ok(&["diagnostics"]) + .contains("Claude Code (claude-code): yes")); +} + +#[test] +fn broken_linked_git_administration_makes_workspace_unknown() { + let fixture = Fixture::new(); + let git_dir = fixture.linked_git_worktree(false); + std::fs::write(git_dir.join("commondir"), "SYNTHETIC_INVALID_COMMONDIR\n").unwrap(); + let pointer = std::fs::read(fixture.work.path().join(".git")).unwrap(); + let settings = fixture.work.path().join(".claude/settings.json"); + std::fs::create_dir_all(settings.parent().unwrap()).unwrap(); + std::fs::write(settings, r#"{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"atomic agent hooks claude-code stop"}]}]}}"#).unwrap(); + let json = fixture.ok(&["diagnostics", "--json"]); + let report: Value = serde_json::from_str(&json).unwrap(); + assert_eq!(report["workspace"]["status"], "unreadable"); + assert_eq!( + find(&report["agents"], "name", "claude-code")["enabled"], + "unknown" + ); + let text = fixture.ok(&["diagnostics"]); + assert!(text.contains("Claude Code (claude-code): unknown")); + assert!(!format!("{text}{json}").contains("SYNTHETIC_INVALID_COMMONDIR")); + fixture.assert_home_redacted(&text); + fixture.assert_home_redacted(&json); + assert_eq!( + std::fs::read(fixture.work.path().join(".git")).unwrap(), + pointer + ); + assert_eq!( + std::fs::read(git_dir.join("commondir")).unwrap(), + b"SYNTHETIC_INVALID_COMMONDIR\n" + ); +} + +#[test] +fn valid_atomic_parent_wins_over_broken_nested_git() { + let fixture = Fixture::new(); + fixture.ok(&["init", "--view", "main"]); + let nested = fixture.work.path().join("nested"); + std::fs::create_dir(&nested).unwrap(); + std::fs::write(nested.join(".git"), "gitdir: SYNTHETIC_BROKEN_GITDIR\n").unwrap(); + let settings = fixture.work.path().join(".claude/settings.json"); + std::fs::create_dir_all(settings.parent().unwrap()).unwrap(); + std::fs::write(settings, r#"{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"atomic agent hooks claude-code stop"}]}]}}"#).unwrap(); + let json = fixture.ok_at(&nested, &["diagnostics", "--json"]); + let report: Value = serde_json::from_str(&json).unwrap(); + assert_eq!(report["workspace"]["status"], "found"); + assert_eq!( + find(&report["agents"], "name", "claude-code")["enabled"], + "yes" + ); + let text = fixture.ok_at(&nested, &["diagnostics"]); + assert!(text.contains("Claude Code (claude-code): yes")); + assert!(!format!("{text}{json}").contains("SYNTHETIC_BROKEN_GITDIR")); + + let nested_link = fixture.work.path().join("nested-link"); + std::fs::create_dir(&nested_link).unwrap(); + std::os::unix::fs::symlink("SYNTHETIC_MISSING_GITDIR", nested_link.join(".git")).unwrap(); + let json = fixture.ok_at(&nested_link, &["diagnostics", "--json"]); + let report: Value = serde_json::from_str(&json).unwrap(); + assert_eq!(report["workspace"]["status"], "found"); + assert_eq!( + find(&report["agents"], "name", "claude-code")["enabled"], + "yes" + ); + assert!(!json.contains("SYNTHETIC_MISSING_GITDIR")); +} + fn find<'v>(list: &'v Value, key: &str, name: &str) -> &'v Value { list.as_array() .unwrap() @@ -151,6 +812,10 @@ fn installed_integration_and_enabled_agent_are_reported_separately_and_redacted( !everything.contains("secret"), "credentials never reach the report" ); + assert!( + !everything.contains("SYNTHETIC_"), + "query and fragment are removed" + ); let home = fixture.home.path().display().to_string(); assert!(!everything.contains(&home), "home is shown as ~"); } @@ -159,8 +824,13 @@ fn installed_integration_and_enabled_agent_are_reported_separately_and_redacted( fn inside_a_git_backed_workspace_the_shim_is_reported_and_nothing_changes() { let fixture = Fixture::new(); assert!(Command::new("git") + .env_clear() + .env("PATH", std::env::var_os("PATH").unwrap()) .args(["init", "-q"]) .current_dir(fixture.work.path()) + .env("HOME", fixture.home.path()) + .env("GIT_CONFIG_NOSYSTEM", "1") + .env("GIT_CONFIG_GLOBAL", "/dev/null") .status() .unwrap() .success()); diff --git a/docs/diagnostics.md b/docs/diagnostics.md index 666ff1f1..c9c11eb4 100644 --- a/docs/diagnostics.md +++ b/docs/diagnostics.md @@ -22,7 +22,7 @@ invocation appends to. | Workspace | The same upward search other commands use | | Agent integrations (installed packages) | Install receipts in `~/.atomic/integrations//receipt.json`: package version, the Atomic version that installed it, install time, source, and whether each recorded file is unchanged, modified, or missing | | Skills | The `atomic-skills` package manifest cached by the last `atomic agent enable`, plus each skill file listed in an integration receipt with its own `version:` frontmatter | -| Enabled agents | Whether Atomic hooks are live in each agent's configuration, with the evidence | +| Enabled agents | Whether supported settings contain recognizable active Atomic hooks, with the evidence and inspection limitations | | Git shim | `[git.shim] enabled` in `.atomic/config.toml`, plus the state of each Atomic hook dispatcher (as `atomic git hooks status` reports them) | **Installed is not the same as enabled.** An integration is *installed* when it @@ -31,25 +31,33 @@ its live configuration. Hooks can exist without a receipt (built-in hooks), and receipt survives hooks removed by hand. Each agent is reported as `yes`, `no`, or `unknown`: -- `yes`: the agent's adapter finds Atomic hooks (the check `atomic agent - status` uses), or a settings file named in the receipt still contains the - integration's hook command. -- `no`: none of that evidence was found. -- `unknown`: the receipt or a settings file cannot be read, or the package - installs its hooks somewhere Atomic cannot inspect. +- `yes`: a recognizable command hook occurs in an inspected configuration, + and no inspected scope is unreadable or conflicts with it. +- `no`: supported, inspectable settings contain no active Atomic hooks, or + those settings are absent. +- `unknown`: settings or required locations cannot be inspected, a receipt is + unreadable without independent positive evidence, scopes conflict, or the + agent's active hook/plugin format cannot be verified. -Every unavailable value is reported as unknown or not found, with a reason. -Values are never inferred. +These are observations of supported local configuration, not a guarantee that +an agent actually runs a hook. See the inspection limits below. ## Privacy -The report contains booleans, versions, timestamps, and paths. URL credentials, -query strings, and fragments are removed from integration sources. Paths under -the home directory are shown as `~/…`. The report never includes file contents, -tokens, transcripts, or other configuration values. +The report contains versions, timestamps, paths, integration sources, and +names read from local metadata. URL credentials, query strings, and fragments +are removed from URL-shaped integration sources. Paths under a known home +directory are shown as `~/…`. Error reasons use content-free summaries rather +than raw parser or operating-system errors. Review the report before sharing: +paths, names, versions, and other metadata can themselves contain sensitive +information, and arbitrary non-URL source strings are not credential scrubbed. ## Limits +- **Linked Git worktrees:** if ordinary workspace discovery finds no Atomic + workspace, diagnostics invokes local `git rev-parse` with optional locks + disabled to inspect a linked worktree. If Git or its administrative paths + cannot be inspected, workspace-dependent results are `unknown`. - **Agent application versions** (for example, the Claude Code version) are not collected. Atomic has no record of them, and detecting them would mean running third-party programs. The report says so explicitly. @@ -59,9 +67,15 @@ tokens, transcripts, or other configuration values. An install that used `--from-skills` leaves no cache. - **Flat-layout skills** (`.md`, as used for Cline and agy) are recognised only when the skills package manifest is cached. -- **Enabled** follows each adapter's own definition of "installed". For a few - adapters (for example Hermes and Sherpa), that check finds the agent's - configuration rather than specific hook entries. +- **Enabled** inspects recognized JSON command-hook entries for Claude Code, + Gemini CLI, and Codex. It checks their home and workspace settings, plus + Claude's workspace-local settings, and supported receipt settings at those + locations. Other agents and unsupported receipt locations, keys, commands, + or hook/plugin formats are `unknown` rather than inferred from file presence + or incidental text. Unreadable or malformed settings are `unknown`; a + conflicting or uninspectable scope can make an otherwise positive observation + `unknown`. Other settings sources, managed policies, runtime conditions and + future agent formats may affect actual execution and are not fully modeled. ## Was a record made by an agent? From 42116de5fb5d1b3dcd705fed55001f5268ac19c7 Mon Sep 17 00:00:00 2001 From: Bradley Hilton Date: Thu, 29 Oct 2026 05:32:30 +0100 Subject: [PATCH 2/2] feat: report hook activity and skill metadata in diagnostics --- Cargo.lock | 21 ++ atomic-cli/Cargo.toml | 2 + .../src/commands/diagnostics/collect.rs | 270 ++++++++++++++++-- atomic-cli/src/commands/diagnostics/render.rs | 47 ++- .../tests/it/diagnostics_integration_test.rs | 203 ++++++++++++- docs/diagnostics.md | 18 +- 6 files changed, 519 insertions(+), 42 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1bb82edd..3e1e2d6d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -296,9 +296,11 @@ dependencies = [ "prost-types", "ratatui", "rayon", + "redb 4.4.0", "reqwest", "serde", "serde_json", + "serde_yaml_ng", "serial_test", "tempfile", "thiserror 1.0.69", @@ -4079,6 +4081,19 @@ dependencies = [ "serde", ] +[[package]] +name = "serde_yaml_ng" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4db627b98b36d4203a7b458cf3573730f2bb591b28871d916dfa9efabfd41f" +dependencies = [ + "indexmap 2.14.2", + "itoa", + "ryu", + "serde", + "unsafe-libyaml", +] + [[package]] name = "serial_test" version = "3.5.0" @@ -5050,6 +5065,12 @@ dependencies = [ "ctutils", ] +[[package]] +name = "unsafe-libyaml" +version = "0.2.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861" + [[package]] name = "untrusted" version = "0.9.0" diff --git a/atomic-cli/Cargo.toml b/atomic-cli/Cargo.toml index 32d1317c..4d923839 100644 --- a/atomic-cli/Cargo.toml +++ b/atomic-cli/Cargo.toml @@ -91,7 +91,9 @@ uuid = { version = "1.0", features = ["serde", "v4"] } # Utilities serde = { workspace = true } serde_json = { workspace = true } +serde_yaml_ng = "0.10" toml = { workspace = true } +redb = { workspace = true } bytes = { workspace = true } fs2 = "0.4" url = { workspace = true } diff --git a/atomic-cli/src/commands/diagnostics/collect.rs b/atomic-cli/src/commands/diagnostics/collect.rs index 892c6c26..397c3573 100644 --- a/atomic-cli/src/commands/diagnostics/collect.rs +++ b/atomic-cli/src/commands/diagnostics/collect.rs @@ -7,6 +7,7 @@ //! the network. A value that cannot be read is reported with the reason, //! never filled in by inference. +use std::collections::BTreeMap; use std::fmt; use std::io::ErrorKind; use std::path::{Path, PathBuf}; @@ -102,6 +103,7 @@ pub(crate) struct InstalledIntegration { /// The Atomic version that performed the install. pub installed_with: String, pub installed_at: String, + pub last_fired: HookActivity, /// `registry`, `local`, or `url`. pub source_kind: &'static str, /// Where the package came from, with any URL credentials removed. @@ -109,6 +111,15 @@ pub(crate) struct InstalledIntegration { pub files: FileCounts, } +/// The latest recorded dispatch in this workspace, not a machine-wide history. +#[derive(Debug, Clone, Serialize, PartialEq, Eq)] +#[serde(tag = "status", rename_all = "snake_case")] +pub(crate) enum HookActivity { + Observed { at: String }, + NotObserved, + Unavailable { reason: &'static str }, +} + /// The receipt's files compared against what is on disk now. #[derive(Debug, Default, Serialize, PartialEq, Eq)] pub(crate) struct FileCounts { @@ -149,9 +160,46 @@ pub(crate) struct InstalledSkill { pub name: String, pub path: String, pub state: FileState, - /// The skill file's own `version:` frontmatter; `null` when it declares - /// none or cannot be read. + /// Nested metadata version, or the legacy top-level version when present. pub version: Option, + pub updated_at: Option, + pub metadata_status: SkillMetadataStatus, + pub missing_metadata: Vec<&'static str>, +} + +#[derive(Clone, Copy, Debug, Serialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub(crate) enum SkillMetadataStatus { + Complete, + Incomplete, + Invalid, + Unavailable, +} + +#[derive(Debug, PartialEq, Eq)] +struct SkillMetadata { + version: Option, + updated_at: Option, + status: SkillMetadataStatus, + missing: Vec<&'static str>, +} + +impl SkillMetadata { + fn unavailable() -> Self { + Self { + version: None, + updated_at: None, + status: SkillMetadataStatus::Unavailable, + missing: Vec::new(), + } + } + + fn invalid() -> Self { + Self { + status: SkillMetadataStatus::Invalid, + ..Self::unavailable() + } + } } #[derive(Clone, Copy, Debug, Serialize, PartialEq, Eq)] @@ -537,6 +585,12 @@ pub(crate) fn collect_from( _ => None, }; + let hook_activity = match &sources.workspace { + Ok(Some(root)) => read_hook_activity(root), + Ok(None) => Err("not inside an Atomic workspace"), + Err(_) => Err("workspace cannot be determined"), + }; + let mut installed_skills = Vec::new(); let integrations = receipts .iter() @@ -560,16 +614,20 @@ pub(crate) fn collect_from( FileState::Unreadable => files.unreadable += 1, } if let Some(name) = skill_name(&file.dst, declared) { + let metadata = match state { + FileState::Present | FileState::Modified => { + skill_metadata(&file.dst) + } + _ => SkillMetadata::unavailable(), + }; installed_skills.push(InstalledSkill { agent: agent.clone(), name, path: display_path(&file.dst, home), - version: match state { - FileState::Present | FileState::Modified => { - skill_version(&file.dst) - } - _ => None, - }, + version: metadata.version, + updated_at: metadata.updated_at, + metadata_status: metadata.status, + missing_metadata: metadata.missing, state, }); } @@ -579,6 +637,16 @@ pub(crate) fn collect_from( version: receipt.version.clone(), installed_with: receipt.cli_version.clone(), installed_at: receipt.installed_at.clone(), + last_fired: match &hook_activity { + Ok(events) => { + events.get(agent).map_or(HookActivity::NotObserved, |at| { + HookActivity::Observed { + at: at.to_rfc3339(), + } + }) + } + Err(reason) => HookActivity::Unavailable { reason }, + }, source_kind, source, files, @@ -730,6 +798,54 @@ pub(crate) fn collect_from( } } +/// Read immutable observations without starting the service or opening the +/// repository for writes. Any unreadable source makes the latest time unknown. +fn read_hook_activity( + root: &Path, +) -> Result>, &'static str> { + use atomic_core::pristine::tables::SESSION_LOG; + use redb::{ReadableDatabase, ReadableTable}; + + let dot = atomic_repository::Repository::canonical_dot_dir(root) + .map_err(|_| "hook history location cannot be resolved")?; + let database = redb::ReadOnlyDatabase::open(dot.join("atomic.redb")) + .map_err(|_| "hook history cannot be read or is in use")?; + let txn = database + .begin_read() + .map_err(|_| "hook history cannot be read")?; + let mut times = BTreeMap::new(); + let mut observe = |event: atomic_agent::hook_log::SessionLogEvent| -> Result<(), &'static str> { + let at = chrono::DateTime::parse_from_rfc3339(&event.at) + .map_err(|_| "hook history contains an invalid timestamp")? + .with_timezone(&chrono::Utc); + times + .entry(event.agent) + .and_modify(|last: &mut chrono::DateTime| { + *last = (*last).max(at); + }) + .or_insert(at); + Ok(()) + }; + match txn.open_table(SESSION_LOG) { + Ok(table) => { + for entry in table.iter().map_err(|_| "hook history cannot be read")? { + let (_, value) = entry.map_err(|_| "hook history cannot be read")?; + let event = serde_json::from_slice(value.value()) + .map_err(|_| "hook history contains an invalid event")?; + observe(event)?; + } + } + Err(redb::TableError::TableDoesNotExist(_)) => {} + Err(_) => return Err("hook history cannot be read"), + } + for (_, event) in + atomic_agent::hook_log::pending(root).map_err(|_| "pending hook history cannot be read")? + { + observe(event)?; + } + Ok(times) +} + // Receipts and files enum ReceiptLookup { @@ -983,22 +1099,92 @@ fn skill_name(dst: &Path, declared: Option<&[String]>) -> Option { .then(|| stem.to_string()) } -/// The `version:` key of a skill file's YAML frontmatter, when it has one. -fn skill_version(path: &Path) -> Option { - let text = std::fs::read_to_string(path).ok()?; - frontmatter_version(&text) +fn skill_metadata(path: &Path) -> SkillMetadata { + match std::fs::read_to_string(path) { + Ok(text) => frontmatter_metadata(&text), + Err(_) => SkillMetadata::unavailable(), + } } -fn frontmatter_version(text: &str) -> Option { +fn frontmatter_metadata(text: &str) -> SkillMetadata { + use serde_yaml_ng::Value; + + fn key(name: &str) -> Value { + Value::String(name.to_string()) + } + fn string(value: Option<&Value>) -> Result, ()> { + match value { + None | Some(Value::Null) => Ok(None), + Some(Value::String(value)) if value.trim().is_empty() => Ok(None), + Some(Value::String(value)) if !value.chars().any(char::is_control) => { + Ok(Some(value.trim().to_string())) + } + _ => Err(()), + } + } + let incomplete = || SkillMetadata { + version: None, + updated_at: None, + status: SkillMetadataStatus::Incomplete, + missing: vec!["metadata.version", "metadata.updatedAt"], + }; let mut lines = text.lines(); - if lines.next()?.trim_end() != "---" { - return None; - } - lines - .take_while(|line| line.trim_end() != "---") - .find_map(|line| line.strip_prefix("version:")) - .map(|value| value.trim().trim_matches(['"', '\'']).to_string()) - .filter(|value| !value.is_empty()) + if lines.next().map(str::trim_end) != Some("---") { + return incomplete(); + } + let mut yaml = String::new(); + let mut closed = false; + for line in lines { + if line.trim_end() == "---" { + closed = true; + break; + } + yaml.push_str(line); + yaml.push('\n'); + } + if !closed { + return SkillMetadata::invalid(); + } + let root = match serde_yaml_ng::from_str(&yaml) { + Ok(Value::Null) => return incomplete(), + Ok(Value::Mapping(root)) => root, + _ => return SkillMetadata::invalid(), + }; + let legacy_version = string(root.get(key("version"))).unwrap_or(None); + let metadata = match root.get(key("metadata")) { + None | Some(Value::Null) => { + return SkillMetadata { + version: legacy_version, + ..incomplete() + }; + } + Some(Value::Mapping(metadata)) => metadata, + _ => return SkillMetadata::invalid(), + }; + let (version, updated_at) = match ( + string(metadata.get(key("version"))), + string(metadata.get(key("updatedAt"))), + ) { + (Ok(version), Ok(updated_at)) => (version, updated_at), + _ => return SkillMetadata::invalid(), + }; + let mut missing = Vec::new(); + if version.is_none() { + missing.push("metadata.version"); + } + if updated_at.is_none() { + missing.push("metadata.updatedAt"); + } + SkillMetadata { + version: version.or(legacy_version), + updated_at, + status: if missing.is_empty() { + SkillMetadataStatus::Complete + } else { + SkillMetadataStatus::Incomplete + }, + missing, + } } // Agents @@ -1529,18 +1715,44 @@ mod tests { } #[test] - fn frontmatter_version_is_read_only_from_frontmatter() { + fn skill_metadata_reads_nested_yaml_only_from_frontmatter() { + let nested = frontmatter_metadata("---\nname: atomic-vault\nmetadata:\n version: \"1.0.0\"\n updatedAt: \"2026-10-28T18:18:12Z\"\n---\n"); + assert_eq!(nested.version.as_deref(), Some("1.0.0")); + assert_eq!(nested.updated_at.as_deref(), Some("2026-10-28T18:18:12Z")); + assert_eq!(nested.status, SkillMetadataStatus::Complete); + assert!(nested.missing.is_empty()); + + let flow = frontmatter_metadata( + "---\nmetadata: {updatedAt: '2026-10-29', version: '2.1.0'}\n---\n", + ); + assert_eq!(flow.version.as_deref(), Some("2.1.0")); + assert_eq!(flow.updated_at.as_deref(), Some("2026-10-29")); + assert_eq!(flow.status, SkillMetadataStatus::Complete); + + let partial = + frontmatter_metadata("---\nmetadata:\n updatedAt: '2026-10-29'\n---\nversion: 9\n"); + assert_eq!(partial.version, None); + assert_eq!(partial.missing, ["metadata.version"]); + assert_eq!(partial.updated_at.as_deref(), Some("2026-10-29")); + let legacy = frontmatter_metadata("---\nversion: '2.0.0'\nother: {version: 'wrong'}\n---\nmetadata:\n version: 'wrong'\n"); + assert_eq!(legacy.version.as_deref(), Some("2.0.0")); + assert_eq!(legacy.missing, ["metadata.version", "metadata.updatedAt"]); + assert_eq!( + frontmatter_metadata("version: 9\n").status, + SkillMetadataStatus::Incomplete + ); + assert_eq!( + frontmatter_metadata("---\nmetadata: [broken\n---\n").status, + SkillMetadataStatus::Invalid + ); assert_eq!( - frontmatter_version("---\nversion: 1.2.3\n---\n").as_deref(), - Some("1.2.3") + frontmatter_metadata("---\nmetadata:\n version: x\n").status, + SkillMetadataStatus::Invalid ); assert_eq!( - frontmatter_version("---\nversion: '1.2.3'\n---\n").as_deref(), - Some("1.2.3") + frontmatter_metadata("---\nmetadata: {version: [1, 2]}\n---\n").status, + SkillMetadataStatus::Invalid ); - assert_eq!(frontmatter_version("---\nname: x\n---\nversion: 9\n"), None); - assert_eq!(frontmatter_version("version: 9\n"), None); - assert_eq!(frontmatter_version("---\nversion:\n---\n"), None); } fn settings(path: &str, hooks: HookPresence) -> SettingsProbe { diff --git a/atomic-cli/src/commands/diagnostics/render.rs b/atomic-cli/src/commands/diagnostics/render.rs index 20b027c8..19507b92 100644 --- a/atomic-cli/src/commands/diagnostics/render.rs +++ b/atomic-cli/src/commands/diagnostics/render.rs @@ -7,8 +7,8 @@ use std::fmt::Write; use super::collect::{ - AgentState, Enabled, FileCounts, FileState, GitHooks, IntegrationState, Report, ShimStatus, - SkillsPackage, Workspace, + AgentState, Enabled, FileCounts, FileState, GitHooks, HookActivity, IntegrationState, Report, + ShimStatus, SkillMetadataStatus, SkillsPackage, Workspace, }; /// Width of the label column. @@ -80,6 +80,12 @@ fn render_integrations(o: &mut String, report: &Report) { installed.installed_at, installed.installed_with ), ); + let last_fired = match &installed.last_fired { + HookActivity::Observed { at } => format!("{at} (current repository)"), + HookActivity::NotObserved => "not observed in this repository".to_string(), + HookActivity::Unavailable { reason } => format!("unknown — {reason}"), + }; + field(o, " Last fired", &last_fired); field( o, " Source", @@ -129,19 +135,37 @@ fn render_skills(o: &mut String, report: &Report) { field(o, "Installed", "none recorded in integration receipts"); } for skill in &report.skills.installed { - let version = skill - .version - .as_deref() - .map_or_else(|| "no version declared".to_string(), |v| format!("v{v}")); + let version = skill.version.as_deref().map_or_else( + || match skill.metadata_status { + SkillMetadataStatus::Incomplete => "no version declared".to_string(), + _ => "version unknown".to_string(), + }, + |v| format!("v{v}"), + ); let state = match skill.state { FileState::Present => "", FileState::Modified => ", modified since install", FileState::Missing => ", missing", FileState::Unreadable => ", unreadable", }; + let metadata = match skill.metadata_status { + SkillMetadataStatus::Complete => format!( + ", updated {}", + skill.updated_at.as_deref().unwrap_or("unknown") + ), + SkillMetadataStatus::Incomplete => format!( + ", missing {} (older or unversioned copy)", + skill.missing_metadata.join(", ") + ), + SkillMetadataStatus::Invalid => ", invalid skill metadata".to_string(), + SkillMetadataStatus::Unavailable => ", skill metadata unavailable".to_string(), + }; line( o, - &format!(" {} for {} — {version}{state}", skill.name, skill.agent), + &format!( + " {} for {} — {version}{metadata}{state}", + skill.name, skill.agent + ), ); } blank(o); @@ -257,6 +281,9 @@ mod tests { version: "1.4.0".to_string(), installed_with: "0.19.0".to_string(), installed_at: "2026-10-01T12:00:00+00:00".to_string(), + last_fired: HookActivity::Observed { + at: "2026-10-28T11:00:00+00:00".to_string(), + }, source_kind: "registry", source: "https://example.atomic.storage/pkg".to_string(), files: FileCounts { @@ -289,6 +316,9 @@ mod tests { path: "~/.claude/skills/atomic-vault/SKILL.md".to_string(), state: FileState::Modified, version: None, + updated_at: None, + metadata_status: SkillMetadataStatus::Incomplete, + missing_metadata: vec!["metadata.version", "metadata.updatedAt"], }], }, agents: vec![ @@ -344,13 +374,14 @@ Agent integrations (installed packages) Claude Code (claude-code) Version: 1.4.0 Installed: 2026-10-01T12:00:00+00:00 with atomic 0.19.0 + Last fired: 2026-10-28T11:00:00+00:00 (current repository) Source: https://example.atomic.storage/pkg (registry) Files: 3 recorded, 2 unchanged, 1 missing Not installed: cline, codex Skills Skills package: unknown — no synced atomic-skills package - atomic-vault for claude-code — no version declared, modified since install + atomic-vault for claude-code — no version declared, missing metadata.version, metadata.updatedAt (older or unversioned copy), modified since install Enabled agents (Atomic hooks active) Claude Code (claude-code): yes diff --git a/atomic-cli/tests/it/diagnostics_integration_test.rs b/atomic-cli/tests/it/diagnostics_integration_test.rs index d967f326..0d05084c 100644 --- a/atomic-cli/tests/it/diagnostics_integration_test.rs +++ b/atomic-cli/tests/it/diagnostics_integration_test.rs @@ -1,8 +1,9 @@ //! `atomic diagnostics` end to end: a hermetic home, the real binary. #![cfg(not(windows))] +use std::io::Write; use std::path::Path; -use std::process::{Command, Output}; +use std::process::{Command, Output, Stdio}; use std::sync::OnceLock; use serde_json::Value; @@ -337,6 +338,206 @@ fn malformed_repository_config_never_discloses_values_in_either_renderer() { ); } +#[test] +fn installed_skill_metadata_and_missing_fields_are_reported() { + let fixture = Fixture::new(); + fixture.install_integration("claude-code", "1.4.0"); + let skill = fixture + .home + .path() + .join(".claude/skills/atomic-vault/SKILL.md"); + std::fs::write(&skill, "---\nname: atomic-vault\nmetadata:\n version: \"1.0.0\"\n updatedAt: \"2026-10-28T18:18:12Z\"\n---\nbody\n").unwrap(); + let report = fixture.json(); + let installed = find(&report["skills"]["installed"], "name", "atomic-vault"); + assert_eq!(installed["version"], "1.0.0"); + assert_eq!(installed["updated_at"], "2026-10-28T18:18:12Z"); + assert_eq!(installed["metadata_status"], "complete"); + assert_eq!(installed["missing_metadata"], serde_json::json!([])); + let text = fixture.ok(&["diagnostics"]); + assert!(text.contains("v1.0.0, updated 2026-10-28T18:18:12Z")); + + std::fs::write( + &skill, + "---\nname: atomic-vault\nmetadata:\n version: '1.0.0'\n---\n", + ) + .unwrap(); + let report = fixture.json(); + let installed = find(&report["skills"]["installed"], "name", "atomic-vault"); + assert_eq!(installed["metadata_status"], "incomplete"); + assert_eq!( + installed["missing_metadata"], + serde_json::json!(["metadata.updatedAt"]) + ); + assert!(fixture + .ok(&["diagnostics"]) + .contains("missing metadata.updatedAt")); + + std::fs::write(&skill, "---\nname: atomic-vault\n---\n").unwrap(); + let report = fixture.json(); + let installed = find(&report["skills"]["installed"], "name", "atomic-vault"); + assert_eq!(installed["metadata_status"], "incomplete"); + assert_eq!( + installed["missing_metadata"], + serde_json::json!(["metadata.version", "metadata.updatedAt"]) + ); + assert!(fixture + .ok(&["diagnostics"]) + .contains("older or unversioned copy")); + + std::fs::write(&skill, "---\nmetadata: [SYNTHETIC_PRIVATE_DETAIL\n---\n").unwrap(); + let report = fixture.json(); + let installed = find(&report["skills"]["installed"], "name", "atomic-vault"); + assert_eq!(installed["metadata_status"], "invalid"); + assert!(!report.to_string().contains("SYNTHETIC_PRIVATE_DETAIL")); + let text = fixture.ok(&["diagnostics"]); + assert!(text.contains("invalid skill metadata")); + assert!(!text.contains("SYNTHETIC_PRIVATE_DETAIL")); + + std::fs::remove_file(&skill).unwrap(); + std::fs::create_dir(&skill).unwrap(); + let report = fixture.json(); + let installed = find(&report["skills"]["installed"], "name", "atomic-vault"); + assert_eq!(installed["metadata_status"], "unavailable"); + assert!(fixture + .ok(&["diagnostics"]) + .contains("skill metadata unavailable")); +} + +fn hook_event(agent: &str, at: &str, outcome: &str) -> atomic_agent::hook_log::SessionLogEvent { + atomic_agent::hook_log::SessionLogEvent { + event_id: uuid::Uuid::new_v4().to_string(), + session_id: None, + parent_session_id: None, + agent: agent.to_string(), + display_name: agent.to_string(), + verb: "session-start".to_string(), + outcome: outcome.to_string(), + detail: Some("SYNTHETIC_PRIVATE_DETAIL".to_string()), + at: at.to_string(), + } +} + +#[test] +fn last_fired_uses_repository_history_and_pending_events() { + let fixture = Fixture::new(); + fixture.ok(&["init", "--view", "main"]); + fixture.install_integration("claude-code", "1.4.0"); + { + let store = atomic_repository::redb_change_store::RedbChangeStore::open_existing( + fixture.work.path().join(".atomic/atomic.redb"), + ) + .unwrap(); + store + .append_session_log(&hook_event("claude-code", "2026-10-01T12:00:00Z", "ok")) + .unwrap(); + store + .append_session_log(&hook_event("other-agent", "2026-12-01T12:00:00Z", "ok")) + .unwrap(); + store + .append_session_log(&hook_event( + "claude-code", + "2026-10-02T12:00:00+03:00", + "error", + )) + .unwrap(); + } + atomic_agent::hook_log::spool( + fixture.work.path(), + &hook_event("claude-code", "2026-10-02T11:00:00Z", "error"), + ) + .unwrap(); + let report = fixture.json(); + let integration = find(&report["integrations"]["packages"], "agent", "claude-code"); + assert_eq!(integration["last_fired"]["status"], "observed"); + assert_eq!(integration["last_fired"]["at"], "2026-10-02T11:00:00+00:00"); + let text = fixture.ok(&["diagnostics"]); + assert!(text.contains("Last fired:")); + assert!(text.contains("2026-10-02T11:00:00+00:00 (current repository)")); + assert!(!text.contains("SYNTHETIC_PRIVATE_DETAIL")); + assert!(!report.to_string().contains("SYNTHETIC_PRIVATE_DETAIL")); +} + +#[test] +fn last_fired_distinguishes_missing_and_unavailable_history() { + let fixture = Fixture::new(); + fixture.install_integration("claude-code", "1.4.0"); + let report = fixture.json(); + let integration = find(&report["integrations"]["packages"], "agent", "claude-code"); + assert_eq!(integration["last_fired"]["status"], "unavailable"); + fixture.ok(&["init", "--view", "main"]); + let report = fixture.json(); + let integration = find(&report["integrations"]["packages"], "agent", "claude-code"); + assert_eq!(integration["last_fired"]["status"], "not_observed"); + let pending = fixture.work.path().join(".atomic/hook-log-pending"); + std::fs::create_dir_all(&pending).unwrap(); + std::fs::write(pending.join("bad.json"), "SYNTHETIC_PRIVATE_DETAIL").unwrap(); + let report = fixture.json(); + let integration = find(&report["integrations"]["packages"], "agent", "claude-code"); + assert_eq!(integration["last_fired"]["status"], "unavailable"); + assert!(!report.to_string().contains("SYNTHETIC_PRIVATE_DETAIL")); + let text = fixture.ok(&["diagnostics"]); + assert!(text.contains("Last fired: unknown")); + assert!(!text.contains("SYNTHETIC_PRIVATE_DETAIL")); +} + +#[test] +fn last_fired_is_populated_by_a_real_hook_dispatch() { + let fixture = Fixture::new(); + fixture.ok(&["init", "--view", "main"]); + fixture.install_integration("claude-code", "1.4.0"); + let mut command = Command::new(&fixture.binary); + for (name, _) in std::env::vars_os() { + if name.to_string_lossy().starts_with("ATOMIC_") + || name.to_string_lossy().starts_with("GIT_") + { + command.env_remove(name); + } + } + let mut hook = command + .args([ + "agent", + "hooks", + "claude-code", + "session-start", + "--foreground", + ]) + .current_dir(fixture.work.path()) + .env("HOME", fixture.home.path()) + .env("ATOMIC_HOME", fixture.home.path().join(".atomic")) + .env("ATOMIC_CONFIG_DIR", fixture.home.path().join(".atomic")) + .env("ATOMIC_SERVICE", "local") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + hook.stdin.take().unwrap().write_all(b"{").unwrap(); + assert!(!hook.wait_with_output().unwrap().status.success()); + let report = fixture.json(); + let integration = find(&report["integrations"]["packages"], "agent", "claude-code"); + assert_eq!(integration["last_fired"]["status"], "observed"); + chrono::DateTime::parse_from_rfc3339(integration["last_fired"]["at"].as_str().unwrap()) + .expect("hook dispatch timestamp"); +} + +#[test] +fn last_fired_reports_unknown_when_database_is_in_use() { + let fixture = Fixture::new(); + fixture.ok(&["init", "--view", "main"]); + fixture.install_integration("claude-code", "1.4.0"); + let _held = atomic_repository::redb_change_store::RedbChangeStore::open_existing( + fixture.work.path().join(".atomic/atomic.redb"), + ) + .unwrap(); + let report = fixture.json(); + let integration = find(&report["integrations"]["packages"], "agent", "claude-code"); + assert_eq!(integration["last_fired"]["status"], "unavailable"); + assert!(integration["last_fired"]["reason"] + .as_str() + .unwrap() + .contains("in use")); +} + #[test] fn malformed_receipt_and_manifest_never_disclose_values_in_either_renderer() { let fixture = Fixture::new(); diff --git a/docs/diagnostics.md b/docs/diagnostics.md index c9c11eb4..bed8c4fd 100644 --- a/docs/diagnostics.md +++ b/docs/diagnostics.md @@ -20,8 +20,8 @@ invocation appends to. |---|---| | Atomic version, install source, platform | The running binary (`atomic --version`); install source uses the same detection as `atomic update` | | Workspace | The same upward search other commands use | -| Agent integrations (installed packages) | Install receipts in `~/.atomic/integrations//receipt.json`: package version, the Atomic version that installed it, install time, source, and whether each recorded file is unchanged, modified, or missing | -| Skills | The `atomic-skills` package manifest cached by the last `atomic agent enable`, plus each skill file listed in an integration receipt with its own `version:` frontmatter | +| Agent integrations (installed packages) | Install receipts in `~/.atomic/integrations//receipt.json`, plus last recorded hook dispatch from the current repository's hook log | +| Skills | The cached `atomic-skills` package manifest and each installed skill's `metadata.version` and `metadata.updatedAt` frontmatter | | Enabled agents | Whether supported settings contain recognizable active Atomic hooks, with the evidence and inspection limitations | | Git shim | `[git.shim] enabled` in `.atomic/config.toml`, plus the state of each Atomic hook dispatcher (as `atomic git hooks status` reports them) | @@ -42,6 +42,13 @@ or `unknown`: These are observations of supported local configuration, not a guarantee that an agent actually runs a hook. See the inspection limits below. +The last-fired time includes successful and failed dispatches recorded in the +current repository, including pending events for this working copy. Repositories +and their linked working copies share committed history; other repositories are +not searched. An absent observation does not prove the hook never ran. +If another process holds the repository database for writing, the timestamp is +reported as unknown rather than opening or modifying the database. + ## Privacy The report contains versions, timestamps, paths, integration sources, and @@ -61,8 +68,11 @@ information, and arbitrary non-URL source strings are not credential scrubbed. - **Agent application versions** (for example, the Claude Code version) are not collected. Atomic has no record of them, and detecting them would mean running third-party programs. The report says so explicitly. -- **Skill versions** come from a skill file's `version:` frontmatter when it has - one. The skills package version comes from the local cache. That cache is +- **Skill metadata** comes from each installed skill file's YAML frontmatter: + `metadata.version` and `metadata.updatedAt`. Missing fields are flagged as a + possible older or unversioned copy; unreadable or invalid files are reported + separately. A legacy top-level `version` remains visible but does not satisfy + the nested metadata requirement. The skills package version comes from the local cache. That cache is refreshed on every `atomic agent enable`, so it shows the most recent sync. An install that used `--from-skills` leaves no cache. - **Flat-layout skills** (`.md`, as used for Cline and agy) are recognised