hyalo-core 0.7.1

Core library for hyalo — frontmatter parsing, querying, and mutation for Markdown files
Documentation
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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
//! Vault index abstraction — decouples commands from their data source.
//!
//! The [`VaultIndex`] trait provides a uniform interface over pre-scanned vault
//! data. Commands program against this trait and don't know whether data came
//! from a live filesystem scan ([`ScannedIndex`]) or a serialized snapshot.

use anyhow::{Context, Result};
use indexmap::IndexMap;
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::time::SystemTime;

use crate::filter::extract_tags;
use crate::frontmatter;
use crate::link_graph::{FileLinks, LinkGraph, LinkGraphVisitor};
use crate::links::Link;
use crate::scanner::{self, FileVisitor, FrontmatterCollector, ScanAction};
use crate::tasks::TaskExtractor;
use crate::types::{FindTaskInfo, OutlineSection, TaskCount};

// ---------------------------------------------------------------------------
// IndexEntry
// ---------------------------------------------------------------------------

/// Per-file pre-scanned data stored in the index.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IndexEntry {
    /// Vault-relative path (forward slashes).
    pub rel_path: String,
    /// ISO 8601 mtime string.
    pub modified: String,
    /// Raw frontmatter properties.
    pub properties: IndexMap<String, serde_json::Value>,
    /// Extracted tags (from properties).
    pub tags: Vec<String>,
    /// Document outline sections.
    pub sections: Vec<OutlineSection>,
    /// Task checkboxes with section context.
    pub tasks: Vec<FindTaskInfo>,
    /// Outbound links with 1-based line numbers.
    pub links: Vec<(usize, Link)>,
}

// ---------------------------------------------------------------------------
// VaultIndex trait
// ---------------------------------------------------------------------------

/// Abstraction over how vault data is obtained.
/// Commands program against this trait, not a concrete data source.
pub trait VaultIndex {
    /// All entries in the index, in vault-relative path order.
    fn entries(&self) -> &[IndexEntry];

    /// Look up a single file by vault-relative path.
    fn get(&self, rel_path: &str) -> Option<&IndexEntry>;

    /// The pre-built link graph for backlink lookups.
    fn link_graph(&self) -> &LinkGraph;
}

// ---------------------------------------------------------------------------
// ScanOptions — controls what ScannedIndex::build scans
// ---------------------------------------------------------------------------

/// Controls which parts of each file are scanned during index building.
///
/// When `scan_body` is `false`, only YAML frontmatter is read — sections, tasks,
/// and links fields in [`IndexEntry`] will be empty `Vec`s. The [`LinkGraph`]
/// will be empty.  This is an optimization for commands that only need
/// frontmatter data (e.g. `properties summary`, `tags summary`,
/// `find --property status=planned` without body fields).
#[derive(Debug, Clone, Copy)]
pub struct ScanOptions {
    /// When false, only frontmatter is read.
    pub scan_body: bool,
}

// ---------------------------------------------------------------------------
// ScannedIndex — live filesystem scan
// ---------------------------------------------------------------------------

/// A vault index built by scanning files from disk.
///
/// This extracts the per-file scan logic that was previously inlined in each
/// command (`find`, `summary`, etc.) into a reusable builder behind the
/// [`VaultIndex`] trait. No new functionality — it's a refactor of existing
/// scanning patterns.
pub struct ScannedIndex {
    entries: Vec<IndexEntry>,
    /// Fast path → index lookup built at construction time.
    path_index: HashMap<String, usize>,
    graph: LinkGraph,
}

/// Warning produced during index build (e.g. malformed YAML frontmatter).
pub struct IndexWarning {
    /// Vault-relative path of the file that was skipped.
    pub rel_path: String,
    /// Human-readable error message.
    pub message: String,
}

/// Result of building a [`ScannedIndex`].
pub struct ScannedIndexBuild {
    /// The built index.
    pub index: ScannedIndex,
    /// Files that were skipped (e.g. malformed frontmatter).
    pub warnings: Vec<IndexWarning>,
}

