dracon-system 0.112.44

Disk, process, storage, and service diagnostics for local development machines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
//! Symlink ownership management — deterministic link reconciliation.

use anyhow::Result;
use serde::Serialize;
use std::fs;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

use crate::{
    check_safe_to_delete_guard, expand_tilde, LinkCommands, LinkEntry, LinkEntryStatus,
    LinkStatusReport, SystemPolicy,
};

/// Evaluate a single link entry: check if symlink exists and points to the correct target.
pub(crate) fn evaluate_link(entry: &LinkEntry) -> LinkEntryStatus {
    let link = expand_tilde(&entry.link);
    let target = expand_tilde(&entry.target);
    let target_exists = target.exists();
    let meta = fs::symlink_metadata(&link).ok();
    let exists = meta.is_some();
    let is_symlink = meta
        .as_ref()
        .map(|m| m.file_type().is_symlink())
        .unwrap_or(false);

    let mut points_to = String::new();
    let mut in_sync = false;
    let issue = if !target_exists {
        "target_missing".to_string()
    } else if !exists {
        "link_missing".to_string()
    } else if !is_symlink {
        "path_not_symlink".to_string()
    } else {
        match fs::read_link(&link) {
            Ok(actual) => {
                let actual_abs = if actual.is_absolute() {
                    actual
                } else {
                    link.parent().unwrap_or_else(|| Path::new("/")).join(actual)
                };
                points_to = path_display(&actual_abs);
                if normalize_path(&actual_abs) == normalize_path(&target) {
                    in_sync = true;
                    "ok".to_string()
                } else {
                    "link_target_mismatch".to_string()
                }
            }
            Err(_) => "readlink_failed".to_string(),
        }
    };

    LinkEntryStatus {
        link: path_display(&link),
        target: path_display(&target),
        exists,
        is_symlink,
        target_exists,
        points_to,
        in_sync,
        issue,
    }
}

fn normalize_path(path: &Path) -> PathBuf {
    path.canonicalize()
        .unwrap_or_else(|_| lexical_normalize(path))
}

/// Lexical normalization for paths `canonicalize()` cannot resolve (a
/// missing/broken intermediate component, e.g. a link target written
/// as `~/a/../b` where `a` no longer exists): collapses `.` and `..`
/// components without touching the filesystem. ADDED 2026-08-10 (audit
/// LOW): the old fallback compared RAW strings, so equivalent forms
/// like `~/a/../b` vs `~/b` reported `link_target_mismatch` for an
/// in-sync link whenever canonicalize failed on either side.
pub(crate) fn lexical_normalize(path: &Path) -> PathBuf {
    use std::path::Component;
    let mut out: Vec<Component> = Vec::new();
    for comp in path.components() {
        match comp {
            Component::CurDir => {}
            Component::ParentDir => {
                // Pop the last normal component; if there is none (root,
                // prefix, or leading `..`), keep the `..` so paths like
                // `../../x` survive unchanged — never drop it silently.
                if matches!(out.last(), Some(Component::Normal(_))) {
                    out.pop();
                } else {
                    out.push(comp);
                }
            }
            other => out.push(other),
        }
    }
    out.iter().collect()
}

/// Build a full link status report from policy.
pub(crate) fn build_link_report(policy: &SystemPolicy) -> LinkStatusReport {
    build_link_report_with(policy, &[])
}

