1use std::collections::BTreeMap;
8use std::fmt::Write as _;
9use std::path::Path;
10
11use super::log::{self, LOG_FILE};
12use super::redact::Redactor;
13use crate::adapters::ADAPTERS;
14use crate::adapters::detect::{self, NoRegistry};
15use crate::apply::placeholder_path;
16use crate::catalog;
17use crate::env::Env;
18use crate::error::CoreError;
19use crate::fs::Fs;
20use crate::layering::projects::this_overlay;
21use crate::paths::SurjectionHome;
22use crate::remote::config::RemotesFile;
23use crate::scan::external::skillspector;
24use crate::store::{Store, utc_datetime};
25use crate::versions::{self, Registry};
26
27pub const DEFAULT_LOG_LINES: usize = 50;
29
30#[derive(Debug, Clone, Copy)]
32pub struct ReportOptions<'a> {
33 pub program: &'a str,
35 pub channel: Option<&'a str>,
38 pub log_lines: usize,
40}
41
42const FILES: [&str; 10] = [
44 "store/loadout.toml",
45 "state/machine.toml",
46 "state/ledger.json",
47 "state/ledger.key",
48 "state/remotes.toml",
49 "state/trust.json",
50 "state/scan-rules.toml",
51 "state/local-settings.toml",
52 "state/unmanaged-seen.json",
53 "logs/surjection.log",
54];
55
56const FOLDERS: [&str; 12] = [
58 "store",
59 "store/servers",
60 "store/skills",
61 "state",
62 "state/journal",
63 "state/applies",
64 "state/merge",
65 "backups",
66 "cache",
67 "tools",
68 "imports",
69 "logs",
70];
71
72pub fn build(env: &Env, fs: &dyn Fs, home: &SurjectionHome, options: &ReportOptions<'_>) -> String {
75 let mut out = String::new();
76 let _ = write_report(&mut out, env, fs, home, options);
77 Redactor::new(env, &home.path).redact(&out)
78}
79
80fn write_report(
81 out: &mut String,
82 env: &Env,
83 fs: &dyn Fs,
84 home: &SurjectionHome,
85 options: &ReportOptions<'_>,
86) -> std::fmt::Result {
87 writeln!(out, "# Surjection diagnostic report")?;
88 writeln!(out)?;
89 writeln!(out, "Generated {}.", utc_datetime(env.now()))?;
90 writeln!(
91 out,
92 "Contains versions, file names, sizes, counts, client detection and recent log lines. \
93 No secret values, file contents, remote URLs or full paths. Nothing was sent anywhere."
94 )?;
95
96 writeln!(out, "\n## Version\n")?;
97 writeln!(out, "- Program: {}", options.program)?;
98 writeln!(
99 out,
100 "- OS: {} ({})",
101 env.os().as_str(),
102 std::env::consts::ARCH
103 )?;
104 writeln!(
105 out,
106 "- Install channel: {}",
107 options.channel.unwrap_or("unknown")
108 )?;
109
110 writeln!(out, "\n## Data folder\n")?;
111 writeln!(
112 out,
113 "- Location: {} (set by: {})",
114 placeholder_path(env, &home.path, None),
115 home.source.as_str()
116 )?;
117 writeln!(
118 out,
119 "- Inside a sync folder: {}",
120 home.sync_root
121 .as_ref()
122 .map_or("no", |root| root.kind.as_str())
123 )?;
124 if !fs.is_dir(&home.path) {
125 writeln!(out, "- Not created yet.")?;
126 } else {
127 for folder in FOLDERS {
128 let path = home.path.join(folder);
129 match fs.read_dir(&path) {
130 Ok(entries) => writeln!(out, "- `{folder}/`: {} entries", entries.len())?,
131 Err(_) => writeln!(out, "- `{folder}/`: absent")?,
132 }
133 }
134 for file in FILES {
135 let path = home.path.join(file);
136 if fs.is_regular_file(&path) {
137 let size = fs.file_size(&path).unwrap_or(0);
138 writeln!(out, "- `{file}`: {}", human_size(size))?;
139 } else {
140 writeln!(out, "- `{file}`: absent")?;
141 }
142 }
143 for n in 1..=log::Rotation::DEFAULT.keep {
144 let file = format!("logs/{LOG_FILE}.{n}");
145 let path = home.path.join(&file);
146 if fs.is_regular_file(&path) {
147 let size = fs.file_size(&path).unwrap_or(0);
148 writeln!(out, "- `{file}`: {}", human_size(size))?;
149 }
150 }
151 match newer_file(fs, home) {
152 Ok(None) => writeln!(out, "- Written by a newer Surjection: no")?,
153 Ok(Some((file, found, supported))) => writeln!(
154 out,
155 "- Written by a newer Surjection: yes (`{file}` has schema {found}; this build reads up to {supported})"
156 )?,
157 Err(err) => writeln!(
158 out,
159 "- Written by a newer Surjection: {}",
160 unavailable(&err)
161 )?,
162 }
163 }
164
165 let store = Store::open(env, fs, home, options.program);
166 match &store {
167 Ok(Some(store)) => {
168 writeln!(out, "- Store schema: {}", store.identity().schema)?;
169 match store.commit_count() {
170 Ok(count) => writeln!(out, "- Store commits: {count}")?,
171 Err(err) => writeln!(out, "- Store commits: {}", unavailable(&err))?,
172 }
173 }
174 Ok(None) => writeln!(out, "- Store: not created yet")?,
175 Err(err) => writeln!(out, "- Store: {}", unavailable(err))?,
176 }
177
178 writeln!(out, "\n## Clients\n")?;
179 write_clients(out, env, fs)?;
180
181 writeln!(out, "\n## Counts\n")?;
182 write_counts(out, fs, home, &store)?;
183
184 writeln!(out, "\n## Scanners\n")?;
185 writeln!(out, "- Built-in scanner: on")?;
186 match skillspector::status(env, fs, home) {
187 Ok(status) => {
188 writeln!(
189 out,
190 "- SkillSpector: {}, {}{}",
191 if status.enabled { "on" } else { "off" },
192 status.availability.as_str(),
193 status
194 .availability
195 .runtime()
196 .map(|runtime| format!(", runtime {}", runtime.kind.as_str()))
197 .unwrap_or_default()
198 )?;
199 if let Some(version) = &status.private_uv {
200 writeln!(out, "- Private uv: {version}")?;
201 }
202 }
203 Err(err) => writeln!(out, "- SkillSpector: {}", unavailable(&err))?,
204 }
205
206 writeln!(out, "\n## Online catalogs\n")?;
207 match catalog::online(fs, home) {
208 Ok(setting) if !setting.answered => writeln!(out, "- Not answered yet (off)")?,
209 Ok(setting) => writeln!(out, "- {}", if setting.on { "On" } else { "Off" })?,
210 Err(err) => writeln!(out, "- {}", unavailable(&err))?,
211 }
212
213 let lines = log::tail(home, options.log_lines.max(200));
214 writeln!(out, "\n## Recent error codes\n")?;
215 let codes = log::error_codes(&lines);
216 if codes.is_empty() {
217 writeln!(out, "- None in the log")?;
218 }
219 for (code, count) in codes {
220 writeln!(out, "- `{code}` ({count}x)")?;
221 }
222
223 writeln!(out, "\n## Recent log lines\n")?;
224 let skip = lines.len().saturating_sub(options.log_lines);
225 if lines.len() == skip {
226 writeln!(out, "No log lines.")?;
227 } else {
228 writeln!(out, "```")?;
229 for line in &lines[skip..] {
230 writeln!(out, "{line}")?;
231 }
232 writeln!(out, "```")?;
233 }
234 Ok(())
235}
236
237fn write_clients(out: &mut String, env: &Env, fs: &dyn Fs) -> std::fmt::Result {
240 writeln!(out, "| Client | Detected | Config file |")?;
241 writeln!(out, "|---|---|---|")?;
242 let mut others = 0;
243 for spec in ADAPTERS {
244 let detected = detect::detect(spec, env, fs, &NoRegistry).detected();
245 let file = spec.mcp.as_ref().and_then(|mcp| {
246 mcp.user
247 .iter()
248 .filter_map(|location| location.resolve(env, None))
249 .find(|path| fs.is_regular_file(path))
250 });
251 if !detected && file.is_none() {
252 others += 1;
253 continue;
254 }
255 let file = file.map_or_else(
256 || "absent".to_owned(),
257 |path| format!("`{}`", placeholder_path(env, &path, None)),
258 );
259 writeln!(
260 out,
261 "| {} | {} | {file} |",
262 spec.id,
263 if detected { "yes" } else { "no" }
264 )?;
265 }
266 writeln!(
267 out,
268 "\n{others} other clients: not detected, no config file."
269 )
270}
271
272fn write_counts(
273 out: &mut String,
274 fs: &dyn Fs,
275 home: &SurjectionHome,
276 store: &Result<Option<Store<'_>>, CoreError>,
277) -> std::fmt::Result {
278 match store {
279 Ok(Some(store)) => {
280 match store.servers() {
281 Ok(servers) => writeln!(out, "- Servers: {}", servers.len())?,
282 Err(err) => writeln!(out, "- Servers: {}", unavailable(&err))?,
283 }
284 writeln!(
285 out,
286 "- Skills: {}",
287 count_dirs(fs, &home.store_dir().join("skills"))
288 )?;
289 match this_overlay(store, fs, &home.state_dir()) {
290 Ok(overlay) => writeln!(
291 out,
292 "- Projects on this machine: {}",
293 overlay
294 .and_then(|overlay| overlay.projects)
295 .map_or(0, |projects| projects.len())
296 )?,
297 Err(err) => writeln!(out, "- Projects on this machine: {}", unavailable(&err))?,
298 }
299 }
300 _ => writeln!(
301 out,
302 "- Servers: 0\n- Skills: 0\n- Projects on this machine: 0"
303 )?,
304 }
305 match RemotesFile::load(fs, &home.state_dir()) {
306 Ok(file) if file.remotes.is_empty() => writeln!(out, "- Remotes: none")?,
307 Ok(file) => {
308 let mut kinds: BTreeMap<&str, usize> = BTreeMap::new();
309 for remote in &file.remotes {
310 *kinds.entry(remote.kind.as_str()).or_default() += 1;
311 }
312 let kinds: Vec<String> = kinds
313 .into_iter()
314 .map(|(kind, count)| format!("{kind} {count}"))
315 .collect();
316 writeln!(out, "- Remotes: {}", kinds.join(", "))?;
317 }
318 Err(err) => writeln!(out, "- Remotes: {}", unavailable(&err))?,
319 }
320 Ok(())
321}
322
323fn newer_file(fs: &dyn Fs, home: &SurjectionHome) -> Result<Option<(String, i64, i64)>, CoreError> {
326 let registry = Registry::builtin();
327 Ok(versions::survey(fs, home, ®istry)?
328 .into_iter()
329 .find_map(|found| {
330 let supported = registry.kind(found.kind)?.current();
331 (found.version > supported).then(|| (found.file(), found.version, supported))
332 }))
333}
334
335fn count_dirs(fs: &dyn Fs, dir: &Path) -> usize {
336 fs.read_dir(dir)
337 .map(|entries| entries.iter().filter(|path| fs.is_dir(path)).count())
338 .unwrap_or(0)
339}
340
341fn unavailable(err: &CoreError) -> String {
342 format!("unavailable ({})", err.code().as_str())
343}
344
345fn human_size(bytes: u64) -> String {
347 const KIB: u64 = 1024;
348 if bytes < KIB {
349 format!("{bytes} B")
350 } else if bytes < KIB * KIB {
351 format!("{:.1} KiB", bytes as f64 / KIB as f64)
352 } else {
353 format!("{:.1} MiB", bytes as f64 / (KIB * KIB) as f64)
354 }
355}