impl ScannedIndex {
    /// Build an index by scanning a list of files from disk.
    ///
    /// `files` is a slice of `(full_path, rel_path)` pairs, as returned by
    /// `collect_files` or `discover_files`. Each file is scanned in a single
    /// pass with multiple visitors.
    ///
    /// `site_prefix` is passed through to the link graph builder for resolving
    /// absolute links.
    pub fn build(
        files: &[(PathBuf, String)],
        site_prefix: Option<&str>,
        options: &ScanOptions,
    ) -> Result<ScannedIndexBuild> {
        let mut entries = Vec::with_capacity(files.len());
        let mut file_links_vec: Vec<FileLinks> = Vec::with_capacity(files.len());
        let mut warnings: Vec<IndexWarning> = Vec::new();

        let results: Vec<Result<(IndexEntry, Option<FileLinks>)>> = files
            .par_iter()
            .map(|(full_path, rel_path)| scan_one_file(full_path, rel_path, options.scan_body))
            .collect();

        for (i, result) in results.into_iter().enumerate() {
            match result {
                Ok((entry, file_links)) => {
                    entries.push(entry);
                    if let Some(fl) = file_links {
                        file_links_vec.push(fl);
                    }
                }
                Err(e) if frontmatter::is_parse_error(&e) => {
                    warnings.push(IndexWarning {
                        rel_path: files[i].1.clone(),
                        message: e.to_string(),
                    });
                }
                Err(e) => return Err(e),
            }
        }

        // Sort entries by vault-relative path so VaultIndex::entries() guarantees
        // a stable, deterministic order (as documented on the trait).
        entries.sort_by(|a, b| a.rel_path.cmp(&b.rel_path));

        let graph = if options.scan_body {
            let graph_build = LinkGraph::from_file_links(file_links_vec, site_prefix);
            graph_build.graph
        } else {
            LinkGraph::default()
        };

        // Build path_index AFTER sorting so indices remain valid.
        let path_index: HashMap<String, usize> = entries
            .iter()
            .enumerate()
            .map(|(i, e)| (e.rel_path.clone(), i))
            .collect();

        Ok(ScannedIndexBuild {
            index: ScannedIndex {
                entries,
                path_index,
                graph,
            },
            warnings,
        })
    }
}

impl VaultIndex for ScannedIndex {
    fn entries(&self) -> &[IndexEntry] {
        &self.entries
    }

    fn get(&self, rel_path: &str) -> Option<&IndexEntry> {
        self.path_index.get(rel_path).map(|&i| &self.entries[i])
    }

    fn link_graph(&self) -> &LinkGraph {
        &self.graph
    }
}

// ---------------------------------------------------------------------------
// SnapshotIndex — MessagePack-serialized snapshot
// ---------------------------------------------------------------------------

/// Metadata header embedded in every snapshot file.
#[derive(Debug, Serialize, Deserialize)]
struct SnapshotHeader {
    /// Canonical vault directory path (informational; not re-validated on load).
    vault_dir: String,
    /// Site prefix used when building the index (informational).
    site_prefix: Option<String>,
    /// Unix timestamp (seconds) when the snapshot was created.
    created_at: u64,
    /// PID of the process that created this snapshot.
    pid: u32,
}

/// Internal serialization envelope — header + entries + graph.
#[derive(Serialize, Deserialize)]
struct SnapshotData {
    header: SnapshotHeader,
    entries: Vec<IndexEntry>,
    graph: LinkGraph,
}

/// Borrowed variant used only for serialization — avoids cloning all entries.
#[derive(Serialize)]
struct SnapshotDataRef<'a> {
    header: SnapshotHeader,
    entries: &'a [IndexEntry],
    graph: &'a LinkGraph,
}

/// A vault index loaded from a MessagePack snapshot file.
///
/// Created by [`SnapshotIndex::save`] and loaded by [`SnapshotIndex::load`].
/// Implements [`VaultIndex`] so commands can use it transparently.
pub struct SnapshotIndex {
    entries: Vec<IndexEntry>,
    /// Fast path → index lookup built after deserialization.
    path_index: HashMap<String, usize>,
    graph: LinkGraph,
    header: SnapshotHeader,
}

impl SnapshotIndex {
    // ------------------------------------------------------------------
    // Mutation helpers — update entries in-place after a mutation command
    // ------------------------------------------------------------------

    /// Remove an entry by vault-relative path (for `mv` old path).
    pub fn remove_entry(&mut self, rel_path: &str) {
        if let Some(&idx) = self.path_index.get(rel_path) {
            self.entries.remove(idx);
            self.rebuild_path_index();
        }
    }