/// Build a link report from policy plus extra entries (daemon-owned
/// auto-relocation records). ADDED 2026-09-27 (space tiers Phase 2).
pub(crate) fn build_link_report_with(
    policy: &SystemPolicy,
    extra: &[LinkEntry],
) -> LinkStatusReport {
    let mut entries = Vec::with_capacity(policy.links.entries.len() + extra.len());
    let mut healthy = 0usize;
    let mut drifted = 0usize;
    let mut missing_target = 0usize;
    let mut missing_link = 0usize;

    for entry in policy.links.entries.iter().chain(extra.iter()) {
        let status = evaluate_link(entry);
        match status.issue.as_str() {
            "ok" => healthy += 1,
            "target_missing" => {
                drifted += 1;
                missing_target += 1;
            }
            "link_missing" => {
                drifted += 1;
                missing_link += 1;
            }
            _ => drifted += 1,
        }
        entries.push(status);
    }

    LinkStatusReport {
        total: entries.len(),
        entries,
        healthy,
        drifted,
        missing_target,
        missing_link,
        // Populated by apply_link_policy with the per-entry failures it
        // recovered from; a report-only build has none.
        errors: Vec::new(),
    }
}

pub(crate) fn backup_path_for(link: &Path) -> PathBuf {
    // FIXED 2026-08-10 (audit LOW): the pre-fix timestamp was
    // second-resolution (`as_secs()`), so two force_replace backups of
    // the same basename in one directory within the same second (same
    // link listed twice in one run, or a daemon pulse plus a manual
    // `link apply` in the same second) produced the SAME backup path
    // and `fs::rename` silently overwrote the earlier backup. Nanosecond
    // resolution plus a collision-avoidance suffix makes every backup
    // name unique.
    let ts = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    let name = link
        .file_name()
        .map(|n| n.to_string_lossy().to_string())
        .unwrap_or_else(|| "link".to_string());
    let base = format!("{name}.dracon-system-backup-{ts}");
    unique_backup_path(link.parent().unwrap_or_else(|| Path::new(".")), &base)
}

/// First free `<base>`, `<base>-1`, `<base>-2`, … path under `dir`.
/// Uses `symlink_metadata` (not `exists`) so a leftover BROKEN symlink
/// at a candidate name also counts as occupied and is skipped.
pub(crate) fn unique_backup_path(dir: &Path, base: &str) -> PathBuf {
    let mut candidate = dir.join(base);
    let mut n = 1u32;
    while fs::symlink_metadata(&candidate).is_ok() {
        candidate = dir.join(format!("{base}-{n}"));
        n += 1;
    }
    candidate
}

/// Apply link policy: create or fix symlinks according to the configuration.
///
/// FIXED 2026-10-01 (audit), three defects in one function:
/// 1. `force_replace` called the STRICT `check_safe_to_delete`, whose
///    SYSTEM_PROTECTED list contains `/home` and whose check is a DESCENDANT
///    check — so every link under `$HOME` was refused and the flag was dead
///    for every real-world link (including the one the example config ships).
///    The guard-specific variant is the right one here: it still refuses exact
///    system roots, the user's `protected_paths`, symlinks, and
///    canonicalisation failures, and only skips the /home-descendant rule that
///    exists to stop bulk tree deletion.
/// 2. A force-replaced file was renamed to a backup and THEN symlinked, with
///    no rollback: a failing `symlink(2)` left the path gone with the data
///    only in a backup.
/// 3. A `?` inside the entry loop aborted the whole batch on the first
///    failure, so later entries were never repaired and no report was built.
///    Failures are now collected per entry and the report is still returned.
pub(crate) fn apply_link_policy(
    policy: &SystemPolicy,
    force_replace: bool,
) -> Result<LinkStatusReport> {
    let mut errors: Vec<String> = Vec::new();
    for entry in &policy.links.entries {
        if let Err(e) = apply_one_link(entry, force_replace, &policy.guard.protected_paths) {
            eprintln!("✗ link {}: {e:#}", entry.link);
            errors.push(format!("{}: {e:#}", entry.link));
        }
    }

    let mut report = build_link_report(policy);
    report.errors = errors;
    Ok(report)
}

