From 3a630702d7f9a08b751ff11228d34063be9d3d6b Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 19:39:10 +0000 Subject: [PATCH 1/2] feat: add read-only `atomic diagnostics` support report Collects the context support otherwise requests over several follow-ups: Atomic version and install source, installed agent integration packages (receipt versions and file drift), installed skills and their versions, which agents have Atomic hooks enabled (with evidence, distinct from installed), and whether the Git shim is enabled. `--json` emits one document. Unknown values are reported with a reason, never inferred. The command writes nothing, needs no network, and works outside a workspace. URL credentials are redacted and home paths shown as `~`. Reuses `atomic update` install detection, integration receipts, agent adapters, `shim_config`, and the git hook dispatcher inspection (now returned as data so `git hooks status` and diagnostics share it). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Q7Qtv2GmBTRRN3Xy1jzx17 --- README.md | 1 + .../src/commands/diagnostics/collect.rs | 1308 +++++++++++++++++ atomic-cli/src/commands/diagnostics/mod.rs | 54 + atomic-cli/src/commands/diagnostics/render.rs | 456 ++++++ .../src/commands/git/hook_dispatchers.rs | 152 +- atomic-cli/src/commands/mod.rs | 2 + atomic-cli/src/logging/mod.rs | 2 +- atomic-cli/src/logging/redact.rs | 2 +- atomic-cli/src/main.rs | 17 + .../tests/it/diagnostics_integration_test.rs | 207 +++ atomic-cli/tests/it/main.rs | 1 + docs/README.md | 2 + docs/diagnostics.md | 83 ++ 13 files changed, 2257 insertions(+), 30 deletions(-) create mode 100644 atomic-cli/src/commands/diagnostics/collect.rs create mode 100644 atomic-cli/src/commands/diagnostics/mod.rs create mode 100644 atomic-cli/src/commands/diagnostics/render.rs create mode 100644 atomic-cli/tests/it/diagnostics_integration_test.rs create mode 100644 docs/diagnostics.md diff --git a/README.md b/README.md index 6a4c6c47..621e2792 100644 --- a/README.md +++ b/README.md @@ -592,6 +592,7 @@ Every change stores two parallel representations: | `atomic agent status` | Show sessions, hook liveness, and failures (`--json` for tooling) | | `atomic agent explain ` | Generate AI reasoning summary for a session | | `atomic agent attest` | List and inspect attestations | +| `atomic diagnostics` | Read-only support report: version, integrations, skills, enabled agents, Git shim (`--json`) | Hook health is computed from session-scoped logs, so concurrent agents retain their own outcomes and a child's success cannot hide a parent's failure. See diff --git a/atomic-cli/src/commands/diagnostics/collect.rs b/atomic-cli/src/commands/diagnostics/collect.rs new file mode 100644 index 00000000..e6ccbed7 --- /dev/null +++ b/atomic-cli/src/commands/diagnostics/collect.rs @@ -0,0 +1,1308 @@ +//! Gathering the support report. +//! +//! Every fact comes from the running binary or from local configuration that +//! Atomic itself wrote: integration receipts, the `atomic-skills` cache +//! manifest, each agent's hook configuration (through its adapter), and the +//! repository's `.atomic/config.toml`. Nothing is written and nothing touches +//! the network. A value that cannot be read is reported with the reason, +//! never filled in by inference. + +use std::io::ErrorKind; +use std::path::{Path, PathBuf}; + +use atomic_agent::hooks::AgentRegistry; +use atomic_agent::integrations::{IntegrationManifest, Receipt}; +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; + +/// Version of the JSON document. Bumped when a field changes meaning. +pub(crate) const SCHEMA: u32 = 1; + +/// Registry name of the shared skills package. It is synced as a cache for +/// other integrations to copy skills from, never installed on its own. +const SKILLS_PACKAGE: &str = "atomic-skills"; + +const RECEIPT_FILE: &str = "receipt.json"; + +// Report + +#[derive(Debug, Serialize)] +pub(crate) struct Report { + pub schema: u32, + pub generated_at: String, + pub atomic: AtomicInfo, + pub workspace: Workspace, + pub integrations: Integrations, + pub skills: Skills, + /// Every agent Atomic has an adapter for, and whether its hooks are active. + pub agents: Vec, + pub git_shim: GitShim, + /// Facts a support conversation may ask for that this report does not + /// collect, and why. + pub not_collected: Vec, +} + +#[derive(Debug, Serialize)] +pub(crate) struct AtomicInfo { + pub version: String, + /// `installer`, `homebrew`, `cargo`, `manual`, or `unknown` — the same + /// detection `atomic update` routes upgrades with. + pub install_source: String, + pub os: &'static str, + pub arch: &'static str, +} + +#[derive(Debug, Serialize)] +#[serde(tag = "status", rename_all = "snake_case")] +pub(crate) enum Workspace { + Found { root: String }, + NotFound, + Unreadable { reason: String }, +} + +#[derive(Debug, Serialize)] +pub(crate) struct Integrations { + /// Where receipts are read from; absent when it cannot be resolved. + #[serde(skip_serializing_if = "Option::is_none")] + pub root: Option, + /// `ATOMIC_INTEGRATIONS_HOME` relocated the root. + pub root_overridden: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub root_error: Option, + pub packages: Vec, +} + +/// One externally packaged integration and its install receipt. +#[derive(Debug, Serialize)] +pub(crate) struct Integration { + pub agent: String, + pub display_name: String, + #[serde(flatten)] + pub state: IntegrationState, +} + +#[derive(Debug, Serialize)] +#[serde(tag = "status", rename_all = "snake_case")] +pub(crate) enum IntegrationState { + Installed(InstalledIntegration), + NotInstalled, + Unreadable { reason: String }, +} + +#[derive(Debug, Serialize)] +pub(crate) struct InstalledIntegration { + /// Package version from its manifest, as recorded at install time. + pub version: String, + /// The Atomic version that performed the install. + pub installed_with: String, + pub installed_at: String, + /// `registry`, `local`, or `url`. + pub source_kind: &'static str, + /// Where the package came from, with any URL credentials removed. + pub source: String, + pub files: FileCounts, +} + +/// The receipt's files compared against what is on disk now. +#[derive(Debug, Default, Serialize, PartialEq, Eq)] +pub(crate) struct FileCounts { + pub recorded: usize, + pub present: usize, + pub modified: usize, + pub missing: usize, + pub unreadable: usize, +} + +#[derive(Debug, Serialize)] +pub(crate) struct Skills { + pub package: SkillsPackage, + /// Skill files integrations copied into place, per their receipts. + pub installed: Vec, +} + +#[derive(Debug, Serialize)] +#[serde(tag = "status", rename_all = "snake_case")] +pub(crate) enum SkillsPackage { + /// The cached package manifest the last `atomic agent enable` synced. + Available { + name: &'static str, + version: String, + skills: Vec, + }, + NotFound { + reason: String, + }, + Unreadable { + reason: String, + }, +} + +#[derive(Debug, Serialize)] +pub(crate) struct InstalledSkill { + pub agent: String, + 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. + pub version: Option, +} + +#[derive(Clone, Copy, Debug, Serialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub(crate) enum FileState { + /// Matches what was installed. + Present, + /// Exists, but its content differs from what was installed. + Modified, + Missing, + Unreadable, +} + +#[derive(Debug, Serialize)] +pub(crate) struct AgentState { + pub name: String, + pub display_name: String, + pub enabled: Enabled, + /// What the `enabled` answer rests on. + pub evidence: Vec, +} + +#[derive(Clone, Copy, Debug, Serialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub(crate) enum Enabled { + Yes, + No, + /// The evidence needed to answer could not be read or does not exist. + Unknown, +} + +#[derive(Debug, Serialize)] +pub(crate) struct GitShim { + pub status: ShimStatus, + #[serde(skip_serializing_if = "Option::is_none")] + pub reason: Option, + pub hooks: GitHooks, +} + +#[derive(Clone, Copy, Debug, Serialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub(crate) enum ShimStatus { + /// `[git.shim] enabled = true` in the repository configuration. + Enabled, + Disabled, + /// Outside an Atomic workspace there is no shim to ask about. + NotApplicable, + Unknown, +} + +#[derive(Debug, Serialize)] +#[serde(tag = "status", rename_all = "snake_case")] +pub(crate) enum GitHooks { + NotApplicable, + NoGitRepository, + /// `core.hooksPath` points elsewhere; Atomic does not manage hooks there. + ExternallyManaged { + hooks_path: String, + }, + Inspected { + dispatchers: Vec, + }, + Unreadable { + reason: String, + }, +} + +#[derive(Debug, Serialize)] +pub(crate) struct Dispatcher { + pub hook: &'static str, + /// Stable key, e.g. `atomic_owned`. + pub state: &'static str, + /// The wording `atomic git hooks status` prints. + #[serde(skip)] + pub label: &'static str, +} + +#[derive(Debug, Serialize)] +pub(crate) struct NotCollected { + pub item: &'static str, + pub reason: &'static str, +} + +// Sources + +/// Where collection reads from. Resolved from the process in production; +/// tests point every location at temporary directories. +pub(crate) struct Sources { + pub home: Option, + pub integrations_root: Result, + pub integrations_root_overridden: bool, + /// The enclosing Atomic workspace; `Ok(None)` outside one. + pub workspace: Result, String>, + pub install_source: String, +} + +impl Sources { + pub(crate) fn from_process() -> Self { + let workspace = match find_repository_root() { + Ok(root) => Ok(Some(root)), + Err(CliError::RepositoryNotFound { .. }) => Ok(None), + Err(error) => Err(error.to_string()), + }; + 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(), + integrations_root: atomic_agent::integrations::integrations_root() + .map_err(|error| error.to_string()), + integrations_root_overridden: std::env::var_os("ATOMIC_INTEGRATIONS_HOME").is_some(), + workspace, + install_source, + } + } +} + +/// One agent adapter, reduced to what the report needs from it. +pub(crate) struct AgentProbe<'a> { + 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. +pub(crate) fn collect() -> Report { + let registry = AgentRegistry::with_defaults(); + let probes = registry + .iter() + .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(); + collect_from(&Sources::from_process(), &probes, &packaged) +} + +/// Collect the report from explicit sources: `probes` are the agent +/// adapters, `packaged` the agents with an integration package. +pub(crate) fn collect_from( + sources: &Sources, + probes: &[AgentProbe<'_>], + packaged: &[String], +) -> Report { + let home = sources.home.as_deref(); + let display_name = |agent: &str| { + probes + .iter() + .find(|probe| probe.name == agent) + .map_or_else(|| agent.to_string(), |probe| probe.display_name.clone()) + }; + + // Receipts, for every packaged agent plus any receipt on disk for an + // agent this binary no longer lists — that is exactly the + // version-skew case a support conversation needs to see. + let mut agents_with_packages: Vec = packaged + .iter() + .filter(|name| *name != SKILLS_PACKAGE) + .cloned() + .collect(); + if let Ok(root) = &sources.integrations_root { + for name in receipts_on_disk(root) { + if name != SKILLS_PACKAGE && !agents_with_packages.contains(&name) { + agents_with_packages.push(name); + } + } + } + agents_with_packages.sort(); + let receipts: Vec<(String, ReceiptLookup)> = agents_with_packages + .into_iter() + .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}" + )), + }; + (agent, lookup) + }) + .collect(); + let receipt_for = |agent: &str| { + receipts + .iter() + .find(|(name, _)| name == agent) + .map(|(_, lookup)| lookup) + }; + + let package = match &sources.integrations_root { + Ok(root) => read_skills_package(&root.join(SKILLS_PACKAGE).join("repo")), + Err(reason) => SkillsPackage::Unreadable { + reason: format!("integrations directory unresolved: {reason}"), + }, + }; + let declared = match &package { + SkillsPackage::Available { skills, .. } => Some(skills.as_slice()), + _ => None, + }; + + let mut installed_skills = Vec::new(); + let integrations = receipts + .iter() + .map(|(agent, lookup)| { + let state = match lookup { + ReceiptLookup::Absent => IntegrationState::NotInstalled, + ReceiptLookup::Unreadable(reason) => IntegrationState::Unreadable { + reason: reason.clone(), + }, + ReceiptLookup::Found(receipt) => { + let mut files = FileCounts { + recorded: receipt.files.len(), + ..FileCounts::default() + }; + for file in &receipt.files { + let state = file_state(&file.dst, &file.blake3); + match state { + FileState::Present => files.present += 1, + FileState::Modified => files.modified += 1, + FileState::Missing => files.missing += 1, + FileState::Unreadable => files.unreadable += 1, + } + if let Some(name) = skill_name(&file.dst, declared) { + 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, + }, + state, + }); + } + } + let (source_kind, source) = describe_source(&receipt.source, agent, home); + IntegrationState::Installed(InstalledIntegration { + version: receipt.version.clone(), + installed_with: receipt.cli_version.clone(), + installed_at: receipt.installed_at.clone(), + source_kind, + source, + files, + }) + } + }; + Integration { + agent: agent.clone(), + display_name: display_name(agent), + state, + } + }) + .collect(); + + let workspace_root = sources.workspace.as_ref().ok().and_then(Option::as_deref); + 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 { + Some(ReceiptLookup::Found(receipt)) => receipt + .settings + .iter() + .map(|entry| SettingsProbe { + path: display_path(&entry.target, home), + hooks: settings_hooks(&entry.target, &entry.command_prefix), + }) + .collect(), + _ => Vec::new(), + }; + let (enabled, evidence) = classify_enabled(&probe.name, adapter, receipt, &settings); + AgentState { + name: probe.name.clone(), + display_name: probe.display_name.clone(), + enabled, + evidence, + } + }) + .collect(); + agents.sort_by(|a, b| a.name.cmp(&b.name)); + + Report { + schema: SCHEMA, + generated_at: chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true), + atomic: AtomicInfo { + version: env!("ATOMIC_CLI_VERSION").to_string(), + install_source: sources.install_source.clone(), + os: std::env::consts::OS, + arch: std::env::consts::ARCH, + }, + workspace: match &sources.workspace { + Ok(Some(root)) => Workspace::Found { + root: display_path(root, home), + }, + Ok(None) => Workspace::NotFound, + Err(reason) => Workspace::Unreadable { + reason: reason.clone(), + }, + }, + integrations: Integrations { + root: sources + .integrations_root + .as_ref() + .ok() + .map(|root| display_path(root, home)), + root_overridden: sources.integrations_root_overridden, + root_error: sources.integrations_root.as_ref().err().cloned(), + packages: integrations, + }, + skills: Skills { + package, + installed: installed_skills, + }, + agents, + git_shim: collect_git_shim(&sources.workspace, home), + not_collected: vec![NotCollected { + item: "agent application versions", + reason: "Atomic keeps no record of the agent applications' own versions, and \ + detecting them would mean running third-party programs", + }], + } +} + +// Receipts and files + +enum ReceiptLookup { + Found(Receipt), + Absent, + Unreadable(String), +} + +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) if error.kind() == ErrorKind::NotFound => ReceiptLookup::Absent, + Err(error) => ReceiptLookup::Unreadable(format!("cannot read receipt: {error}")), + } +} + +/// Agent directories under the integrations root that hold a receipt. +fn receipts_on_disk(root: &Path) -> Vec { + let Ok(entries) = std::fs::read_dir(root) else { + return Vec::new(); + }; + entries + .flatten() + .filter(|entry| entry.path().join(RECEIPT_FILE).is_file()) + .filter_map(|entry| entry.file_name().into_string().ok()) + .collect() +} + +fn file_state(path: &Path, recorded_blake3: &str) -> FileState { + match std::fs::read(path) { + Ok(bytes) if blake3::hash(&bytes).to_hex().as_str() == recorded_blake3 => { + FileState::Present + } + Ok(_) => FileState::Modified, + Err(error) if error.kind() == ErrorKind::NotFound => FileState::Missing, + Err(_) => FileState::Unreadable, + } +} + +/// Whether a settings file still carries this integration's hook commands. +#[derive(Debug)] +enum HookPresence { + Present, + Absent, + Unreadable(String), +} + +struct SettingsProbe { + path: String, + hooks: HookPresence, +} + +fn settings_hooks(path: &Path, 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()), + } +} + +/// Describe a receipt's source without leaking credentials or the user's +/// home directory. +fn describe_source(source: &str, agent: &str, home: Option<&Path>) -> (&'static str, String) { + let registry_url = atomic_agent::integrations::resolve(agent).map(|spec| spec.url); + if registry_url.as_deref() == Some(source) { + ("registry", source.to_string()) + } else if source.contains("://") { + ("url", redact::urls(source)) + } else { + ("local", display_path(Path::new(source), home)) + } +} + +// 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`; \ + `--from-skills` installs leave no cache)" + .to_string(), + }; + } + match IntegrationManifest::load(cache) { + Ok(manifest) => SkillsPackage::Available { + name: SKILLS_PACKAGE, + version: manifest.version, + skills: manifest + .declared_skills + .into_iter() + .map(|skill| skill.name) + .collect(), + }, + Err(error) => SkillsPackage::Unreadable { + reason: error.to_string(), + }, + } +} + +/// The skill an installed file is, if it is one. +/// +/// Nested layouts install `/SKILL.md`; flat ones (Cline, agy) install +/// `.md`, which is only recognisable as a skill when the declared skill +/// list is known. +fn skill_name(dst: &Path, declared: Option<&[String]>) -> Option { + let file_name = dst.file_name()?.to_str()?; + if file_name == "SKILL.md" { + let name = dst.parent()?.file_name()?.to_str()?.to_string(); + return match declared { + Some(declared) if !declared.contains(&name) => None, + _ => Some(name), + }; + } + let stem = file_name.strip_suffix(".md")?; + declared? + .iter() + .any(|name| name == stem) + .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 frontmatter_version(text: &str) -> Option { + 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()) +} + +// 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) { + evidence.push(format!("Atomic hook commands present in {}", probe.path)); + } + } + if !evidence.is_empty() { + 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(_)) => { + 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) + } + } + } +} + +// Git shim + +fn collect_git_shim(workspace: &Result, String>, home: Option<&Path>) -> GitShim { + let root = match workspace { + Ok(Some(root)) => root, + Ok(None) => { + return GitShim { + status: ShimStatus::NotApplicable, + reason: Some("not inside an Atomic workspace".to_string()), + hooks: GitHooks::NotApplicable, + } + } + Err(reason) => { + return GitShim { + status: ShimStatus::Unknown, + reason: Some(format!("workspace lookup failed: {reason}")), + hooks: GitHooks::NotApplicable, + } + } + }; + + let (status, reason) = match 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())), + }; + let hooks = match inspect_dispatchers(root) { + Ok(None) => GitHooks::NoGitRepository, + Ok(Some(DispatcherReport::External { hooks_path })) => GitHooks::ExternallyManaged { + hooks_path: display_path(&hooks_path, home), + }, + Ok(Some(DispatcherReport::Inspected(hooks))) => GitHooks::Inspected { + dispatchers: hooks + .into_iter() + .map(|hook| Dispatcher { + hook: hook.name, + state: hook.state.code(), + label: hook.state.label(), + }) + .collect(), + }, + Err(error) => GitHooks::Unreadable { + reason: error.to_string(), + }, + }; + GitShim { + status, + reason, + hooks, + } +} + +/// `path` with the home directory shown as `~`, so a pasted report does not +/// carry the user's account name. +fn display_path(path: &Path, home: Option<&Path>) -> String { + match home.and_then(|home| path.strip_prefix(home).ok()) { + Some(rest) if rest.as_os_str().is_empty() => "~".to_string(), + Some(rest) => format!("~/{}", rest.display()), + None => path.display().to_string(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + use tempfile::TempDir; + + struct Fixture { + home: TempDir, + } + + impl Fixture { + fn new() -> Self { + Self { + home: TempDir::new().unwrap(), + } + } + + fn integrations(&self) -> PathBuf { + self.home.path().join(".atomic").join("integrations") + } + + fn sources(&self, workspace: Option) -> Sources { + Sources { + home: Some(self.home.path().to_path_buf()), + integrations_root: Ok(self.integrations()), + integrations_root_overridden: false, + workspace: Ok(workspace), + install_source: "cargo".to_string(), + } + } + + /// Install `files` (relative to home) and write the receipt that + /// records them as installed with the given content. + fn install(&self, agent: &str, version: &str, files: &[(&str, &str)]) -> Vec { + let paths: Vec = files + .iter() + .map(|(rel, body)| { + let path = self.home.path().join(rel); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(&path, body).unwrap(); + path + }) + .collect(); + let receipt = serde_json::json!({ + "schema": 1, + "agent": agent, + "version": version, + "cli_version": "0.19.0", + "installed_at": "2026-10-01T12:00:00+00:00", + "source": "/home/someone/src/pkg", + "files": paths.iter().zip(files).map(|(path, (_, body))| serde_json::json!({ + "dst": path, + "blake3": blake3::hash(body.as_bytes()).to_hex().to_string(), + })).collect::>(), + "settings": [], + }); + self.write_receipt(agent, &receipt); + paths + } + + fn write_receipt(&self, agent: &str, receipt: &serde_json::Value) { + let dir = self.integrations().join(agent); + fs::create_dir_all(&dir).unwrap(); + fs::write( + dir.join(RECEIPT_FILE), + serde_json::to_string(receipt).unwrap(), + ) + .unwrap(); + } + + fn skills_cache(&self, manifest: &str) { + let dir = self.integrations().join(SKILLS_PACKAGE).join("repo"); + fs::create_dir_all(&dir).unwrap(); + fs::write( + dir.join(atomic_agent::integrations::MANIFEST_FILE), + manifest, + ) + .unwrap(); + } + } + + fn probe(name: &str, installed: bool) -> AgentProbe<'static> { + AgentProbe { + name: name.to_string(), + display_name: name.to_uppercase(), + hooks_installed: Box::new(move |_| installed), + } + } + + fn integration<'r>(report: &'r Report, agent: &str) -> &'r IntegrationState { + &report + .integrations + .packages + .iter() + .find(|p| p.agent == agent) + .unwrap_or_else(|| panic!("{agent} listed")) + .state + } + + fn agent<'r>(report: &'r Report, name: &str) -> &'r AgentState { + report.agents.iter().find(|a| a.name == name).unwrap() + } + + #[test] + fn a_fresh_machine_reports_everything_as_absent_not_guessed() { + let fixture = Fixture::new(); + let report = collect_from( + &fixture.sources(None), + &[probe("claude-code", false)], + &["claude-code".to_string(), SKILLS_PACKAGE.to_string()], + ); + + assert!(matches!(report.workspace, Workspace::NotFound)); + assert!(matches!( + integration(&report, "claude-code"), + IntegrationState::NotInstalled + )); + assert!( + !report + .integrations + .packages + .iter() + .any(|p| p.agent == SKILLS_PACKAGE), + "the skills package is a cache, not an integration" + ); + assert!(matches!( + report.skills.package, + SkillsPackage::NotFound { .. } + )); + assert!(report.skills.installed.is_empty()); + assert_eq!(agent(&report, "claude-code").enabled, Enabled::No); + assert_eq!(report.git_shim.status, ShimStatus::NotApplicable); + assert!(matches!(report.git_shim.hooks, GitHooks::NotApplicable)); + assert_eq!(report.atomic.version, env!("ATOMIC_CLI_VERSION")); + } + + #[test] + fn installed_integrations_report_receipt_versions_and_file_drift() { + let fixture = Fixture::new(); + let paths = fixture.install( + "opencode", + "1.2.0", + &[ + (".config/opencode/a.md", "a"), + (".config/opencode/b.md", "b"), + (".config/opencode/c.md", "c"), + ], + ); + fs::write(&paths[1], "edited by the user").unwrap(); + fs::remove_file(&paths[2]).unwrap(); + + let report = collect_from( + &fixture.sources(None), + &[probe("opencode", false)], + &["opencode".to_string()], + ); + + let IntegrationState::Installed(installed) = integration(&report, "opencode") else { + panic!("opencode is installed"); + }; + assert_eq!(installed.version, "1.2.0"); + assert_eq!(installed.installed_with, "0.19.0"); + assert_eq!(installed.source_kind, "local"); + assert_eq!( + installed.files, + FileCounts { + recorded: 3, + present: 1, + modified: 1, + missing: 1, + unreadable: 0, + } + ); + } + + #[test] + fn a_corrupt_receipt_is_unreadable_and_leaves_enablement_unknown() { + let fixture = Fixture::new(); + let dir = fixture.integrations().join("cline"); + fs::create_dir_all(&dir).unwrap(); + fs::write(dir.join(RECEIPT_FILE), "{ not json").unwrap(); + + let report = collect_from( + &fixture.sources(None), + &[probe("cline", false)], + &["cline".to_string()], + ); + + assert!(matches!( + integration(&report, "cline"), + IntegrationState::Unreadable { .. } + )); + let cline = agent(&report, "cline"); + assert_eq!(cline.enabled, Enabled::Unknown); + assert!(cline.evidence[0].contains("receipt unreadable")); + } + + #[test] + fn receipts_for_agents_this_binary_does_not_list_are_still_reported() { + let fixture = Fixture::new(); + fixture.install("retired-agent", "0.1.0", &[(".retired/x.md", "x")]); + + let report = collect_from(&fixture.sources(None), &[], &[]); + + assert!(matches!( + integration(&report, "retired-agent"), + IntegrationState::Installed(_) + )); + } + + #[test] + 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()); + + let report = collect_from(&sources, &[probe("cline", false)], &["cline".to_string()]); + + assert_eq!( + report.integrations.root_error.as_deref(), + Some("cannot resolve home directory") + ); + assert!(matches!( + integration(&report, "cline"), + IntegrationState::Unreadable { .. } + )); + assert!(matches!( + report.skills.package, + SkillsPackage::Unreadable { .. } + )); + assert_eq!(agent(&report, "cline").enabled, Enabled::Unknown); + } + + #[test] + fn skills_are_found_from_receipts_with_their_package_and_file_versions() { + let fixture = Fixture::new(); + fixture.skills_cache( + "schema = 1\nagent = \"atomic-skills\"\nversion = \"0.4.0\"\n\n\ + [[declared-skill]]\nname = \"atomic-vault\"\n\n\ + [[declared-skill]]\nname = \"atomic-vcs\"\n", + ); + fixture.install( + "claude-code", + "1.0.0", + &[ + ( + ".claude/skills/atomic-vault/SKILL.md", + "---\nname: atomic-vault\nversion: \"2.1.0\"\n---\nbody\n", + ), + (".claude/skills/atomic-vcs/SKILL.md", "no frontmatter\n"), + (".claude/skills/someone-elses/SKILL.md", "---\n---\n"), + (".claude/agents/atomic.md", "agent definition"), + ], + ); + fixture.install( + "cline", + "1.0.0", + &[("Documents/Cline/Workflows/atomic-vault.md", "flat layout")], + ); + + let report = collect_from( + &fixture.sources(None), + &[probe("claude-code", false), probe("cline", false)], + &["claude-code".to_string(), "cline".to_string()], + ); + + let SkillsPackage::Available { + version, skills, .. + } = &report.skills.package + else { + panic!("skills cache is readable"); + }; + assert_eq!(version, "0.4.0"); + assert_eq!(skills, &["atomic-vault", "atomic-vcs"]); + + let found: Vec<(&str, &str, Option<&str>)> = report + .skills + .installed + .iter() + .map(|s| (s.agent.as_str(), s.name.as_str(), s.version.as_deref())) + .collect(); + assert_eq!( + found, + vec![ + ("claude-code", "atomic-vault", Some("2.1.0")), + ("claude-code", "atomic-vcs", None), + ("cline", "atomic-vault", None), + ], + "undeclared SKILL.md files and non-skill files are not skills" + ); + assert_eq!( + report.skills.installed[0].path, + "~/.claude/skills/atomic-vault/SKILL.md" + ); + } + + #[test] + fn without_the_skills_cache_only_nested_skill_files_are_recognised() { + assert_eq!( + skill_name(Path::new("/h/.claude/skills/x/SKILL.md"), None).as_deref(), + Some("x") + ); + assert_eq!(skill_name(Path::new("/h/Workflows/x.md"), None), None); + } + + #[test] + fn frontmatter_version_is_read_only_from_frontmatter() { + assert_eq!( + frontmatter_version("---\nversion: 1.2.3\n---\n").as_deref(), + Some("1.2.3") + ); + assert_eq!( + frontmatter_version("---\nversion: '1.2.3'\n---\n").as_deref(), + Some("1.2.3") + ); + 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 { + SettingsProbe { + path: path.to_string(), + hooks, + } + } + + fn receipt() -> ReceiptLookup { + ReceiptLookup::Found( + serde_json::from_value(serde_json::json!({ + "schema": 1, "agent": "x", "version": "1", "cli_version": "1", + "installed_at": "t", "source": "s", "files": [], + })) + .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")); + + // Installed, and the settings file still carries the hooks. + let (enabled, evidence) = classify_enabled( + "x", + NOTHING, + Some(&receipt()), + &[settings("~/.x/settings.json", HookPresence::Present)], + ); + assert_eq!(enabled, Enabled::Yes); + assert_eq!( + 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()), + )], + ); + 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()), &[]); + 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, + &[], + ); + assert_eq!(enabled, Enabled::No); + assert!(evidence.is_empty()); + } + + #[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"); + fs::create_dir_all(settings_path.parent().unwrap()).unwrap(); + fs::write( + &settings_path, + r#"{"hooks":{"Stop":[{"command":"atomic agent hooks x stop"}]}}"#, + ) + .unwrap(); + fixture.write_receipt( + "x", + &serde_json::json!({ + "schema": 1, "agent": "x", "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", + }], + }), + ); + + let report = collect_from( + &fixture.sources(None), + &[probe("x", false)], + &["x".to_string()], + ); + let x = agent(&report, "x"); + assert_eq!(x.enabled, Enabled::Yes); + assert_eq!( + x.evidence, + ["Atomic hook commands present in ~/.x/settings.json"] + ); + + let IntegrationState::Installed(installed) = integration(&report, "x") else { + panic!("x is installed"); + }; + assert_eq!(installed.source_kind, "url"); + assert_eq!(installed.source, "https://***@example.com/pkg"); + } + + #[test] + fn a_workspace_without_git_reports_the_shim_consent_and_no_git() { + let fixture = Fixture::new(); + let workspace = TempDir::new().unwrap(); + atomic_repository::Repository::init(workspace.path()).unwrap(); + + let report = collect_from( + &fixture.sources(Some(workspace.path().to_path_buf())), + &[], + &[], + ); + + assert!(matches!(report.workspace, Workspace::Found { .. })); + assert_eq!(report.git_shim.status, ShimStatus::Disabled); + assert!(matches!(report.git_shim.hooks, GitHooks::NoGitRepository)); + } + + #[test] + fn shim_consent_in_repository_config_reads_as_enabled() { + let fixture = Fixture::new(); + let workspace = TempDir::new().unwrap(); + drop(git2::Repository::init(workspace.path()).unwrap()); + atomic_repository::Repository::init(workspace.path()).unwrap(); + fs::write( + workspace.path().join(".atomic").join("config.toml"), + "[git.shim]\nenabled = true\n", + ) + .unwrap(); + + let report = collect_from( + &fixture.sources(Some(workspace.path().to_path_buf())), + &[], + &[], + ); + + assert_eq!(report.git_shim.status, ShimStatus::Enabled); + let GitHooks::Inspected { dispatchers } = &report.git_shim.hooks else { + panic!("a Git repository's hooks are inspected"); + }; + assert_eq!(dispatchers.len(), 5); + assert!(dispatchers.iter().all(|d| d.state == "not_installed")); + } + + #[test] + fn an_unparseable_repository_config_leaves_the_shim_unknown() { + let fixture = Fixture::new(); + let workspace = TempDir::new().unwrap(); + atomic_repository::Repository::init(workspace.path()).unwrap(); + fs::write( + workspace.path().join(".atomic").join("config.toml"), + "[git.shim\n", + ) + .unwrap(); + + let report = collect_from( + &fixture.sources(Some(workspace.path().to_path_buf())), + &[], + &[], + ); + + assert_eq!(report.git_shim.status, ShimStatus::Unknown); + assert!(report.git_shim.reason.is_some()); + } + + #[test] + fn home_paths_are_shown_relative_to_tilde() { + let home = Path::new("/home/alice"); + assert_eq!( + display_path(Path::new("/home/alice/.claude/settings.json"), Some(home)), + "~/.claude/settings.json" + ); + assert_eq!(display_path(home, Some(home)), "~"); + assert_eq!(display_path(Path::new("/opt/x"), Some(home)), "/opt/x"); + assert_eq!(display_path(Path::new("/opt/x"), None), "/opt/x"); + } +} diff --git a/atomic-cli/src/commands/diagnostics/mod.rs b/atomic-cli/src/commands/diagnostics/mod.rs new file mode 100644 index 00000000..86e87fa4 --- /dev/null +++ b/atomic-cli/src/commands/diagnostics/mod.rs @@ -0,0 +1,54 @@ +//! `atomic diagnostics` — a read-only support report. +//! +//! Collects the context a support conversation otherwise asks for one +//! follow-up at a time: the Atomic version and install source, installed +//! 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 `~`. +//! +//! # Examples +//! +//! ```text +//! # Paste-ready text report +//! atomic diagnostics +//! +//! # The same facts as one JSON document +//! atomic diagnostics --json +//! ``` + +mod collect; +mod render; + +use clap::Args; + +use crate::commands::Command; +use crate::error::CliResult; + +/// Print a read-only support report. +#[derive(Debug, Args)] +pub struct Diagnostics { + /// Print the report as one JSON document. + #[arg(long)] + json: bool, +} + +impl Command for Diagnostics { + fn run(&self) -> CliResult<()> { + let report = collect::collect(); + if self.json { + println!( + "{}", + serde_json::to_string_pretty(&report) + .expect("the report is plain data and always serializes") + ); + } else { + print!("{}", render::render_text(&report)); + } + Ok(()) + } +} diff --git a/atomic-cli/src/commands/diagnostics/render.rs b/atomic-cli/src/commands/diagnostics/render.rs new file mode 100644 index 00000000..20b027c8 --- /dev/null +++ b/atomic-cli/src/commands/diagnostics/render.rs @@ -0,0 +1,456 @@ +//! Plain-text rendering of the support report. +//! +//! The text is meant to be pasted into a support conversation, so it carries +//! no color or terminal control codes, keeps one fact per line, and names +//! every unknown value as unknown with its reason. + +use std::fmt::Write; + +use super::collect::{ + AgentState, Enabled, FileCounts, FileState, GitHooks, IntegrationState, Report, ShimStatus, + SkillsPackage, Workspace, +}; + +/// Width of the label column. +const LABEL: usize = 16; + +pub(crate) fn render_text(report: &Report) -> String { + let mut out = String::new(); + let o = &mut out; + + line(o, "Atomic diagnostics"); + line(o, "=================="); + field(o, "Generated", &report.generated_at); + blank(o); + + section(o, "Atomic"); + field(o, "Version", &report.atomic.version); + field(o, "Install source", &report.atomic.install_source); + field( + o, + "Platform", + &format!("{} {}", report.atomic.os, report.atomic.arch), + ); + let workspace = match &report.workspace { + Workspace::Found { root } => root.clone(), + Workspace::NotFound => "none (not inside an Atomic workspace)".to_string(), + Workspace::Unreadable { reason } => format!("unknown — {reason}"), + }; + field(o, "Workspace", &workspace); + blank(o); + + render_integrations(o, report); + render_skills(o, report); + render_agents(o, &report.agents); + render_shim(o, report); + + section(o, "Not collected"); + for item in &report.not_collected { + line(o, &format!(" {}: {}", item.item, item.reason)); + } + + out +} + +fn render_integrations(o: &mut String, report: &Report) { + section(o, "Agent integrations (installed packages)"); + let integrations = &report.integrations; + let root = match (&integrations.root, &integrations.root_error) { + (Some(root), _) if integrations.root_overridden => { + format!("{root} (set by ATOMIC_INTEGRATIONS_HOME)") + } + (Some(root), _) => root.clone(), + (None, Some(error)) => format!("unknown — {error}"), + (None, None) => "unknown".to_string(), + }; + field(o, "Receipts", &root); + + let mut not_installed = Vec::new(); + for package in &integrations.packages { + let name = format!("{} ({})", package.display_name, package.agent); + match &package.state { + IntegrationState::Installed(installed) => { + line(o, &format!(" {name}")); + field(o, " Version", &installed.version); + field( + o, + " Installed", + &format!( + "{} with atomic {}", + installed.installed_at, installed.installed_with + ), + ); + field( + o, + " Source", + &format!("{} ({})", installed.source, installed.source_kind), + ); + field(o, " Files", &file_counts(&installed.files)); + } + IntegrationState::Unreadable { reason } => { + line(o, &format!(" {name}")); + field(o, " Version", &format!("unknown — {reason}")); + } + IntegrationState::NotInstalled => not_installed.push(package.agent.as_str()), + } + } + if !not_installed.is_empty() { + field(o, "Not installed", ¬_installed.join(", ")); + } + blank(o); +} + +fn file_counts(files: &FileCounts) -> String { + let mut parts = vec![format!("{} recorded", files.recorded)]; + for (count, label) in [ + (files.present, "unchanged"), + (files.modified, "modified"), + (files.missing, "missing"), + (files.unreadable, "unreadable"), + ] { + if count > 0 { + parts.push(format!("{count} {label}")); + } + } + parts.join(", ") +} + +fn render_skills(o: &mut String, report: &Report) { + section(o, "Skills"); + let package = match &report.skills.package { + SkillsPackage::Available { name, version, .. } => { + format!("{name} {version} (cached by the last `atomic agent enable`)") + } + SkillsPackage::NotFound { reason } => format!("unknown — {reason}"), + SkillsPackage::Unreadable { reason } => format!("unknown — {reason}"), + }; + field(o, "Skills package", &package); + if report.skills.installed.is_empty() { + 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 state = match skill.state { + FileState::Present => "", + FileState::Modified => ", modified since install", + FileState::Missing => ", missing", + FileState::Unreadable => ", unreadable", + }; + line( + o, + &format!(" {} for {} — {version}{state}", skill.name, skill.agent), + ); + } + blank(o); +} + +fn render_agents(o: &mut String, agents: &[AgentState]) { + section(o, "Enabled agents (Atomic hooks active)"); + let mut not_enabled = Vec::new(); + for agent in agents { + let answer = match agent.enabled { + Enabled::Yes => "yes", + Enabled::Unknown => "unknown", + Enabled::No if agent.evidence.is_empty() => { + not_enabled.push(agent.name.as_str()); + continue; + } + Enabled::No => "no", + }; + line( + o, + &format!(" {} ({}): {answer}", agent.display_name, agent.name), + ); + for evidence in &agent.evidence { + line(o, &format!(" - {evidence}")); + } + } + if agents.iter().all(|agent| agent.enabled == Enabled::No) { + line(o, " No agent has Atomic hooks enabled."); + } + if !not_enabled.is_empty() { + field(o, "Not enabled", ¬_enabled.join(", ")); + } + blank(o); +} + +fn render_shim(o: &mut String, report: &Report) { + section(o, "Git shim"); + let shim = &report.git_shim; + let status = match shim.status { + ShimStatus::Enabled => "yes ([git.shim] enabled = true)".to_string(), + ShimStatus::Disabled => "no".to_string(), + ShimStatus::NotApplicable => format!( + "not applicable — {}", + shim.reason.as_deref().unwrap_or("no workspace") + ), + ShimStatus::Unknown => format!( + "unknown — {}", + shim.reason.as_deref().unwrap_or("not readable") + ), + }; + field(o, "Enabled", &status); + match &shim.hooks { + GitHooks::NotApplicable => {} + GitHooks::NoGitRepository => field(o, "Git hooks", "no Git repository in this workspace"), + GitHooks::ExternallyManaged { hooks_path } => field( + o, + "Git hooks", + &format!("managed outside Atomic (core.hooksPath = {hooks_path})"), + ), + GitHooks::Unreadable { reason } => field(o, "Git hooks", &format!("unknown — {reason}")), + GitHooks::Inspected { dispatchers } => { + field(o, "Git hooks", ""); + for dispatcher in dispatchers { + line(o, &format!(" {}: {}", dispatcher.hook, dispatcher.label)); + } + } + } + blank(o); +} + +fn section(o: &mut String, title: &str) { + line(o, title); +} + +fn field(o: &mut String, label: &str, value: &str) { + let label = format!("{label}:"); + line(o, format!(" {label: Report { + Report { + schema: SCHEMA, + generated_at: "2026-10-28T12:00:00Z".to_string(), + atomic: AtomicInfo { + version: "0.20.0".to_string(), + install_source: "cargo".to_string(), + os: "linux", + arch: "x86_64", + }, + workspace: Workspace::NotFound, + integrations: Integrations { + root: Some("~/.atomic/integrations".to_string()), + root_overridden: false, + root_error: None, + packages: vec![ + Integration { + agent: "claude-code".to_string(), + display_name: "Claude Code".to_string(), + state: IntegrationState::Installed(InstalledIntegration { + version: "1.4.0".to_string(), + installed_with: "0.19.0".to_string(), + installed_at: "2026-10-01T12:00:00+00:00".to_string(), + source_kind: "registry", + source: "https://example.atomic.storage/pkg".to_string(), + files: FileCounts { + recorded: 3, + present: 2, + missing: 1, + ..FileCounts::default() + }, + }), + }, + Integration { + agent: "cline".to_string(), + display_name: "Cline".to_string(), + state: IntegrationState::NotInstalled, + }, + Integration { + agent: "codex".to_string(), + display_name: "Codex".to_string(), + state: IntegrationState::NotInstalled, + }, + ], + }, + skills: Skills { + package: SkillsPackage::NotFound { + reason: "no synced atomic-skills package".to_string(), + }, + installed: vec![InstalledSkill { + agent: "claude-code".to_string(), + name: "atomic-vault".to_string(), + path: "~/.claude/skills/atomic-vault/SKILL.md".to_string(), + state: FileState::Modified, + version: None, + }], + }, + agents: vec![ + AgentState { + name: "claude-code".to_string(), + display_name: "Claude Code".to_string(), + enabled: Enabled::Yes, + evidence: vec![ + "Atomic hook commands present in ~/.claude/settings.json".to_string() + ], + }, + AgentState { + name: "cline".to_string(), + display_name: "Cline".to_string(), + enabled: Enabled::No, + evidence: vec![], + }, + AgentState { + name: "kiro".to_string(), + display_name: "Kiro".to_string(), + enabled: Enabled::Unknown, + evidence: vec!["integration receipt unreadable: bad json".to_string()], + }, + ], + git_shim: GitShim { + status: ShimStatus::NotApplicable, + reason: Some("not inside an Atomic workspace".to_string()), + hooks: GitHooks::NotApplicable, + }, + not_collected: vec![NotCollected { + item: "agent application versions", + reason: "not recorded", + }], + } + } + + #[test] + fn text_report_names_every_section_and_value() { + let text = render_text(&report()); + let expected = "\ +Atomic diagnostics +================== + Generated: 2026-10-28T12:00:00Z + +Atomic + Version: 0.20.0 + Install source: cargo + Platform: linux x86_64 + Workspace: none (not inside an Atomic workspace) + +Agent integrations (installed packages) + Receipts: ~/.atomic/integrations + Claude Code (claude-code) + Version: 1.4.0 + Installed: 2026-10-01T12:00:00+00:00 with atomic 0.19.0 + 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 + +Enabled agents (Atomic hooks active) + Claude Code (claude-code): yes + - Atomic hook commands present in ~/.claude/settings.json + Kiro (kiro): unknown + - integration receipt unreadable: bad json + Not enabled: cline + +Git shim + Enabled: not applicable — not inside an Atomic workspace + +Not collected + agent application versions: not recorded +"; + assert_eq!(text, expected); + } + + #[test] + fn text_report_is_plain_ascii_layout_without_control_codes() { + let text = render_text(&report()); + assert!( + !text.contains('\u{1b}'), + "no ANSI escapes in a pasted report" + ); + assert!( + text.lines().all(|l| l == l.trim_end()), + "no trailing spaces" + ); + } + + #[test] + fn shim_and_hooks_render_their_states() { + let mut report = report(); + report.workspace = Workspace::Found { + root: "~/code/app".to_string(), + }; + report.git_shim = GitShim { + status: ShimStatus::Enabled, + reason: None, + hooks: GitHooks::Inspected { + dispatchers: vec![ + Dispatcher { + hook: "post-checkout", + state: "atomic_owned", + label: "Atomic-owned dispatcher installed", + }, + Dispatcher { + hook: "pre-push", + state: "not_installed", + label: "not installed", + }, + ], + }, + }; + let text = render_text(&report); + assert!(text.contains(" Workspace: ~/code/app\n")); + assert!(text.contains(" Enabled: yes ([git.shim] enabled = true)\n")); + assert!(text.contains( + " Git hooks:\n post-checkout: Atomic-owned dispatcher installed\n \ + pre-push: not installed\n" + )); + + report.git_shim = GitShim { + status: ShimStatus::Unknown, + reason: Some("cannot load the repository configuration".to_string()), + hooks: GitHooks::NoGitRepository, + }; + let text = render_text(&report); + assert!(text + .contains(" Enabled: unknown — cannot load the repository configuration\n")); + assert!(text.contains(" Git hooks: no Git repository in this workspace\n")); + } + + #[test] + fn no_enabled_agents_is_said_outright() { + let mut report = report(); + for agent in &mut report.agents { + agent.enabled = Enabled::No; + agent.evidence.clear(); + } + let text = render_text(&report); + assert!(text.contains(" No agent has Atomic hooks enabled.\n")); + assert!(text.contains(" Not enabled: claude-code, cline, kiro\n")); + } + + #[test] + fn json_report_carries_explicit_statuses() { + let value = serde_json::to_value(report()).unwrap(); + assert_eq!(value["schema"], SCHEMA); + assert_eq!(value["workspace"]["status"], "not_found"); + assert_eq!(value["integrations"]["packages"][0]["status"], "installed"); + assert_eq!(value["integrations"]["packages"][0]["version"], "1.4.0"); + assert_eq!( + value["integrations"]["packages"][1]["status"], + "not_installed" + ); + assert_eq!(value["skills"]["package"]["status"], "not_found"); + assert!(value["skills"]["installed"][0]["version"].is_null()); + assert_eq!(value["agents"][2]["enabled"], "unknown"); + assert_eq!(value["git_shim"]["status"], "not_applicable"); + assert_eq!(value["git_shim"]["hooks"]["status"], "not_applicable"); + } +} diff --git a/atomic-cli/src/commands/git/hook_dispatchers.rs b/atomic-cli/src/commands/git/hook_dispatchers.rs index 5de9a7e3..d78cbde6 100644 --- a/atomic-cli/src/commands/git/hook_dispatchers.rs +++ b/atomic-cli/src/commands/git/hook_dispatchers.rs @@ -9,12 +9,13 @@ use std::fs; use std::io::ErrorKind; -use std::path::Path; +use std::path::{Path, PathBuf}; use super::hooks::{ canonical_root, git_error, git_hook_context, is_legacy_atomic_only, is_owned_dispatcher, - print_unmanaged_instructions, + print_unmanaged_instructions, GitHookContext, }; +use super::observation::{observe_git, GitObservation}; use crate::error::CliResult; use crate::output::{print_info, print_warning}; @@ -147,41 +148,133 @@ fn remove_owned_hook(path: &Path) -> CliResult { pub(crate) fn show_status(root: &Path) -> CliResult<()> { let root = canonical_root(root)?; let context = git_hook_context(&root)?; - if let Some(custom_hooks_path) = context.custom_hooks_path { - for hook_name in ATOMIC_DISPATCHER_HOOKS { - print_info(&format!( - "{hook_name}: externally managed through core.hooksPath '{}'", - custom_hooks_path.display() - )); + match dispatcher_states(&context)? { + DispatcherReport::External { hooks_path } => { + for hook_name in ATOMIC_DISPATCHER_HOOKS { + print_info(&format!( + "{hook_name}: externally managed through core.hooksPath '{}'", + hooks_path.display() + )); + } + } + DispatcherReport::Inspected(hooks) => { + for hook in hooks { + print_info(&format!( + "{}: {} ({})", + hook.name, + hook.state.label(), + hook.path.display() + )); + } } - return Ok(()); } + Ok(()) +} - let hooks_dir = context.common_dir.join("hooks"); - for hook_name in ATOMIC_DISPATCHER_HOOKS { - let path = hooks_dir.join(hook_name); - print_info(&format!( - "{hook_name}: {} ({})", - hook_status(&path)?, - path.display() - )); +/// Where the shim's dispatchers live, and the state of each one. +#[derive(Debug)] +pub(crate) enum DispatcherReport { + /// A custom `core.hooksPath` is set; Atomic never manages hooks there. + External { hooks_path: PathBuf }, + /// One entry per hook in [`ATOMIC_DISPATCHER_HOOKS`], in that order. + Inspected(Vec), +} + +#[derive(Debug)] +pub(crate) struct DispatcherHook { + pub(crate) name: &'static str, + pub(crate) path: PathBuf, + pub(crate) state: HookState, +} + +/// What occupies one hook path. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum HookState { + NotInstalled, + AtomicOwned, + UnmanagedSymlink, + UnmanagedNonFile, + Unmanaged, + UnmanagedUnreadable, +} + +impl HookState { + /// The wording `atomic git hooks status` prints. + pub(crate) fn label(self) -> &'static str { + match self { + Self::NotInstalled => "not installed", + Self::AtomicOwned => "Atomic-owned dispatcher installed", + Self::UnmanagedSymlink => "unmanaged symlink", + Self::UnmanagedNonFile => "unmanaged non-file", + Self::Unmanaged => "unmanaged hook installed", + Self::UnmanagedUnreadable => "unmanaged unreadable hook", + } + } + + /// Stable machine-readable key. + pub(crate) fn code(self) -> &'static str { + match self { + Self::NotInstalled => "not_installed", + Self::AtomicOwned => "atomic_owned", + Self::UnmanagedSymlink => "unmanaged_symlink", + Self::UnmanagedNonFile => "unmanaged_non_file", + Self::Unmanaged => "unmanaged", + Self::UnmanagedUnreadable => "unmanaged_unreadable", + } } - Ok(()) } -fn hook_status(path: &Path) -> CliResult<&'static str> { +/// Inspect the dispatchers of the Git repository colocated with `root`, or +/// `None` when there is no Git repository there. Read-only. +pub(crate) fn inspect_dispatchers(root: &Path) -> CliResult> { + let root = canonical_root(root)?; + match observe_git(&root) { + Ok(GitObservation::NoGit { .. }) => return Ok(None), + Ok(GitObservation::Repository(_)) => {} + Err(error) => { + return Err(git_error(format!( + "cannot resolve Git administrative paths: {error}" + ))) + } + } + dispatcher_states(&git_hook_context(&root)?).map(Some) +} + +/// Inspect every dispatcher path without changing anything. +fn dispatcher_states(context: &GitHookContext) -> CliResult { + if let Some(hooks_path) = &context.custom_hooks_path { + return Ok(DispatcherReport::External { + hooks_path: hooks_path.clone(), + }); + } + let hooks_dir = context.common_dir.join("hooks"); + ATOMIC_DISPATCHER_HOOKS + .into_iter() + .map(|name| { + let path = hooks_dir.join(name); + Ok(DispatcherHook { + name, + state: hook_status(&path)?, + path, + }) + }) + .collect::>() + .map(DispatcherReport::Inspected) +} + +fn hook_status(path: &Path) -> CliResult { match fs::symlink_metadata(path) { - Err(error) if error.kind() == ErrorKind::NotFound => Ok("not installed"), + Err(error) if error.kind() == ErrorKind::NotFound => Ok(HookState::NotInstalled), Err(error) => Err(git_error(format!( "cannot inspect hook '{}': {error}", path.display() ))), - Ok(metadata) if metadata.file_type().is_symlink() => Ok("unmanaged symlink"), - Ok(metadata) if !metadata.file_type().is_file() => Ok("unmanaged non-file"), + Ok(metadata) if metadata.file_type().is_symlink() => Ok(HookState::UnmanagedSymlink), + Ok(metadata) if !metadata.file_type().is_file() => Ok(HookState::UnmanagedNonFile), Ok(_) => Ok(match fs::read(path) { - Ok(content) if is_owned_dispatcher(&content) => "Atomic-owned dispatcher installed", - Ok(_) => "unmanaged hook installed", - Err(_) => "unmanaged unreadable hook", + Ok(content) if is_owned_dispatcher(&content) => HookState::AtomicOwned, + Ok(_) => HookState::Unmanaged, + Err(_) => HookState::UnmanagedUnreadable, }), } } @@ -268,17 +361,20 @@ mod tests { fn hook_status_classifies_missing_owned_and_foreign_hooks() { let dir = TempDir::new().unwrap(); assert_eq!( - hook_status(&dir.path().join("missing")).unwrap(), + hook_status(&dir.path().join("missing")).unwrap().label(), "not installed" ); let owned = dir.path().join("owned"); fs::write(&owned, OWNED).unwrap(); assert_eq!( - hook_status(&owned).unwrap(), + hook_status(&owned).unwrap().label(), "Atomic-owned dispatcher installed" ); let foreign = dir.path().join("foreign"); fs::write(&foreign, CUSTOM).unwrap(); - assert_eq!(hook_status(&foreign).unwrap(), "unmanaged hook installed"); + assert_eq!( + hook_status(&foreign).unwrap().label(), + "unmanaged hook installed" + ); } } diff --git a/atomic-cli/src/commands/mod.rs b/atomic-cli/src/commands/mod.rs index 8b2dd558..5d76c4cc 100644 --- a/atomic-cli/src/commands/mod.rs +++ b/atomic-cli/src/commands/mod.rs @@ -75,6 +75,7 @@ pub mod compact; pub mod complete; pub mod completions; pub mod conflicts; +pub mod diagnostics; pub mod diff; pub mod doctor; pub mod init; @@ -150,6 +151,7 @@ pub use clone::Clone; pub use compact::Compact; pub use completions::Completions; pub use conflicts::Conflicts; +pub use diagnostics::Diagnostics; pub use diff::Diff; pub use doctor::Doctor; pub use git::Git; diff --git a/atomic-cli/src/logging/mod.rs b/atomic-cli/src/logging/mod.rs index 6909b545..e741e7c9 100644 --- a/atomic-cli/src/logging/mod.rs +++ b/atomic-cli/src/logging/mod.rs @@ -16,7 +16,7 @@ //! The `log` macros the crates already use reach both outputs unchanged. mod file_format; -mod redact; +pub(crate) mod redact; mod retention; mod terminal; diff --git a/atomic-cli/src/logging/redact.rs b/atomic-cli/src/logging/redact.rs index 3f159ac0..b137756e 100644 --- a/atomic-cli/src/logging/redact.rs +++ b/atomic-cli/src/logging/redact.rs @@ -5,7 +5,7 @@ /// name the URL they failed on, remote URLs can carry credentials in either /// place, and an "invalid URL" error may quote one too malformed to parse, /// so this over-redacts rather than parsing. -pub(super) fn urls(text: &str) -> String { +pub(crate) fn urls(text: &str) -> String { let mut out = String::with_capacity(text.len()); let mut rest = text; while let Some(at) = rest.find("://") { diff --git a/atomic-cli/src/main.rs b/atomic-cli/src/main.rs index eca574ee..50f20b2b 100644 --- a/atomic-cli/src/main.rs +++ b/atomic-cli/src/main.rs @@ -75,6 +75,7 @@ use commands::{ Compact, Completions, Conflicts, + Diagnostics, Diff, Doctor, Git, @@ -493,6 +494,21 @@ enum Commands { /// such as backfilling the dependency index for legacy repositories. Doctor(Doctor), + /// Print a read-only support report. + /// + /// Reports the Atomic version, installed agent integrations and skills + /// with their versions, which agents have Atomic hooks enabled, and + /// whether the Git shim is enabled. Changes nothing, needs no network, + /// and works outside a workspace. + /// + /// # Examples + /// + /// ```text + /// atomic diagnostics + /// atomic diagnostics --json + /// ``` + Diagnostics(Diagnostics), + /// Reclaim unused space in the repository database. Compact(Compact), @@ -1045,6 +1061,7 @@ fn main() { Commands::Blame(blame) => blame.run(), Commands::Doctor(doctor) => doctor.run(), + Commands::Diagnostics(diagnostics) => diagnostics.run(), Commands::Compact(compact) => compact.run(), Commands::Git(git) => git.run(), diff --git a/atomic-cli/tests/it/diagnostics_integration_test.rs b/atomic-cli/tests/it/diagnostics_integration_test.rs new file mode 100644 index 00000000..c484ab6d --- /dev/null +++ b/atomic-cli/tests/it/diagnostics_integration_test.rs @@ -0,0 +1,207 @@ +//! `atomic diagnostics` end to end: a hermetic home, the real binary. +#![cfg(not(windows))] + +use std::path::Path; +use std::process::{Command, Output}; + +use serde_json::Value; +use tempfile::TempDir; + +struct Fixture { + work: TempDir, + home: TempDir, +} + +impl Fixture { + fn new() -> Self { + Self { + work: tempfile::tempdir().unwrap(), + home: tempfile::tempdir().unwrap(), + } + } + + fn run(&self, args: &[&str]) -> Output { + let mut command = Command::new(env!("CARGO_BIN_EXE_atomic")); + for (name, _) in std::env::vars_os() { + if name.to_string_lossy().starts_with("ATOMIC_") { + command.env_remove(name); + } + } + command + .args(args) + .current_dir(self.work.path()) + .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("GIT_CONFIG_NOSYSTEM", "1") + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .env("NO_COLOR", "1") + .output() + .expect("run atomic") + } + + fn ok(&self, args: &[&str]) -> String { + let output = self.run(args); + assert!(output.status.success(), "{args:?}: {output:?}"); + String::from_utf8(output.stdout).unwrap() + } + + fn json(&self) -> Value { + let text = self.ok(&["diagnostics", "--json"]); + serde_json::from_str(&text) + .unwrap_or_else(|error| panic!("one JSON document expected: {error}: {text}")) + } + + /// An installed integration whose recorded file is still on disk, and + /// whose settings file carries its hook command. + fn install_integration(&self, agent: &str, version: &str) { + let home = self.home.path(); + let file = home.join(".claude/skills/atomic-vault/SKILL.md"); + let body = "---\nname: atomic-vault\nversion: 2.0.0\n---\n"; + std::fs::create_dir_all(file.parent().unwrap()).unwrap(); + std::fs::write(&file, body).unwrap(); + let settings = home.join(".claude/settings.json"); + std::fs::write( + &settings, + r#"{"hooks":{"Stop":[{"hooks":[{"command":"atomic agent hooks claude-code stop"}]}]}}"#, + ) + .unwrap(); + let receipt = serde_json::json!({ + "schema": 1, + "agent": agent, + "version": version, + "cli_version": "0.19.0", + "installed_at": "2026-10-01T12:00:00+00:00", + "source": "https://token:secret@example.com/pkg", + "files": [{ + "dst": file, + "blake3": blake3::hash(body.as_bytes()).to_hex().to_string(), + }], + "settings": [{ + "target": settings, + "hooks_key": "hooks", + "command_prefix": "atomic agent hooks claude-code", + }], + }); + let dir = home.join(".atomic/integrations").join(agent); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("receipt.json"), receipt.to_string()).unwrap(); + } +} + +fn find<'v>(list: &'v Value, key: &str, name: &str) -> &'v Value { + list.as_array() + .unwrap() + .iter() + .find(|entry| entry[key] == name) + .unwrap_or_else(|| panic!("{name} listed in {list}")) +} + +#[test] +fn outside_a_workspace_the_report_still_succeeds_with_what_it_can_read() { + let fixture = Fixture::new(); + let report = fixture.json(); + + assert_eq!(report["schema"], 1); + assert!(report["atomic"]["version"] + .as_str() + .unwrap() + .starts_with(env!("CARGO_PKG_VERSION"))); + assert_eq!(report["workspace"]["status"], "not_found"); + assert_eq!(report["git_shim"]["status"], "not_applicable"); + assert_eq!(report["skills"]["package"]["status"], "not_found"); + assert_eq!( + find(&report["integrations"]["packages"], "agent", "claude-code")["status"], + "not_installed" + ); + assert_eq!( + find(&report["agents"], "name", "claude-code")["enabled"], + "no" + ); + + let text = fixture.ok(&["diagnostics"]); + assert!(text.starts_with("Atomic diagnostics\n")); + assert!(text.contains(" Workspace: none (not inside an Atomic workspace)\n")); +} + +#[test] +fn installed_integration_and_enabled_agent_are_reported_separately_and_redacted() { + let fixture = Fixture::new(); + fixture.install_integration("claude-code", "1.4.0"); + + let report = fixture.json(); + let claude = find(&report["integrations"]["packages"], "agent", "claude-code"); + assert_eq!(claude["status"], "installed"); + assert_eq!(claude["version"], "1.4.0"); + assert_eq!(claude["files"]["present"], 1); + assert_eq!(claude["source"], "https://***@example.com/pkg"); + assert_eq!( + find(&report["agents"], "name", "claude-code")["enabled"], + "yes" + ); + + let skill = &report["skills"]["installed"][0]; + assert_eq!(skill["name"], "atomic-vault"); + assert_eq!(skill["version"], "2.0.0"); + assert_eq!(skill["path"], "~/.claude/skills/atomic-vault/SKILL.md"); + + let everything = format!("{report}{}", fixture.ok(&["diagnostics"])); + assert!( + !everything.contains("secret"), + "credentials never reach the report" + ); + let home = fixture.home.path().display().to_string(); + assert!(!everything.contains(&home), "home is shown as ~"); +} + +#[test] +fn inside_a_git_backed_workspace_the_shim_is_reported_and_nothing_changes() { + let fixture = Fixture::new(); + assert!(Command::new("git") + .args(["init", "-q"]) + .current_dir(fixture.work.path()) + .status() + .unwrap() + .success()); + fixture.ok(&["init", "--view", "main"]); + let before = snapshot(fixture.work.path()); + + let report = fixture.json(); + assert_eq!(report["workspace"]["status"], "found"); + assert_eq!(report["git_shim"]["status"], "disabled"); + let dispatchers = report["git_shim"]["hooks"]["dispatchers"] + .as_array() + .unwrap(); + assert_eq!(dispatchers.len(), 5); + assert!(dispatchers.iter().all(|d| d["state"] == "not_installed")); + fixture.ok(&["diagnostics"]); + + assert_eq!( + before, + snapshot(fixture.work.path()), + "diagnostics is read-only" + ); +} + +/// Every file under `root` with its length and modification time. +fn snapshot(root: &Path) -> Vec<(String, u64, std::time::SystemTime)> { + let mut entries = Vec::new(); + let mut stack = vec![root.to_path_buf()]; + while let Some(dir) = stack.pop() { + for entry in std::fs::read_dir(&dir).unwrap().flatten() { + let meta = entry.metadata().unwrap(); + if meta.is_dir() { + stack.push(entry.path()); + } else { + entries.push(( + entry.path().display().to_string(), + meta.len(), + meta.modified().unwrap(), + )); + } + } + } + entries.sort(); + entries +} diff --git a/atomic-cli/tests/it/main.rs b/atomic-cli/tests/it/main.rs index e3bd271a..d98588ff 100644 --- a/atomic-cli/tests/it/main.rs +++ b/atomic-cli/tests/it/main.rs @@ -19,6 +19,7 @@ mod clone_sidecar_integration_test; mod compact_service_integration_test; mod concurrent_intent_reads_test; mod cross_stream_matrix_test; +mod diagnostics_integration_test; mod git_adoption_cb7b_test; mod git_anchor_cb7a_test; mod git_binding_cb6a_test; diff --git a/docs/README.md b/docs/README.md index debda40e..d81c1a93 100644 --- a/docs/README.md +++ b/docs/README.md @@ -7,6 +7,7 @@ Welcome to the Atomic VCS documentation. This directory contains comprehensive d | Document | Description | Audience | |----------|-------------|----------| | [CLI Reference](../atomic-cli/README.md) | Complete command reference for the `atomic` CLI | Users, Everyone | +| [Support Diagnostics](./diagnostics.md) | `atomic diagnostics`: a read-only, paste-ready support report | Users, Support | | [Hook Health and Session Logs](./hook-health.md) | Diagnose hook failures and inspect per-session health | Users, Integration developers | | [Shim Operating Guide](./shim-operating-guide.md) | Git shim enable/disable, vault projection policy, trust, recovery, privacy, and observability (CB-13C; exercised against the shipping CLI) | Users, Agents | | [Stack Walkthrough](./walkthrough-stacks.md) | Hands-on tutorial for stacks, apply, and stash | Users, Contributors | @@ -23,6 +24,7 @@ Welcome to the Atomic VCS documentation. This directory contains comprehensive d - **New to Atomic?** Start with [COMPARISON.md](./COMPARISON.md) to understand what makes Atomic different - **Using the CLI?** See the [CLI Reference](../atomic-cli/README.md) for every command and option +- **Asking for support?** Run `atomic diagnostics` and paste the output — see [Support Diagnostics](./diagnostics.md) - **Are agent hooks working?** See [Hook Health and Session Logs](./hook-health.md) for liveness, failures, and session correlation - **Learning stacks?** Walk through the [Stack Walkthrough](./walkthrough-stacks.md) step by step - **AI audit trail?** Read the [Attestation Design](./attestation-design.md) for graph-level cost and compliance tracking diff --git a/docs/diagnostics.md b/docs/diagnostics.md new file mode 100644 index 00000000..666ff1f1 --- /dev/null +++ b/docs/diagnostics.md @@ -0,0 +1,83 @@ +# Support Diagnostics + +`atomic diagnostics` prints a report to paste into a support conversation. It +collects what support otherwise asks for one follow-up at a time. + +```sh +atomic diagnostics # paste-ready text +atomic diagnostics --json # the same facts as one JSON document +``` + +The command is read-only. It changes no configuration, attempts no repair, and +uses no network. Outside an Atomic workspace it still reports everything that +does not depend on a workspace. The exit status is 0 even when values are +unknown. The only file it touches is the command log that every `atomic` +invocation appends to. + +## What it reports + +| Section | Source | +|---|---| +| 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 | +| Enabled agents | Whether Atomic hooks are live in each agent's configuration, with the evidence | +| 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 +has a receipt. An agent is *enabled* when Atomic's hook commands are present in +its live configuration. Hooks can exist without a receipt (built-in hooks), and a +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. + +Every unavailable value is reported as unknown or not found, with a reason. +Values are never inferred. + +## 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. + +## Limits + +- **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 + 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 + 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. + +## Was a record made by an agent? + +That is a property of one change, so it is not part of this report. Atomic does +record it: + +- Changes recorded by agent hooks carry a hashed `SessionEnvelope` (agent name, + session ID, turn number) and hashed AI `Provenance` (vendor, model, tool, + session ID, and `agent_name` / `turn_number` metadata). +- A manual `atomic record` carries AI provenance only when `--ai-assisted` or + the `ATOMIC_AI_*` environment variables are set. It never carries a session + envelope. +- A change with neither shows only that no agent provenance was recorded. An + agent that ran `atomic record` through a shell without those flags looks the + same as a manual record. + +To check a specific record, `atomic change --format json` shows +`has_provenance` and `provenance`. That output also includes the unhashed turn +transcript, so do not paste it into a support conversation as-is. From a33336162d6e81bb2dca78a8e585bceb1b8757b0 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 02:16:28 +0000 Subject: [PATCH 2/2] fix: join diagnostics paths after `~` with `/` on every platform On Windows the remainder after `~` was rendered with the native separator, producing `~/.x\settings.json` and failing the receipt settings test on the Windows runner. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Q7Qtv2GmBTRRN3Xy1jzx17 --- atomic-cli/src/commands/diagnostics/collect.rs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/atomic-cli/src/commands/diagnostics/collect.rs b/atomic-cli/src/commands/diagnostics/collect.rs index e6ccbed7..3fb0e102 100644 --- a/atomic-cli/src/commands/diagnostics/collect.rs +++ b/atomic-cli/src/commands/diagnostics/collect.rs @@ -765,11 +765,18 @@ fn collect_git_shim(workspace: &Result, String>, home: Option<&P } /// `path` with the home directory shown as `~`, so a pasted report does not -/// carry the user's account name. +/// 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()) { Some(rest) if rest.as_os_str().is_empty() => "~".to_string(), - Some(rest) => format!("~/{}", rest.display()), + Some(rest) => { + let parts: Vec<_> = rest + .components() + .map(|part| part.as_os_str().to_string_lossy()) + .collect(); + format!("~/{}", parts.join("/")) + } None => path.display().to_string(), } } @@ -1302,6 +1309,11 @@ mod tests { "~/.claude/settings.json" ); assert_eq!(display_path(home, Some(home)), "~"); + assert_eq!( + display_path(&home.join(".x").join("settings.json"), Some(home)), + "~/.x/settings.json", + "separators after ~ are always /" + ); assert_eq!(display_path(Path::new("/opt/x"), Some(home)), "/opt/x"); assert_eq!(display_path(Path::new("/opt/x"), None), "/opt/x"); }