    /// Insert a new entry (for `mv` new path). Maintains sorted order.
    pub fn insert_entry(&mut self, entry: IndexEntry) {
        let pos = self
            .entries
            .binary_search_by(|e| e.rel_path.cmp(&entry.rel_path))
            .unwrap_or_else(|i| i);
        self.entries.insert(pos, entry);
        self.rebuild_path_index();
    }

    /// Get a mutable reference to an entry by path.
    pub fn get_mut(&mut self, rel_path: &str) -> Option<&mut IndexEntry> {
        self.path_index
            .get(rel_path)
            .copied()
            .map(|i| &mut self.entries[i])
    }

    /// Get a mutable reference to the link graph for in-place updates.
    pub fn graph_mut(&mut self) -> &mut LinkGraph {
        &mut self.graph
    }

    /// Re-scan a single file and replace its index entry.
    ///
    /// Returns the `FileLinks` for the re-scanned file so the caller can
    /// update the link graph separately. Returns `Ok(None)` if the file
    /// is not in the index.
    pub(crate) fn rescan_entry(&mut self, dir: &Path, rel_path: &str) -> Result<Option<FileLinks>> {
        let Some(&idx) = self.path_index.get(rel_path) else {
            return Ok(None);
        };
        let full_path = dir.join(rel_path);
        let (entry, file_links) = scan_one_file(&full_path, rel_path, true)?;
        self.entries[idx] = entry;
        Ok(file_links)
    }

    /// Re-scan a single file from disk and replace its index entry in-place.
    ///
    /// This updates the entry's properties, tags, sections, tasks, links, and
    /// modified timestamp. The link graph is **not** touched — callers that
    /// need graph updates should use [`LinkGraph::rename_path`] separately.
    ///
    /// Returns `true` if the entry was found and refreshed, `false` if
    /// `rel_path` is not in the index.
    pub fn refresh_entry(&mut self, dir: &Path, rel_path: &str) -> Result<bool> {
        match self.rescan_entry(dir, rel_path)? {
            Some(_) => Ok(true),
            None => Ok(false),
        }
    }

    /// Remove an old entry, scan a file at its new path, and insert the result.
    ///
    /// This is the move/rename counterpart of [`refresh_entry`]: it removes the
    /// entry at `old_rel`, scans the file at `new_rel` from disk, and inserts the
    /// fresh entry. The link graph is **not** touched.
    ///
    /// Returns `Ok(true)` if `old_rel` was found and replaced, `Ok(false)` if
    /// `old_rel` was not in the index (in which case nothing is changed).
    pub fn replace_entry(&mut self, dir: &Path, old_rel: &str, new_rel: &str) -> Result<bool> {
        if !self.path_index.contains_key(old_rel) {
            return Ok(false);
        }
        self.remove_entry(old_rel);
        let full_path = dir.join(new_rel);
        let (entry, _file_links) = scan_one_file(&full_path, new_rel, true)?;
        self.insert_entry(entry);
        Ok(true)
    }

    /// Rebuild the path → index lookup after insertions/removals.
    fn rebuild_path_index(&mut self) {
        self.path_index = self
            .entries
            .iter()
            .enumerate()
            .map(|(i, e)| (e.rel_path.clone(), i))
            .collect();
    }

    /// Re-serialize and atomically save the (possibly mutated) snapshot.
    ///
    /// Reuses the original header's `vault_dir` and `site_prefix`.
    pub fn save_to(&self, path: &Path) -> Result<()> {
        write_snapshot(
            self,
            path,
            &self.header.vault_dir,
            self.header.site_prefix.as_deref(),
        )
    }

    // ------------------------------------------------------------------
    // Deserialization
    // ------------------------------------------------------------------