/// Put a force-replaced file back where it was after `symlink(2)` failed, so a
/// failed apply never leaves the operator with an empty path and their data
/// only in a backup. Split out so the restore logic is directly testable:
/// making `symlink(2)` itself fail mid-apply needs a race, but the restore is
/// the part that must not be wrong.
#[cfg(unix)]
fn restore_after_failed_symlink(backup: &Path, link: &Path, symlink_err: &std::io::Error) {
    match fs::rename(backup, link) {
        Ok(()) => eprintln!(
            "link {}: symlink failed ({symlink_err}); the original file was restored",
            link.display()
        ),
        Err(rb) => eprintln!(
            "link {}: symlink failed ({symlink_err}) AND restoring the backup failed ({rb}); the original file is at {}",
            link.display(),
            backup.display()
        ),
    }
}

/// Test-only seam for `restore_after_failed_symlink` (the helper is private and
/// its failure path cannot be reached from `apply_link_policy` without racing
/// the filesystem).
#[cfg(test)]
pub(crate) fn links_restore_after_failed_symlink_for_tests(
    backup: &Path,
    link: &Path,
    symlink_err: &std::io::Error,
) {
    restore_after_failed_symlink(backup, link, symlink_err);
}

/// Apply a single link entry. Errors are returned to the caller, which collects
/// them so one bad entry cannot strand the rest of the batch.
fn apply_one_link(
    entry: &LinkEntry,
    force_replace: bool,
    protected_paths: &[String],
) -> Result<()> {
    let link = expand_tilde(&entry.link);
    let target = expand_tilde(&entry.target);

    if !target.exists() {
        return Ok(());
    }

    if let Some(parent) = link.parent() {
        fs::create_dir_all(parent)?;
    }

    // Set when the original file was renamed aside, so a failed symlink(2) can
    // put the user's data back where it was.
    let mut backup_to_restore: Option<PathBuf> = None;
    let meta = fs::symlink_metadata(&link).ok();
    if let Some(meta) = meta {
        if meta.file_type().is_symlink() {
            // FIXED 2026-07-26 (audit H-13): the pre-fix code routed
            // existing symlinks through check_safe_to_delete, which
            // ALWAYS refuses symlinks — so `link apply` errored on
            // every existing symlink, including the drifted ones it
            // exists to fix (and even in-sync ones, since there was
            // no short-circuit). Removing a symlink never touches its
            // target, so remove it directly; skip entries already in
            // sync.
            if evaluate_link(entry).in_sync {
                return Ok(());
            }
            fs::remove_file(&link)?;
        } else if force_replace {
            // A force-replaced regular file is deleted (after backup),
            // so the user's protected list applies here exactly as it
            // does on every other delete path. Guard variant, not the
            // strict one — see apply_link_policy's note (1).
            let safe_link = check_safe_to_delete_guard(&link, protected_paths)?;
            let backup = backup_path_for(&link);
            fs::rename(&safe_link, &backup)?;
            backup_to_restore = Some(backup);
        } else {
            return Ok(());
        }
    }

    #[cfg(unix)]
    {
        if let Err(e) = std::os::unix::fs::symlink(&target, &link) {
            // The user's file is sitting in the backup; put it back rather than
            // leaving the path empty (see apply_link_policy's note (2)).
            if let Some(backup) = backup_to_restore {
                restore_after_failed_symlink(&backup, &link, &e);
            }
            return Err(e.into());
        }
    }
    #[cfg(not(unix))]
    {
        return Err(anyhow::anyhow!("link apply is only supported on unix"));
    }

    Ok(())
}

/// Display path relative to home if possible.
fn path_display(path: &Path) -> String {
    if let Some(home) = dirs::home_dir() {
        if let Ok(rel) = path.strip_prefix(&home) {
            return format!("~/{}", rel.display());
        }
    }
    path.display().to_string()
}