    /// Deserialize snapshot bytes into a `SnapshotIndex`, optionally printing a
    /// warning when the schema is incompatible.
    ///
    /// Returns `Ok(Some(index))` on success, `Ok(None)` on schema mismatch.
    fn load_inner(bytes: &[u8], warn: bool) -> Option<Self> {
        match rmp_serde::from_slice::<SnapshotData>(bytes) {
            Ok(data) => {
                // Entries are stored in sorted order (ScannedIndex::build sorts
                // before saving).  Re-sort here to guarantee the invariant even
                // if an older snapshot was created without sorting.
                let mut entries = data.entries;
                entries.sort_by(|a, b| a.rel_path.cmp(&b.rel_path));

                let path_index: HashMap<String, usize> = entries
                    .iter()
                    .enumerate()
                    .map(|(i, e)| (e.rel_path.clone(), i))
                    .collect();
                Some(Self {
                    entries,
                    path_index,
                    graph: data.graph,
                    header: data.header,
                })
            }
            Err(e) => {
                if warn {
                    eprintln!(
                        "warning: index file is incompatible ({e}); falling back to disk scan"
                    );
                }
                None
            }
        }
    }

    /// Load a snapshot from a MessagePack file.
    ///
    /// Returns `Ok(Some(index))` on success.
    /// Returns `Ok(None)` when the file is present but cannot be deserialized
    /// (e.g. after a hyalo upgrade that changed the schema) — callers should
    /// fall back to a disk scan. A warning is printed to stderr in this case.
    /// Returns `Err` only for hard I/O failures.
    pub fn load(path: &Path) -> Result<Option<Self>> {
        let bytes = std::fs::read(path)
            .with_context(|| format!("failed to read index file: {}", path.display()))?;
        Ok(Self::load_inner(&bytes, true))
    }

    /// Load a snapshot silently — identical to [`load`] but suppresses the
    /// incompatibility warning.  Used by `find_stale_indexes` which expects to
    /// silently skip files that cannot be deserialized.
    fn load_silent(path: &Path) -> Result<Option<Self>> {
        let bytes = std::fs::read(path)
            .with_context(|| format!("failed to read index file: {}", path.display()))?;
        Ok(Self::load_inner(&bytes, false))
    }

    /// Check whether this snapshot's header matches the expected vault settings.
    ///
    /// Returns `true` when both `vault_dir` and `site_prefix` match the stored
    /// header values.  Callers can use this to detect stale snapshots that were
    /// built for a different vault or with a different site prefix.
    pub fn validate(&self, vault_dir: &str, site_prefix: Option<&str>) -> bool {
        self.header.vault_dir == vault_dir && self.header.site_prefix.as_deref() == site_prefix
    }

    /// Save a snapshot of `index` to a MessagePack file at `path`.
    ///
    /// `vault_dir` and `site_prefix` are stored in the header for informational
    /// purposes (shown by `create-index` on load; not validated on subsequent loads).
    pub fn save(
        index: &dyn VaultIndex,
        path: &Path,
        vault_dir: &str,
        site_prefix: Option<&str>,
    ) -> Result<()> {
        write_snapshot(index, path, vault_dir, site_prefix)
    }

    /// Return header metadata: `(vault_dir, site_prefix, created_at_secs, pid)`.
    pub fn header_info(&self) -> (&str, Option<&str>, u64, u32) {
        (
            &self.header.vault_dir,
            self.header.site_prefix.as_deref(),
            self.header.created_at,
            self.header.pid,
        )
    }
}

/// Shared serialization logic for saving a snapshot index to disk.
///
/// Writes to a temporary file first, then atomically renames into place.
fn write_snapshot(
    index: &dyn VaultIndex,
    path: &Path,
    vault_dir: &str,
    site_prefix: Option<&str>,
) -> Result<()> {
    let header = SnapshotHeader {
        vault_dir: vault_dir.to_owned(),
        site_prefix: site_prefix.map(str::to_owned),
        created_at: SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0),
        pid: std::process::id(),
    };
    let data = SnapshotDataRef {
        header,
        entries: index.entries(),
        graph: index.link_graph(),
    };
    let bytes = rmp_serde::to_vec_named(&data).context("failed to serialize index")?;
    // Use a kernel-assigned temp-file name in the same directory as the
    // target to avoid a predictable path that could be exploited via a
    // pre-created symlink (symlink-substitution attack).  Placing the temp
    // file in the same directory as `path` ensures the subsequent atomic
    // rename stays on the same filesystem.
    let parent = path
        .parent()
        .context("index path has no parent directory")?;
    let mut tmp =
        tempfile::NamedTempFile::new_in(parent).context("failed to create temp file for index")?;
    tmp.write_all(&bytes)
        .context("failed to write temp index")?;
    // On persist failure, dropping `e.file` removes the temp file automatically.
    tmp.persist(path)
        .map_err(|e| e.error)
        .with_context(|| format!("failed to rename index into place: {}", path.display()))?;
    Ok(())
}

impl VaultIndex for SnapshotIndex {
    fn entries(&self) -> &[IndexEntry] {
        &self.entries
    }

    fn get(&self, rel_path: &str) -> Option<&IndexEntry> {
        self.path_index.get(rel_path).map(|&i| &self.entries[i])
    }

    fn link_graph(&self) -> &LinkGraph {
        &self.graph
    }
}

/// Check whether a PID corresponds to a running process.
///
/// On Unix this uses `kill(pid, 0)` (signal 0 is a no-op that only tests
/// existence). On all other platforms we conservatively assume the PID is
/// alive so that we never falsely claim a running process is stale.
fn is_pid_alive(pid: u32) -> bool {
    #[cfg(unix)]
    {
        // A tampered snapshot could carry a PID that exceeds `i32::MAX`.  On
        // platforms where `pid_t` is `i32` the cast would wrap, potentially
        // targeting a real process and blocking stale-index cleanup.  Treat
        // any out-of-range PID as "not alive" so the stale index is removed.
        if pid > i32::MAX as u32 {
            return false;
        }

        // SAFETY: kill(pid, 0) sends signal 0, which is a pure existence check —
        // no signal is actually delivered. The only side effect is updating errno.
        // The guard above ensures pid <= i32::MAX, so cast_signed() is lossless.
        let res = unsafe { libc::kill(pid.cast_signed(), 0) };
        if res == 0 {
            // Process exists and we have permission to signal it.
            true
        } else {
            // ESRCH means "no such process" — definitively dead.
            // EPERM means "process exists but we lack permission" — still alive.
            // Any other errno is treated as alive (conservative default).
            let errno = std::io::Error::last_os_error().raw_os_error().unwrap_or(0);
            errno != libc::ESRCH
        }
    }
    #[cfg(not(unix))]
    {
        let _ = pid;
        true
    }
}

/// Scan `dir` for `.hyalo-index` files whose creator PID is no longer running.
///
/// Returns a list of `(path, vault_dir, created_at)` tuples for stale files.
/// Files that cannot be loaded (incompatible schema, I/O error) are silently
/// skipped — they are already unreachable by the normal load path.
pub fn find_stale_indexes(dir: &Path) -> Result<Vec<(PathBuf, String, u64)>> {
    let mut stale = Vec::new();
    let Ok(read_dir) = std::fs::read_dir(dir) else {
        return Ok(stale);
    };
    for entry in read_dir {
        let entry = entry?;
        let path = entry.path();
        let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
            continue;
        };
        if !name.ends_with(".hyalo-index") {
            continue;
        }
        if let Ok(Some(idx)) = SnapshotIndex::load_silent(&path) {
            let (vault_dir, _, created_at, pid) = idx.header_info();
            if !is_pid_alive(pid) {
                stale.push((path, vault_dir.to_owned(), created_at));
            }
        }
    }
    Ok(stale)
}

// ---------------------------------------------------------------------------
// Per-file scan — single pass with multiple visitors
// ---------------------------------------------------------------------------

/// Scan a single file and return its `IndexEntry` plus optionally `FileLinks`
/// for the link graph.
///
/// When `scan_body` is `false`, only frontmatter is read — sections, tasks, and
/// links are empty, and no `FileLinks` are produced.
pub(crate) fn scan_one_file(
    full_path: &Path,
    rel_path: &str,
    scan_body: bool,
) -> Result<(IndexEntry, Option<FileLinks>)> {
    let mut fm = FrontmatterCollector::new(scan_body);

    let (sections, tasks, links, file_links) = if scan_body {
        let mut section_scanner = SectionScanner::new();
        let mut task_extractor = TaskExtractor::new();
        let mut link_visitor = LinkGraphVisitor::new(PathBuf::from(rel_path));

        scanner::scan_file_multi(
            full_path,
            &mut [
                &mut fm,
                &mut section_scanner,
                &mut task_extractor,
                &mut link_visitor,
            ],
        )?;

        let sections = section_scanner.into_sections();
        let tasks = task_extractor.into_tasks();
        let fl = link_visitor.into_file_links();
        let links_clone: Vec<(usize, Link)> = fl
            .links
            .iter()
            .map(|(line, link)| (*line, link.clone()))
            .collect();
        (sections, tasks, links_clone, Some(fl))
    } else {
        scanner::scan_file_multi(full_path, &mut [&mut fm])?;
        (Vec::new(), Vec::new(), Vec::new(), None)
    };

    let props = fm.into_props();
    let tags = extract_tags(&props);
    let modified = format_modified(full_path)?;

    let entry = IndexEntry {
        rel_path: rel_path.to_owned(),
        modified,
        properties: props,
        tags,
        sections,
        tasks,
        links,
    };

    Ok((entry, file_links))
}