pub(crate) fn cmd_link(cmd: LinkCommands) -> Result<()> {
    use comfy_table::{presets::UTF8_FULL_CONDENSED, Cell, Color, ContentArrangement, Table};

    let (_, policy) = crate::load_system_policy()?;
    // Daemon-owned auto-relocation records merge into status/doctor so
    // automatic moves are monitored like hand-written entries.
    let auto_entries = crate::relocation_link_entries();
    match cmd {
        LinkCommands::Status { json } | LinkCommands::Doctor { json } => {
            let report = build_link_report_with(&policy, &auto_entries);
            if json {
                println!("{}", serde_json::to_string_pretty(&report)?);
            } else {
                let mut table = Table::new();
                table
                    .load_preset(UTF8_FULL_CONDENSED)
                    .set_content_arrangement(ContentArrangement::Dynamic)
                    .set_header(vec![
                        Cell::new("STATUS"),
                        Cell::new("LINK"),
                        Cell::new("TARGET"),
                        Cell::new("ISSUE"),
                    ]);

                for item in &report.entries {
                    let (icon, color) = if item.issue == "ok" {
                        ("\u{2705}", Color::Green)
                    } else if item.issue.contains("missing") || item.issue.contains("not exist") {
                        ("\u{274c}", Color::Red)
                    } else {
                        ("\u{26a0}\u{fe0f}", Color::Yellow)
                    };

                    let issue = if item.issue == "ok" {
                        String::new()
                    } else {
                        format!("\u{2192} {}", item.issue)
                    };

                    table.add_row(vec![
                        Cell::new(icon).fg(color),
                        Cell::new(&item.link),
                        Cell::new(&item.target),
                        Cell::new(issue),
                    ]);
                }

                if report.entries.is_empty() {
                    println!("No configured links");
                } else {
                    println!("{table}");
                }
                println!(
                    "{} links: {} ok, {} drifted, {} missing target, {} missing link",
                    report.total,
                    report.healthy,
                    report.drifted,
                    report.missing_target,
                    report.missing_link
                );
            }
        }
        LinkCommands::Apply {
            json,
            force_replace,
        } => {
            let report = apply_link_policy(&policy, force_replace)?;
            if json {
                println!("{}", serde_json::to_string_pretty(&report)?);
            } else {
                println!("Applied link policy.");
                println!(
                    "{} links: {} ok, {} drifted",
                    report.total, report.healthy, report.drifted
                );
            }
            // Entries that failed are listed (and present in the JSON above),
            // but the rest of the batch WAS applied — so name the failures and
            // exit non-zero instead of reporting a clean run.
            if !report.errors.is_empty() {
                if !json {
                    eprintln!();
                    eprintln!("Some entries could not be applied:");
                }
                for e in &report.errors {
                    eprintln!("  ✗ {e}");
                }
                anyhow::bail!(
                    "{} of {} link entries failed; the rest were applied",
                    report.errors.len(),
                    report.total
                );
            }
        }
    }
    Ok(())
}

/// Default roots to scan for broken symlinks.
fn default_symlink_scan_roots() -> Vec<PathBuf> {
    let home = match dirs::home_dir() {
        Some(h) => h,
        None => return Vec::new(),
    };
    let candidates = [
        home.join("Dev"),
        home.join(".dracon"),
        home.join(".local/bin"),
        home.join(".config"),
    ];
    candidates.into_iter().filter(|p| p.exists()).collect()
}

/// Information about a single broken symlink.
#[derive(Debug, Serialize)]
pub(crate) struct BrokenSymlink {
    pub(crate) path: String,
    pub(crate) target: String,
    pub(crate) target_exists: bool,
}

/// Report of broken symlinks found during scan.
#[derive(Debug, Serialize)]
pub(crate) struct BrokenSymlinkReport {
    pub(crate) roots_scanned: Vec<String>,
    pub(crate) total_scanned: usize,
    pub(crate) broken: Vec<BrokenSymlink>,
}

/// Recursively scan a directory for broken symlinks.
pub(crate) fn scan_broken_symlinks(root: &Path, max_depth: usize) -> (usize, Vec<BrokenSymlink>) {
    let mut count = 0usize;
    let mut broken = Vec::new();

    let entries = match fs::read_dir(root) {
        Ok(e) => e,
        Err(_) => return (0, Vec::new()),
    };

    for entry in entries.flatten() {
        let path = entry.path();
        let meta = match fs::symlink_metadata(&path) {
            Ok(m) => m,
            Err(_) => continue,
        };

        if meta.file_type().is_symlink() {
            count += 1;
            // CORRECTED 2026-08-10 (audit LOW): the pre-fix comments
            // claimed `fs::metadata` "doesn't follow symlinks" — it
            // DOES (that is `symlink_metadata`). The call itself is
            // right: metadata resolves the WHOLE chain, so a chain
            // (L → T → missing) fails and L is reported broken. Do
            // NOT "fix" this to `symlink_metadata` — it would report
            // the intermediate link as existing and chain-following
            // detection would silently break.
            let target = match fs::read_link(&path) {
                Ok(t) => t,
                Err(_) => continue,
            };
            // Resolve target relative to symlink's parent
            let resolved = if target.is_absolute() {
                target.clone()
            } else {
                path.parent()
                    .map(|p| p.join(&target))
                    .unwrap_or(target.clone())
            };
            // fs::metadata follows the full chain; Err = broken.
            let target_exists = fs::metadata(&resolved).is_ok();
            if !target_exists {
                broken.push(BrokenSymlink {
                    path: path.display().to_string(),
                    target: target.display().to_string(),
                    target_exists: false,
                });
            }
        } else if meta.is_dir() && max_depth > 0 {
            // Skip system dirs that are noisy / dangerous to walk
            let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
            if matches!(
                name,
                "target"
                    | "node_modules"
                    | ".git"
                    | ".cache"
                    | ".venv"
                    | "dist"
                    | "build"
                    | "archives"
            ) {
                continue;
            }
            let (sub_count, sub_broken) = scan_broken_symlinks(&path, max_depth - 1);
            count += sub_count;
            broken.extend(sub_broken);
        }
    }
    (count, broken)
}

/// Command handler for `dracon-system symlinks`.
pub(crate) fn cmd_symlinks(roots: Vec<PathBuf>, json: bool, max_depth: usize) -> Result<()> {
    use comfy_table::{presets::UTF8_FULL_CONDENSED, Cell, Color, ContentArrangement, Table};

    let roots = if roots.is_empty() {
        default_symlink_scan_roots()
    } else {
        roots
    };

    let mut total_scanned = 0usize;
    let mut all_broken: Vec<BrokenSymlink> = Vec::new();
    let mut root_strings: Vec<String> = Vec::new();

    for root in &roots {
        root_strings.push(path_display(root));
        let (count, broken) = scan_broken_symlinks(root, max_depth);
        total_scanned += count;
        all_broken.extend(broken);
    }

    if json {
        let report = BrokenSymlinkReport {
            roots_scanned: root_strings,
            total_scanned,
            broken: all_broken,
        };
        println!("{}", serde_json::to_string_pretty(&report)?);
    // FIXED 2026-09-27 (audit rework round 4, F84): `else { if .. }`
    // is `collapsible_else_if` on the pinned MSRV toolchain. Collapsed;
    // behaviour is identical.
    } else if all_broken.is_empty() {
        println!(
            "\u{2705} Scanned {} symlinks across {} root(s) — no broken links found",
            total_scanned,
            root_strings.len()
        );
    } else {
        let mut table = Table::new();
        table
            .load_preset(UTF8_FULL_CONDENSED)
            .set_content_arrangement(ContentArrangement::Dynamic)
            .set_header(vec![
                Cell::new("STATUS"),
                Cell::new("BROKEN LINK"),
                Cell::new("TARGET"),
            ]);
        for item in &all_broken {
            table.add_row(vec![
                Cell::new("\u{274c}").fg(Color::Red),
                Cell::new(&item.path),
                Cell::new(&item.target),
            ]);
        }
        println!("{table}");
        println!(
            "\u{274c} Found {} broken symlink(s) out of {} scanned across {} root(s)",
            all_broken.len(),
            total_scanned,
            root_strings.len()
        );
    }
    Ok(())
}