/// Format a file's last-modified time as ISO 8601 UTC.
pub fn format_modified(path: &Path) -> Result<String> {
    let meta = std::fs::metadata(path)
        .with_context(|| format!("failed to read metadata for {}", path.display()))?;
    let mtime = meta
        .modified()
        .with_context(|| format!("mtime not available for {}", path.display()))?;
    let secs = mtime
        .duration_since(SystemTime::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    Ok(format_iso8601(secs))
}

/// Format Unix timestamp as ISO 8601 UTC (`YYYY-MM-DDTHH:MM:SSZ`).
pub fn format_iso8601(secs: u64) -> String {
    const SECS_PER_MIN: u64 = 60;
    const SECS_PER_HOUR: u64 = 3600;
    const SECS_PER_DAY: u64 = 86400;

    let days = secs / SECS_PER_DAY;
    let rem = secs % SECS_PER_DAY;
    let hh = rem / SECS_PER_HOUR;
    let mm = (rem % SECS_PER_HOUR) / SECS_PER_MIN;
    let ss = rem % SECS_PER_MIN;

    let z = days.cast_signed() + 719_468_i64;
    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
    let doe = (z - era * 146_097).cast_unsigned();
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
    let y = yoe.cast_signed() + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = if m <= 2 { y + 1 } else { y };

    format!("{y:04}-{m:02}-{d:02}T{hh:02}:{mm:02}:{ss:02}Z")
}

// ---------------------------------------------------------------------------
// SectionScanner — inline visitor (mirrors hyalo-cli's SectionScanner)
// ---------------------------------------------------------------------------

// We need a section scanner here in hyalo-core for the index builder.
// This is equivalent to the one in hyalo-cli/src/commands/section_scanner.rs
// but lives in core so it can be used without depending on the CLI crate.

use crate::heading::parse_atx_heading;
use crate::links;

/// State accumulated for the current section being built.
struct SectionBuilder {
    level: u8,
    heading: Option<String>,
    line: usize,
    links: Vec<String>,
    task_total: usize,
    task_done: usize,
    code_blocks: Vec<String>,
}

impl SectionBuilder {
    fn new(level: u8, heading: Option<String>, line: usize) -> Self {
        Self {
            level,
            heading,
            line,
            links: Vec::new(),
            task_total: 0,
            task_done: 0,
            code_blocks: Vec::new(),
        }
    }

    fn finish(self) -> OutlineSection {
        let tasks = if self.task_total > 0 {
            Some(TaskCount {
                total: self.task_total,
                done: self.task_done,
            })
        } else {
            None
        };
        OutlineSection {
            level: self.level,
            heading: self.heading,
            line: self.line,
            links: self.links,
            tasks,
            code_blocks: self.code_blocks,
        }
    }
}

/// Visitor that builds outline sections from body events.
struct SectionScanner {
    current: SectionBuilder,
    sections: Vec<OutlineSection>,
}

impl SectionScanner {
    fn new() -> Self {
        Self {
            current: SectionBuilder::new(0, None, 1),
            sections: Vec::new(),
        }
    }

    fn into_sections(mut self) -> Vec<OutlineSection> {
        let last = std::mem::replace(&mut self.current, SectionBuilder::new(0, None, 0));
        let finished = last.finish();
        let should_emit = finished.level > 0
            || !finished.links.is_empty()
            || finished.tasks.is_some()
            || !finished.code_blocks.is_empty();
        if should_emit {
            self.sections.push(finished);
        }
        self.sections
    }
}

impl FileVisitor for SectionScanner {
    fn on_body_line(&mut self, raw: &str, cleaned: &str, line_num: usize) -> ScanAction {
        if let Some((level, heading_text)) = parse_atx_heading(raw) {
            let finished = std::mem::replace(
                &mut self.current,
                SectionBuilder::new(level, Some(heading_text.to_owned()), line_num),
            );
            let should_emit = finished.level > 0
                || !finished.links.is_empty()
                || finished.task_total > 0
                || !finished.code_blocks.is_empty();
            if should_emit {
                self.sections.push(finished.finish());
            }
            return ScanAction::Continue;
        }

        let mut line_links: Vec<links::Link> = Vec::new();
        links::extract_links_from_text(cleaned, &mut line_links);
        for link in line_links {
            self.current.links.push(format_link_string(&link));
        }

        if let Some((_status, done)) = crate::tasks::detect_task_checkbox(raw) {
            self.current.task_total += 1;
            if done {
                self.current.task_done += 1;
            }
        }

        ScanAction::Continue
    }

    fn on_code_fence_open(&mut self, _raw: &str, language: &str, _line_num: usize) -> ScanAction {
        if !language.is_empty() {
            self.current.code_blocks.push(language.to_owned());
        }
        ScanAction::Continue
    }
}

/// Format a `Link` into a human-readable string for storage in the outline.
fn format_link_string(link: &links::Link) -> String {
    match link.kind {
        links::LinkKind::Wikilink => match &link.label {
            Some(label) if !label.is_empty() => format!("[[{}|{}]]", link.target, label),
            _ => format!("[[{}]]", link.target),
        },
        links::LinkKind::Markdown => match &link.label {
            Some(label) if !label.is_empty() => format!("[{}]({})", label, link.target),
            _ => format!("[]({})", link.target),
        },
    }
}

// ---------------------------------------------------------------------------
// Unit tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;

    macro_rules! md {
        ($s:expr) => {
            $s.strip_prefix('\n').unwrap_or($s)
        };
    }

    fn setup_vault() -> (tempfile::TempDir, Vec<(PathBuf, String)>) {
        let tmp = tempfile::tempdir().unwrap();

        fs::write(
            tmp.path().join("a.md"),
            md!(r"
---
title: Alpha
status: draft
tags:
  - rust
  - cli
---
# Introduction

See [[b]] for context.

## Tasks

- [ ] Write tests
- [x] Write code
"),
        )
        .unwrap();

        fs::write(
            tmp.path().join("b.md"),
            md!(r"
---
title: Beta
status: done
tags:
  - rust
---
# Content

See [[a]] for details.
"),
        )
        .unwrap();

        let files = vec![
            (tmp.path().join("a.md"), "a.md".to_owned()),
            (tmp.path().join("b.md"), "b.md".to_owned()),
        ];
        (tmp, files)
    }

    #[test]
    fn scanned_index_builds_entries() {
        let (_tmp, files) = setup_vault();
        let build = ScannedIndex::build(&files, None, &ScanOptions { scan_body: true }).unwrap();
        assert!(build.warnings.is_empty());
        assert_eq!(build.index.entries().len(), 2);
    }

    #[test]
    fn scanned_index_get_by_path() {
        let (_tmp, files) = setup_vault();
        let build = ScannedIndex::build(&files, None, &ScanOptions { scan_body: true }).unwrap();
        let idx = &build.index;

        let a = idx.get("a.md").unwrap();
        assert_eq!(a.tags, vec!["rust", "cli"]);
        assert_eq!(a.properties.get("status").unwrap(), "draft");

        let b = idx.get("b.md").unwrap();
        assert_eq!(b.tags, vec!["rust"]);

        assert!(idx.get("c.md").is_none());
    }

    #[test]
    fn scanned_index_sections_and_tasks() {
        let (_tmp, files) = setup_vault();
        let build = ScannedIndex::build(&files, None, &ScanOptions { scan_body: true }).unwrap();
        let a = build.index.get("a.md").unwrap();

        // a.md has 2 sections: Introduction and Tasks
        assert_eq!(a.sections.len(), 2);
        assert_eq!(a.sections[0].heading.as_deref(), Some("Introduction"));
        assert_eq!(a.sections[1].heading.as_deref(), Some("Tasks"));

        // a.md has 2 tasks
        assert_eq!(a.tasks.len(), 2);
        assert!(!a.tasks[0].done);
        assert!(a.tasks[1].done);
    }

    #[test]
    fn scanned_index_link_graph() {
        let (_tmp, files) = setup_vault();
        let build = ScannedIndex::build(&files, None, &ScanOptions { scan_body: true }).unwrap();
        let graph = build.index.link_graph();

        // a.md links to b, b.md links to a
        let a_backlinks = graph.backlinks("a");
        assert!(!a_backlinks.is_empty());
        let b_backlinks = graph.backlinks("b");
        assert!(!b_backlinks.is_empty());
    }

    #[test]
    fn scanned_index_outbound_links() {
        let (_tmp, files) = setup_vault();
        let build = ScannedIndex::build(&files, None, &ScanOptions { scan_body: true }).unwrap();
        let a = build.index.get("a.md").unwrap();

        // a.md has one outbound link: [[b]]
        assert_eq!(a.links.len(), 1);
        assert_eq!(a.links[0].1.target, "b");
    }

    #[test]
    fn scanned_index_skips_broken_frontmatter() {
        let tmp = tempfile::tempdir().unwrap();
        fs::write(
            tmp.path().join("good.md"),
            md!(r"
---
title: Good
---
Content.
"),
        )
        .unwrap();
        fs::write(
            tmp.path().join("bad.md"),
            "---\n: invalid yaml [[[{\n---\nContent.\n",
        )
        .unwrap();

        let files = vec![
            (tmp.path().join("good.md"), "good.md".to_owned()),
            (tmp.path().join("bad.md"), "bad.md".to_owned()),
        ];
        let build = ScannedIndex::build(&files, None, &ScanOptions { scan_body: true }).unwrap();
        assert_eq!(build.index.entries().len(), 1);
        assert_eq!(build.warnings.len(), 1);
        assert_eq!(build.warnings[0].rel_path, "bad.md");
    }

    #[test]
    fn scanned_index_modified_is_iso8601() {
        let (_tmp, files) = setup_vault();
        let build = ScannedIndex::build(&files, None, &ScanOptions { scan_body: true }).unwrap();
        let a = build.index.get("a.md").unwrap();
        assert!(
            a.modified.contains('T') && a.modified.ends_with('Z'),
            "unexpected timestamp: {}",
            a.modified
        );
    }

    #[test]
    fn snapshot_roundtrip() {
        let (_tmp, files) = setup_vault();
        let build = ScannedIndex::build(&files, None, &ScanOptions { scan_body: true }).unwrap();
        let index = &build.index;

        let snap_dir = tempfile::tempdir().unwrap();
        let snap_path = snap_dir.path().join(".hyalo-index");

        SnapshotIndex::save(index, &snap_path, "/tmp/vault", None).unwrap();
        let loaded = SnapshotIndex::load(&snap_path)
            .unwrap()
            .expect("snapshot should deserialize");

        assert_eq!(loaded.entries().len(), index.entries().len());
        let a = loaded.get("a.md").unwrap();
        assert_eq!(a.tags, vec!["rust", "cli"]);
        assert_eq!(a.properties.get("status").unwrap(), "draft");
        assert_eq!(a.sections.len(), 2);
        assert_eq!(a.tasks.len(), 2);
        assert_eq!(a.links.len(), 1);
        assert_eq!(a.links[0].1.target, "b");

        // Link graph survives roundtrip
        let bl = loaded.link_graph().backlinks("a");
        assert!(!bl.is_empty());
    }

    #[test]
    fn scanned_index_skip_body() {
        let (_tmp, files) = setup_vault();
        let build = ScannedIndex::build(&files, None, &ScanOptions { scan_body: false }).unwrap();
        assert!(build.warnings.is_empty());
        let idx = &build.index;

        // Frontmatter is still populated
        let a = idx.get("a.md").unwrap();
        assert_eq!(a.tags, vec!["rust", "cli"]);
        assert_eq!(a.properties.get("status").unwrap(), "draft");

        // Body fields are empty
        assert!(a.sections.is_empty());
        assert!(a.tasks.is_empty());
        assert!(a.links.is_empty());

        // Link graph is empty
        assert!(idx.link_graph().backlinks("a").is_empty());
        assert!(idx.link_graph().backlinks("b").is_empty());
    }
}